// JavaScript Document


var processComplete = false;
var beginProcess;
var widthComplete;
var defaultSearchString = 'Search ';
var defaultEmailString = 'Enter your email ';


setActions = function()
{

	closelists();
	
	ieUser = getInternetExplorerVersion();
	if (ieUser != -1){
		if (ieUser < 6){
				alert("Sorry, you have an old version of Internet Explorer which means you can't view this site properly.  Please visit http://www.microsoft.com/ie to upgrade your version of Internet Explorer or use another compatible browser, such as Firefox or Safari."); 
		}
	}
	
	DoWidth();
	
	DoProcess();
	if (processComplete)
	{
		clearTimeout(beginProcess); 
	}
	else
	{
		beginProcess = window.setTimeout(setActions, 15000);
	}

}

/*  
Start of FORM STRIPPER code

This function pre-processes all the input and textarea fields on the page and clears them when they're first selected (once only).

This function allows you to put placeholder text in input and textarea places in order to comply with AAA accessibility requirements, but to retain usability for typical users. 

To make fields 'immune' from this process you should set their class to "prefilled".

*/
function DoProcess() {
	if (processComplete) return;
	if (document.forms) {
		// Iterate forms
		formsCollection = document.forms;
		for(i=0; i<formsCollection.length; i++)
		{
			// Iterate Element
			elementsCollection = formsCollection[i].elements;
			for(j=0; j<elementsCollection.length; j++)
			{
				node = elementsCollection[j];
				if (node.nodeName == "INPUT" && ((node.type == "text" &&  !/prefilled/.test(node.className)) || (node.type == "password" &&  !/prefilled/.test(node.className))))
				{
					if (node.value == "...") {
						node.value=""
					}
					// if 
					node.onfocus = function() {
						this.value= "" ;
						this.onfocus = function(){
							// Unset The onFocus event for this object
							return false;
						}
					}
				}
				else if (node.nodeName == "TEXTAREA" && node.readOnly == false && !/prefilled/.test(node.className))
				{
					if (node.value == "...") {
						node.value="";
					}
					node.onfocus = function() {
						//alert(this.defaultValue);
						this.defaultValue = "";
						this.value = "";
						this.onfocus = function(){
							// Unset The onFocus event for this object
							return false;
						}
					}
				}
			}
		}
	}
	processComplete = true;
}
/*  
End of FORM STRIPPER code
*/


/* 
Start of FORM CHECKER code
*/
function checkForm(formID) {
	var fieldnames = Array();
	fieldnames['realname'] = 'Your name';
	fieldnames['book-title'] = 'Proposed title';
	fieldnames['synopsis'] = 'Synopsis';
	fieldnames['email'] = 'Your email address';
	fieldnames['mailinglist'] = 'Your email address';
	fieldnames['mail'] = 'Your postal address';
	fieldnames['experience'] = 'Your experience';
	fieldnames['comments'] = 'Your comments';
	fieldnames['address'] = 'Your address';
	fieldnames['name'] = 'Your name';
	fieldnames['recipient'] = 'Your friend\'s email address';
	fieldnames['subject'] = 'Message subject';
	fieldnames['message'] = 'Message to send';
	fieldnames['postcode'] = 'Your zip/post code';
	fieldnames['country'] = 'Your country';
	fieldnames['captcha'] = 'Anti-spam question';
	
	missingFields = ""
	badEmail = 0
	badCaptcha = 0
	submitForm = 1
	if (document.forms) {
		// Iterate Element
		elementsCollection = document.getElementById(formID).elements;
		for(j=0; j<elementsCollection.length; j++)
		{
			node = elementsCollection[j];
			
			// Check if any required fields are missing
			if (/required/.test(node.className) && (node.value == "" || node.value == "..."))
			{
				var text = node.id;
				if (fieldnames[node.id]) text = fieldnames[node.id];
				
				if (missingFields == "")
				{
					missingFields = text;
				}
				else
				{
					missingFields = missingFields + ", " + text;
				}
				// Don't submit the form
				submitForm = 0
			}
			
			// Check to see if required email addresses have been filled in AND are correctly formatted
			else if (/email-req/.test(node.className)){
				/* Check if email exists */
				if (node.value == "" || node.value == "...")
				{
					var text = node.id;
					if (fieldnames[node.id]) text = fieldnames[node.id];
					
					if (missingFields == "")
					{
						missingFields = text;
					}
					else
					{
						missingFields = missingFields + ", " + text;
					}
					// Don't submit the form
					submitForm = 0
				}
				else
				{
					var str = node.value; // email string
					
					var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
					var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{1,4}|[0-9]{1,4})(\]?)$/; // valid
					
					if (!reg1.test(str) && reg2.test(str)) 
					{
						// Email is valid, so do nothing
					}
					else
					{
						// Email is invalid
						badEmail = 1
						// Don't submit the form
						submitForm = 0
					}
				}
			}
			
			// Check to see if non-required email addresses are correctly formatted
			else if (/email-nonreq/.test(node.className)){
				/* Check if email field has been filled in */
				if (node.value != "" && node.value != "...")
				{
					var str = node.value; // email string
					
					var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
					var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{1,4}|[0-9]{1,4})(\]?)$/; // valid
					
					if (!reg1.test(str) && reg2.test(str)) 
					{
						// Email is valid, so do nothing
					}
					else
					{
						// Email is invalid
						badEmail = 1
						// Don't submit the form
						submitForm = 0
					}
				}
			}
			
			// Check to see if required country has been filled in
			else if (/country-req/.test(node.className)){
				/* Check if a country has been selected */
				if (node.options[node.selectedIndex].value == "" || node.options[node.selectedIndex].value == "...")
				{
					var text = node.id;
					if (fieldnames[node.id]) text = fieldnames[node.id];
					
					if (missingFields == "")
					{
						missingFields = text;
					}
					else
					{
						missingFields = missingFields + ", " + text;
					}
					// Don't submit the form
					submitForm = 0
				}
			}


			// Captcha
			else if(/captchaAnswer/.test(node.className)) {
				if(node.value == "") {
					var text = node.id;
					if(fieldnames[node.id]) {
						text = fieldnames[node.id];
					}
					if(missingFields == "") {
						missingFields = text;
					} else {
						missingFields = missingFields + ", " + text;
					}
					// Don't submit the form
					submitForm = 0;
				} else {
					var ajax = null;
					if(window.XMLHttpRequest) {              
						ajax = new XMLHttpRequest();              
					} else if(typeof ActiveXObject != "undefined") {                                  
						ajax = new ActiveXObject("Microsoft.XMLHTTP");
					}
					if(ajax != null) {
						ajax.open("POST", "/res/captcha.php", false);
						ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
						ajax.send("captchaAnswer=" + node.value);
						var captcha = ajax.responseText;
						if(captcha == "bad") {
							badCaptcha = 1;
							submitForm = 0;
						}
					}
				}
			}


		}
		
		// Create the error message
		
		if (missingFields != "")
		{
			missingFields = "Sorry, you have missed one or more required fields.\n\nThe fields you missed are: " + missingFields
		}
		
		if (missingFields == "" && badEmail != 0)
		{
			missingFields = "Sorry, appear to have entered an incorrect email address."
		}
		else if (missingFields != "" && badEmail != 0)
		{
			missingFields = missingFields + "\n\nYou also appear to have entered an incorrect email address."
		}

		if (missingFields == "" && badCaptcha != 0)
		{
			missingFields = "Sorry, appear to have entered an incorrect answer for the anti-spam question."
		}
		else if (missingFields != "" && badCaptcha != 0)
		{
			missingFields = missingFields + "\n\nYou also appear to have entered an incorrect answer for the anti-spam question."
		}
		
		if (missingFields != "")
		{
			alert (missingFields)	
		}
	}
	if (submitForm != 1)
	{
		// don't submit the form if there are missing or invalid elements
		return false;
	}

}
/*
End of FORM CHECKER code
*/

/* 
Start of SEARCH FORM CHECKER code
Checks search form isn't blank or "Search" is filled in (ie effectivly blank)
*/
function searchCheck(fieldID) {
	
	submitForm = 1
		
	searchstring = document.getElementById(fieldID).value;
	
	// If the search string is empty or is 'Search' (ans so hasn't been touched)
	if (searchstring == '' || searchstring == defaultSearchString){
		
		// Tell the user
		alert ("Sorry, you haven't searched for anything.  Please type something into the search box and try again.");
		
		// don't submit the form if there are missing or invalid elements
		return false;
	}
	
}

/* 
Drop down resizer IE
This function resizes the books dropdown in IE (note: the CSS only affects IE) 
03/JAN/06: Also gets rid of 'go' button in all browsers
*/
function DoWidth() {
	if (document.getElementById("go-1")){
		var isfocussed = 0;
		var isdone = 0;
		var noexpand = 0;
	
		dropdown0 = document.getElementById("explore_list");
		var thisdrop = "explore_list";
	
		
		if(document.getElementById("go-1")){
			go0 = document.getElementById("go-1");
		}
		
		myWide = "wide";
		
		if (!dropdown0){
			dropdown0 = document.getElementById("book_search");
			myWide = "wide2";
			thisdrop = "book_search";
		}
		
		if (!dropdown0){
			dropdown0 = document.getElementById("explore_list_2");
			myWide = "wide3";
			thisdrop = "explore_list_2";
		} 
		
		if (!dropdown0){
			dropdown0 = document.getElementById("book_sort");
			thisdrop = "book_sort";
			noexpand = 1;
		} 
		
		dropdown0.className = "scripton";
		
		go0.className = "hide";
		
		if (!go0) {
			go0 = document.getElementById("");
		}
		
		var lastfunction = 'go';
		var currentVal = dropdown0.value;
	
		var parentElementHeight = (dropdown0.parentElement)?(dropdown0.parentElement.offsetHeight - 12):(-1);
		
		if (dropdown0 && ieUser != -1 && noexpand == 0){
			
			dropdown0.onactivate = function() {
			    
			    this.className = myWide;
				isfocussed = 1;
				isdone = 0;
				lastfunction = 6;
				if(parentElementHeight != -1 && thisdrop == "book_search"){this.parentElement.style.height = parentElementHeight;}
			}
			
			dropdown0.onmouseover = function() {
			    if (lastfunction == 10){
					lastfunction = 0;
					try{go0.focus();}catch(e){}
				}
				this.className = myWide;
				if (isfocussed == 1){
					//isdone++;
					lastfunction = 5;
				}
				lastfunction = 4;
				if(parentElementHeight != -1 && thisdrop == "book_search"){this.parentElement.style.height = parentElementHeight;}
			}
	
			dropdown0.ondeactivate = function() {
			    this.className = "scripton-narrow";
			    this.blur();
				isfocussed = 0;
				isdone = 0;
				lastfunction = 3;
			}
			
			dropdown0.onblur = function() {
				isdone++;
			}
			
			dropdown0.onchange = function() {
				this.className = "scripton-narrow";
				if (dropdown0.value != currentVal && dropdown0.value != "" && dropdown0.value != "All books"){
					var tmpdrop = dropdown0.value;
					var toblur = document.getElementById(thisdrop);
					toblur.blur();
					//document.location.href = tmpdrop;
					document.getElementById("book_search_form").submit();
				}
				this.blur();
				isfocussed = 1;
				isdone++;
				//try{go0.focus();}catch(e){}
				lastfunction = 7;
			}
			
			dropdown0.onmouseout = function() {
				if (isfocussed == 0){
					this.className = "scripton-narrow";
					this.blur();
					isdone = 0;
					isfocussed = 0;
					lastfunction = 2;
				} else if (isfocussed == 1 && isdone != 0){
					this.className = "scripton-narrow";
					this.blur();
					isdone = 0;
					lastfunction = 1;
				} else if (isfocussed == 1 && isdone == 0){
					lastfunction = 10;
				}
			}
		} else {
			// For Non IE users
			dropdown0.onchange = function() {
				if (dropdown0.value != currentVal && dropdown0.value != "" && dropdown0.value != "All books" && dropdown0.value != "Category"){
					//document.location.href = dropdown0.value;
					document.getElementById("book_search_form").submit();
				}
			}
		}
	}
}
/* 
End of drop down resizer IE
*/



/*
Close lists
Pre-closes all lists when page opens
*/

function closelists(){

	i = 1
	while (i <= 100)
	{
		plus= "plus-" + i;
		if (!document.getElementById(plus)){break;}
		plusName = document.getElementById(plus);
		plusName.className = "on-plus";
		
		chapter = "chapter-list-" + i;
		chapterName = document.getElementById(chapter);
		chapterName.className = "off";
		i++;
	}
}

/*
End close lists
*/


/*
Expand lists
This applies to contents lists on In Detail page
*/


function showchapter(whichChapter) {
	
	chapter = "chapter-list-" + whichChapter;
	chapterName = document.getElementById(chapter);
	
	if(chapterName.className != "off"){
		chapterName.className = "off";
	} else {
		chapterName.className = "on";
	}
	
	plus = "plus-" + whichChapter;
	plusName = document.getElementById(plus);
	
	if(plusName.src.indexOf("icon_plus.gif") == -1){
		plusName.src = "../../images/icon_plus.gif";
	} else {
		plusName.src = "../../images/icon_minus.gif";
	}
	
}

/*
End expand lists
*/


/*
IE Browser detect from MSDN.com
*/

function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
  var rv = -1; // Return value assumes failure
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}

/*
End IE browser detect
*/

/* 
Start of MAILING LIST FORM CHECKER code
Checks search form isn't blank or "Enter your email" is filled in (ie effectivly blank)
Also checks email address is valid
*/
function mailingListCheck(fieldID) {
	
	submitForm = 1
		
	emailstring = document.getElementById(fieldID).value;
	
	// If the search string is empty or is 'Search' (ans so hasn't been touched)
	if (emailstring == '' || emailstring == defaultEmailString){
		
		// Tell the user
		alert ("Sorry, you have not entered your email address.");
		
		// don't submit the form if there are missing or invalid elements
		return false;
	} else {
		var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
		var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{1,4}|[0-9]{1,4})(\]?)$/; // valid
		
		if (!reg1.test(emailstring) && reg2.test(emailstring)) 
		{
			// Email is valid, so do nothing
		}
		else
		{
			// Tell the user
			alert ("Sorry, you have entered an incorrect email address.");
			
			// Don't submit the form
			return false;
		}
	}
	
}


window.onload=setActions;