// JavaScript Document

// BROWSER & STYLE DETECTION
var browsertype, styletype;
var browser = navigator.userAgent;
if(browser.indexOf("MSIE") != -1){
	// Figure out if it's IE6/7/8 - I've already forced IE8 to display as IE8 above using the meta tag so you can pick up the browser version here
	if(browser.indexOf("; MSIE 8") != -1){
		// using IE 8 - can use standards compliant DOM methods
		browsertype = "ie8";
		styletype = "gen";
	} else if(browser.indexOf("; MSIE 7") != -1 || browser.indexOf("; MSIE 6") != -1){
		// Using IE 6/7
		browsertype = "ie";
		styletype = "ie";
	} else{
		// default catch-all for older browsers
		browsertype = "ie";
		styletype = "ie";
	}
} else{
	browsertype = "gen";
	styletype = "gen";
}
// !BROWSER & STYLE DETECTION

/* AJAX CONSTRUCTOR */
function AJAXInteraction(){
	// constructor
	var req = init();
	if(req == null){
		alert("Your browser does not have AJAX support - cannot process updates.");
	} else{
		req.onreadystatechange = processRequest;
	}

	function init(){
		try{
			return new XMLHttpRequest();
		} catch(e){
			var flag = false;
			var ajaxRequest = null;
			var domObj = ["MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
			for(var a = 0; a < domObj.length; a++){
				if(flag == false){
					try{
						ajaxRequest = new ActiveXObject(domObj[a]);
						if(ajaxRequest != null){
							flag = true;
							ajaxRequest = null;
							break;
						}
					} catch(e){
						continue;
					}
				}
			}
			if(flag != false){
				return new ActiveXObject(domObj[a]);
			} else{
				return null;
			}
		}
	}

	function processRequest(){
		if(req.readyState == 4){
			if(req.status == 200){
				if(req.responseText != "SUCCESS"){
					alert("There was a problem with your petition entry.\n\n" + req.responseText);
					document.getElementById("whatpetitionload").style.display = "none";
					document.getElementById("whatpetition").style.display = "block";
					return;
				} else{
					document.ewt.reset();
					document.getElementById("whatpetitionload").style.display = "none";
					document.getElementById("whatpetitionsuccess").style.display = "block";
				}
				req = null;
			}
		}
	}

	this.doGet = function(url, params){
		req.open("GET", "" + url + "?" + params, true);
		req.send(null);
	}

	this.doPost = function(url, params){
		document.getElementById("whatpetition").style.display = "none";
		document.getElementById("whatpetitionload").style.display = "block";
		req.open("POST", "" + url + "", true);
		req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		req.setRequestHeader("Content-length", params.length);
		req.setRequestHeader("Connection", "close");
		req.send(params);
	}
}
/* !AJAX CONSTRUCTOR */

/* HELP LIST FUNCTIONS */
var activelistitem = null;

function showHelpListItem(tgtitem){
	if(activelistitem === null){
		$("#helplistholder_" + tgtitem + "").animate({
			height:	"+" + document.getElementById("helplistcontent_" + tgtitem + "").offsetHeight + "px"
		}, "fast");
		activelistitem = tgtitem;
	} else if(activelistitem != tgtitem){
		$("#helplistholder_" + activelistitem + "").animate({
			height:	"-" + document.getElementById("helplistcontent_" + activelistitem + "").offsetHeight + "px"
		}, "fast", function(){
			$("#helplistholder_" + tgtitem + "").animate({
				height:	"+" + document.getElementById("helplistcontent_" + tgtitem + "").offsetHeight + "px"
			}, "fast");
		});
		activelistitem = tgtitem;
	} else if(activelistitem == tgtitem){
		$("#helplistholder_" + activelistitem + "").animate({
			height:	"-" + document.getElementById("helplistcontent_" + activelistitem + "").offsetHeight + "px"
		}, "fast");
		activelistitem = null;
	}
	return;
}
/* END HELP LIST FUNCTIONS */

/* PETITION FORM VALIDATION FIELDS */
var submitcount = 0;

function checkTextLength(textbox){
	textParam = textbox.value.replace(/^\s*|\s*$/g, "");
	if(textParam){
		textWords = textParam.split(/\s+/);
		if(textWords.length > 500){
			alert("You are only allowed 500 words, please limit your comments.");
			textboxnewvalue = "";
			for(var i = 0; i < 500; i++){
				textboxnewvalue = textboxnewvalue + " " + textWords[i];
			}
			textbox.value = textboxnewvalue;
		} else{
			document.getElementById("charcount").value = (500 - textWords.length);
		}
	}
	return;
}

function trim(str){
    return str.replace(/^\s+|\s+$/g,'');
}

function isEmail(str){
    var regex = /^[-_.a-z0-9]+@(([-a-z0-9]+\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i;
    return regex.test(str);
}

function validatePetition(fobj){
	if(submitcount > 0){
		alert("Please allow a few moments for the form to submit");
	} else{
		var errorstring = "";
		var paramstring = "";
		if(fobj.fname.length == 0 || (trim(fobj.fname.value) == "" || fobj.fname.value == ""))
			errorstring += "-&nbsp;your first name<br />";
		else
			paramstring += "firstname=" + fobj.fname.value + "";
		if(fobj.sname.length == 0 || (trim(fobj.sname.value) == "" || fobj.sname.value == ""))
			errorstring += "-&nbsp;your surname<br />";
		else
			paramstring += "&surname=" + fobj.sname.value + "";
		if(fobj.email.length == 0 || (trim(fobj.email.value) == "" || fobj.email.value == "") || !isEmail(fobj.email.value))
			errorstring += "-&nbsp;a valid email address<br />";
		else
			paramstring += "&email=" + fobj.email.value + "";
		if(fobj.dontdisplayname.checked != false)
			paramstring += "&displayname=" + fobj.dontdisplayname.value + "";
		else
			paramstring += "&displayname=y";
		if(fobj.country.length != 0 || (trim(fobj.country.value) == "" || fobj.country.value == ""))
			paramstring += "&country=" + fobj.country.value + "";
		else
			paramstring += "&country=";
		if(fobj.comments.length != 0 || (trim(fobj.comments.value) == "" || fobj.comments.value == ""))
			paramstring += "&comments=" + escape(fobj.comments.value) + "";
		else
			paramstring += "&comments=";
		if(errorstring != ""){
			paramstring = "";
			var errorframe = {
        		player:     "html",
        		content:    "<div class=\"errordisplay\"><div class=\"errorcontent\">Please tell us the following details:<br /><br /><dl><dd>" + errorstring + "</dd></dl></div></div>",
				width:		250,
				height:		150
    		};
			Shadowbox.open([errorframe]);
		} else if(paramstring != "" && errorstring === ""){
			submitcount++;
			var ai = new AJAXInteraction();
			ai.doPost("services/sign_petition.php", paramstring);
		}
	}
	return false;
}
/* END PETITION FORM VALIDATION FIELDS */

/* SHARE VALIDATION FIELDS */
var submitemailcount = 0;

function validateShare(fobj){
	if(submitemailcount > 0){
		alert("Please allow a few moments for the form to submit");
	} else{
		var errorstring = "";
		var paramstring = "";
		var tostring = "";
		if(fobj.from.length == 0 || (trim(fobj.from.value) == "" || fobj.from.value == "") || !isEmail(fobj.from.value))
			errorstring += "-&nbsp;your valid email address<br />";
		else
			paramstring += "from=" + trim(fobj.from.value) + "";
		if(fobj.to.length == 0 || (trim(fobj.to.value) == "" || fobj.to.value == "")){
			errorstring += "-&nbsp;the email address/addresses you would like to send to<br />";
		} else{
			if(fobj.to.value.indexOf(",") != -1){ // Check if there are commas to seperate multiple values
				toarray = fobj.to.value.split(",");
				for(var i = 0; i < 100; i++){
					if(toarray[i]){
						if(!isEmail(trim(toarray[i]))){
							errorstring += "-&nbsp;" + trim(toarray[i]) + " is not a valid email address<br />";
						} else{
							if(tostring != "")
								tostring += "," + trim(toarray[i]) + "";
							else
								tostring += "" + trim(toarray[i]) + "";
						}
					} else{
						break;
					}
				}
				paramstring += "&to=" + tostring;
			} else{
				if(!isEmail(trim(fobj.to.value)))
					errorstring += "-&nbsp;" + trim(fobj.to.value) + " is not a valid email address<br />";
				else
					paramstring += "&to=" + trim(fobj.to.value) + "";
			}
		}
		if(fobj.message.length != 0 || (trim(fobj.message.value) == "" || fobj.message.value == ""))
			paramstring += "&message=" + escape(fobj.message.value) + "";
		else
			paramstring += "&message=";
		if(errorstring != ""){
			paramstring = "";
			var errorframe = {
        		player:     "html",
        		content:    "<div class=\"errordisplay\"><div class=\"errorcontent\">Please tell us the following details:<br /><br /><dl><dd>" + errorstring + "</dd></dl></div></div>",
				width:		350,
				height:		250
    		};
			Shadowbox.open([errorframe]);
		} else if(paramstring != "" && errorstring === ""){
			submitemailcount++;
			var ai = new AJAXInteraction();
			ai.doPost("services/share.php", paramstring);
		}
	}
	return false;
}
/* END SHARE VALIDATION FIELDS */

var commentsInterval = null;

function commentScroll(){
	var commenttarget = null;
	var commentcount = 0;
	var commentslist = document.getElementById("commentlist");
	for(var c = 0; c < commentslist.childNodes.length; c++){
		if(commentslist.childNodes.item(c).nodeName === "LI"){
			if(commenttarget === null)
				commenttarget = commentslist.childNodes.item(c);
			commentcount++;
			continue;
		} else{
			continue;
		}
	}
	if(commenttarget != null){
		$("#" + commenttarget.id + "").fadeOut("slow", function(){
			var commentclone = commenttarget.cloneNode(true);
			var currentcomment = document.getElementById(commenttarget.id);
			currentcomment.parentNode.removeChild(currentcomment);
			commentslist.appendChild(commentclone);
			if(browsertype === "gen" || browsertype === "ie8"){
				var style = commentclone.getAttribute("style");
				commentclone.setAttribute("style", style.replace(/display: none;/gi, ""));
			} else{
				commentclone.style.display = "block";
			}
		});
	}
}
