
//displays the quickfind dropdown
function showPopup() {
  document.getElementById("quickfind_dropdown").style.display = 'block';
}

//reveals a comment/reply spoiler
function showSpoiler(elementid,parentid) {
  document.getElementById(elementid).style.display = 'block';
  document.getElementById(parentid).style.display = 'none';
}

//used to be used by the quickfind dropdown, may not be needed now
function showHide(elementid, displaytype) {
  if(!displaytype) {
    displaytype = 'block';
  }
  var stat = document.getElementById(elementid).style.display;
  if(stat == 'none' || stat == '') {
    document.getElementById(elementid).style.display = displaytype;
  }
  else {
    document.getElementById(elementid).style.display = 'none';
  }
}

//clears the contents of an input text field if passed the id
function clearField(theElement) {
  theElement.value = "";
}

//switches between the two views on the community main page
function communityTopicSwitch() {
  showHide('recent');
  showHide('hot');
}

//expands the main table on the community page
function communityTopicExpand() {
  showHide('hidden_recent','table');
  showHide('hidden_hot','table');
  var link = document.getElementById("communityTopicExpand");
  if(link.innerHTML == "More hot topics") {
    link.innerHTML = "Less hot topics";
  }
  else {
    link.innerHTML = "More hot topics";
  }
}

//selects all text inside an element when that element is clicked on
function selectAll(id) {
    document.getElementById(id).focus();
    document.getElementById(id).select();
}

//given a URL to an image and a target element id of an image, will change that image
//used on an onclick event on detectives page to replace main image with thumbnails
function imageChange(newimage,imgtarget,newtext,texttarget,copytext) {
  var oldimage = document.getElementById(imgtarget);
  var oldtext = document.getElementById(texttarget);
  if(oldimage) {
    oldimage.src = newimage;
  }
  if(oldtext) {
    oldtext.innerHTML = newtext + "<br/>" + copytext;
  }
}

//registration area
//finds a list of regions based on selection in the country select box
function changeRegions(id_country,id_region,limit_to_populated) {
  //fetch required data from the backend
	var ajaxRequest;
	//Opera 8.0+, Firefox, Safari
	try{ajaxRequest = new XMLHttpRequest();} catch (e){
		//Internet Explorer Browsers
		try{ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");} catch (e) {
			try{ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");} catch (e){
        return false; // Something went wrong
			}
		}
	}
	//receive data sent from the server
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
      var returned = ajaxRequest.responseText;
      var regions = JSON.decode(returned,true);
      var temp1;
      var nvalue;
      var nname;
      var output;
      var option;
      document.getElementById(id_region).innerHTML = "<option value=\"0\"> -- select region -- </option>"; //clear the options from the select box (IE)
      document.getElementById(id_region).innerHTML = ""; //both these lines are necessary for it to work in IE

      option = document.createElement('option');
      option.innerHTML = " -- select region -- ";
      option.value = "0";
      document.getElementById(id_region).appendChild(option);

      for(x in regions) {
        if (regions.hasOwnProperty(x)) {
          temp1 = regions[x];
          if(temp1) {
            nvalue = temp1["id"];
            nname = temp1["region"];
            //stupid workaround to make this work in stupid IE
            option = document.createElement('option');
            option.innerHTML = nname;
            option.value = nvalue;
            document.getElementById(id_region).appendChild(option);
          }
          output += "<option value=\"" + nvalue + "\">" + nname + "</option>";
        }
      }
    }
  }

  //process sending request
  var slug = document.getElementById(id_country).value;
  if(slug != 0) {
    if(!limit_to_populated) {
      ajaxRequest.open("GET", "/country/regions/" + slug + "/", true);
    }
    else {
    	ajaxRequest.open("GET", "/map/country-regions/" + slug + "/", true);
    }
  	ajaxRequest.send(null);
  }
  else {
    document.getElementById(id_region).innerHTML = "<option value=\"0\"> -- select region -- </option>"; //clear the options from the select box (IE)
    document.getElementById(id_region).innerHTML = ""; //both these lines are necessary for it to work in IE

    option = document.createElement('option');
    option.innerHTML = " -- select region -- ";
    option.value = "0";
    document.getElementById(id_region).appendChild(option);
  }
}

//called from manage personal details page to set the user's region in the dropdown box
function setRegion(current_region) {
    var i = 0;
    var region_select = document.getElementById('id_region');

    for (i=0; i<region_select.options.length; i++) {
      if (region_select.options[i].value == current_region) {
  			region_select.selectedIndex = i;
  		}
    }
}


/*
function isValidEmail(str) {
   return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}

function urlencode(str) {
str = escape(str);
str = str.replace('+', '%2B');
str = str.replace('%20', '+');
str = str.replace('*', '%2A');
str = str.replace('/', '%2F');
str = str.replace('@', '%40');
return str;
}

function urldecode(str) {
str = str.replace('+', ' ');
str = unescape(str);
return str;
}

*/
/**************************************
Spans news window
**************************************/
/*
var popup = {
    init: function(){
		var pops = $$('.popup');
		pops.each(function(pop){
			pop.addEvent('click', function(e){
				new Event(e).stop();
				var url = pop.getProperty('href');
				window.open(url);
			});
		});
	}
}

var popup_strict = {
    init: function(){
		var pops = $$('.popup-strict');
		pops.each(function(pop){
			pop.addEvent('click', function(e){
				new Event(e).stop();
				var url = pop.getProperty('href');
				window.open(url, 'window', "status=no,toolbar=no,menubar=no,location=no");
			});
		});
	}
}

var popupWidget = {
    init: function(){
		var pops = $$('.popup-widget');
		pops.each(function(pop){
			pop.addEvent('click', function(e){
				new Event(e).stop();
				var url = pop.getProperty('href');
				window.open(url);
			});
		});
	}
}
*/
/**************************************
Form.autosubmit
hides submit button
autosubmit select input on change
1.2.4 compilant
*************************************/
/*
var autosubmit = {
    init: function(){
        var autosubmit = $$('.autosubmit');
        $each(autosubmit,function(inner_form,index){
            var submit_button = inner_form.getElement('li.submit');
            submit_button.setStyle('display','none')
            var input_select = inner_form.getElements('select');
            input_select.addEvent('change',function(){
                inner_form.submit();
            });
        });
    }
}
*/
/**************************************
Clear the field on click
1.2.4 Compilant
**************************************/
/*
var clearfield = {
    init: function(){
        var message = 'Email Address';
        var clearfields = $$('.clearfield');
        $each(clearfields,function(field,index){
            this.tmp = field.getAttribute('value');
            var message = this.tmp;
            field.addEvent('focus',function(e){
                this.replaced = field.getProperty('value');
                if (field.getProperty('value') == message){
                    field.setProperty('value','');
                }
            });
            field.addEvent('blur', function(){
                if (this.replaced == message && field.getProperty('value') == ''){
                    field.setProperty('value', message);
                }
            });
        });
    }
}

var search_header = {
    init: function(){
        var search_form = $('form_search_header');
        if(search_form){
            var submit_button = search_form.getElement('button');
            submit_button.addEvent('click',function(e){
                if($('q2_id').value.toLowerCase() == 'search' ){
                    $('q2_id').value = ''
                }
            });
        }
    }
}
*/
/**************************************
Replaces images
in the character page
**************************************/
/*
var gallery = {
    init: function(){
        var images = $$('.gallery');
        $each(images,function(image,index){
            image.addEvent('click',function(e){
                new Event(e).stop();
                var container = $('gallery_container');
                container.setStyle('overflow','hidden');
                var description_bits = image.getAttribute('title').split('. Copyright: ')
                var paragraph_footer = new Element('p');
                paragraph_footer.setHTML(description_bits[0]);
                $('gallery_container_footer').empty();
                paragraph_footer.injectInside('gallery_container_footer');
                if(description_bits.length == 2){
                    var paragraph_cr = new Element('p',{
                            'class': 'copyright'
                        });
                    var copyright_text = 'Copyright: ' +description_bits[1];
                    paragraph_cr.setHTML(copyright_text);
                    paragraph_cr.injectInside('gallery_container_footer');
                }
                container_s = container.getSize();
                container.setStyle('height', container_s.size.y);
                var images = [image.getAttribute('href')]
                var loader = new Asset.images(images, {
                                    onComplete: function(){
                                        images.each(function(img){
                                            var gallery_image = new Element('img',{
                                                'src': img,
                                                'class': 'current_image'
                                            });
                                            container.empty();
                                            container.adopt(gallery_image);
                                            image_s = gallery_image.getSize();
                                            var containerFX = new Fx.Styles(container, {duration: 500, transition: Fx.Transitions.Quad.easeIn});
                                            containerFX.start({'height': image_s.size.y})
                                        });
                                    }
                                });
                container.empty();
                var loading_img = new Element('img',{
                        'src': '/site-media/img/base/ajax-loader.gif',
                        'styles': {'height':32, width:32}
                    });
                container.adopt(loading_img);
            });
        });
    }
}
*/
/**************************************
Preserves email while reading TnC
**************************************/
/*
var tnc_email = {
    init: function(){
        var email_input = $('id_email')
        if(email_input){
            email_input.addEvent('change',function(e){
                email = email_input.value;
                var linked = $$('.data_linked');
                $each(linked,function(link,index){
                    if(isValidEmail(email)){
                        tmp_link = link.getAttribute('href');
                        link.setAttribute('href',tmp_link+'?e='+urlencode(email))
                    }
                });
            });
            var location = window.location.href;
            location_bits = location.split('?')
            if(location_bits.length == 2){
                email_bits = location_bits[1].split('=');
                email_input.setAttribute('value',urldecode(email_bits[1]));
            }
        }


    }
}
*/
/************************************************************************
Creates tooltips with images for wish list items
************************************************************************/
/*
var tooltipper = {
    init: function(){

    	//create the tips, with our custom classname
    	var t = new Tips('.product-tip',{
            className: 'product-tip-detail',
            maxTitleChars: 20
            }
        );
    }
}
*/

/************************************************************************
Make reading list and wish list buttons AJAXified
************************************************************************/

/*
var listtoggles = {
    init: function(){

        $$('.list-toggle').each( //for all items classed list-toggle
            function setup(f) {
                f.addEvent('submit', function(e) { //add a submit handler

                    new Event(e).stop(); // stop the non-AJAX post from happening

                    new Element('input', { //on submit, add a hidden field that shows this was a list-toggle POST (required on server side)
                        type:'hidden',
                        name:'list_toggle',
                        value:true
                    }).inject(this);
                    this.set('send', {
                        onRequest: function(){
                            this.getParent().getChildren().addClass('storing'); //can add classes
                        }.bind(this),
                        onComplete: function(r) {
                            (function(){ //wrapping function so we can use delay()
                                wrapping_td = this.getParent(); //get what's holding the form
                                if(wrapping_td != null){
                                     this.getParent().getChildren().removeClass('storing');
                                      wrapping_td.innerHTML = r; //fill it with the new form, back via AJAX
                                      setup(wrapping_td.getElement('form')); //remember to set up a new event listener on it
                                  }
                             }).delay(750, this);
                        }.bind(this)
                    });
                    this.send();
                    //this.send({
                        // onRequest: function(){
                        //     this.getParent().getChildren().addClass('storing'); //can add classes
                        //     console.log(this.getParent().getChildren());
                        // }.bind(this),

                        // onComplete: function(r) {
                        //     (function(){ //wrapping function so we can use delay()
                        //         wrapping_td = this.getParent(); //get what's holding the form
                        //         if(wrapping_td != null){
                        //              this.getParent().getChildren().removeClass('storing');
                        //              wrapping_td.innerHTML = r; //fill it with the new form, back via AJAX
                        //              setup(wrapping_td.getElement('form')); //remember to set up a new event listener on it
                        //          }
                        //     }).delay(750, this);
                        // }.bind(this)
                     //bind() is used so that the onComplete method has access to the specific
                     //element that invoked, so we can update that calling elementhan
                   // });
                })
            }
        );
    }
};

*/
/************************************************************************
nice, usable alert box to warn users of amazon possibly deleting their basket
************************************************************************/
/*
var checkoutWarning = {
    init: function(){
        $$('p.shopping-list-actions a.buy').each(
            function(f){
                f.addEvent('click', function(e){
                    alert("Please be aware that once you add items to your cart on amazon's site, amazon will automatically remove those items from your Agatha Christie shopping list.");
                });
            }
        );
    }
};

*/

/********************
Pop up widgets
 ******************/
/*
var widgets = {
    init: function(){
        var elements = $$('.widget');
        elements.addEvent('click', function(e){
                new Event(e).stop();
                var url = this.getProperty('href');
                var openPopup = new Browser.Popup(url ,{
                        width: 830,
                        height: 630
                    });
            });
    }
};



window.addEvent('domready', function(){
        popup.init();
        popup_strict.init();
        popupWidget.init();
        autosubmit.init();
        clearfield.init();
        gallery.init();
        tnc_email.init();
        search_header.init();
        tooltipper.init();
        listtoggles.init();
        checkoutWarning.init();
        widgets.init();
    });
*/
