function tinyPopup(inPage, inSubpage, inArgs) {
	window.open("/popup/" + inPage + "/" + inSubpage + "/?" + inArgs, "", "location=0,menubar=0,scrollbars=1,status=0,toolbar=0,width=400,height=550,resizable=1,dependent=1,centerscreen=1");
}

/**
 * Checks a users email against database
 * 
 * @param email - the email associated to this account
 */
function emailCheck(email) {

	if (email == "") {

		document.getElementById("submit").disabled=true;
		return;
	}

	if (window.XMLHttpRequest) {
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	} else {// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}

	xmlhttp.onreadystatechange=function()
	{
		if (xmlhttp.readyState==4 && xmlhttp.status==200)
		{
			if (xmlhttp.responseText=="-1") {

				document.getElementById("emailerrormessage").style.display = "none";	
				document.getElementById("emailerrormessage").innerHTML="";				
				document.getElementById("submit").disabled = false;
			} else {
				document.getElementById("emailerrormessage").style.display = "table-row";	
				document.getElementById("emailerrormessage").innerHTML="This email address is unavailable, please contact us should you require assistance.";
				document.getElementById("submit").disabled = true;
			} 
		}
	};
	xmlhttp.open("POST","/library/webshop/usercheck.php?email="+email, true);
	xmlhttp.send();
}


/**
 * Checks for modifications to the cart since the last load
 * 
 * @param time - check the time of the last page load against modifications
 * @param target - where to go to if it is accepted
 */
function cartModificationCheck(time, target) {

	if (window.XMLHttpRequest) {
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	} else {// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}

	xmlhttp.onreadystatechange=function()
	{
		if (xmlhttp.readyState==4 && xmlhttp.status==200)
		{			
			if (xmlhttp.responseText=="notmodified") {				
				navLink(target);
			} else {
				document.getElementById("error").innerHTML="There was a modification to your cart since this page was loaded. " +
						"Please refresh to ensure that latest version of your cart is correct." +
						"<img src='/images/overview/error.png' style='vertical-align: middle;'>";
			} 
		}
	};
	xmlhttp.open("POST","/library/webshop/modificationcheck.php?pagedate="+time, true);
	xmlhttp.send();
}

/**
 * Checks for modifications to the cart since the last load
 * 
 * @param time - check the time of the last page load against modifications
 * @param payment method - paypal, payone, or voucher
 */
function checkoutModificationCheck(time, paymentmethod) {

	if (window.XMLHttpRequest) {
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	} else {// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}

	xmlhttp.onreadystatechange=function()
	{
		if (xmlhttp.readyState==4 && xmlhttp.status==200)
		{			
			if (xmlhttp.responseText=="notmodified") {				
				if (paymentmethod=="paypal") {
					document.paypalform.submit();
				} else if (paymentmethod=="payone") {
					payViaPayOne();
				} else if (paymentmethod=="voucher") {
					document.voucherpaymentform.submit();
				} else {
					alert(paymentmethod);
					document.getElementById("error"+paymentmethod).innerHTML="Error with payment!";
				}
			} else {
				document.getElementById("error"+paymentmethod).innerHTML=
					"There was a modification to your cart since this page was loaded. " +
					"Please go back your <a href='/webshopviewcart/'>cart</a> to ensure your order is correct." +
					"<img src='/images/overview/error.png' style='vertical-align: middle;'>";
			} 
		}
	};
	xmlhttp.open("POST","/library/webshop/modificationcheck.php?pagedate="+time, true);
	xmlhttp.send();
}


/**
 * Checks to see if it is possible to proceed or not
 * @param cart
 * @param target
 */
function checkCart(cart, target, loadtime) {

	// check for valid cart
	if (cart.length>0) {
		// if the modification check is ok		
		cartModificationCheck(loadtime, target);
	} else {
		document.getElementById("error").innerHTML="Please ensure your cart is not empty before continuing!";
	}

}


/**
 * Deletes webshop account
 */
function deleteAccount() {
	if (confirm("Are you sure you want to delete your account?")) {
		document.forms['contentform'].elements["action"].value     = "deleteaccount";
		document.forms['contentform'].submit();
	}
}

/** 
 * Alters between having an account and requiring a password and not
 */
function accountChange(check) {
		
	if (check.checked) {
		
		document.getElementById("passwordrow1").style.display = "table-row";
		document.getElementById("passwordrow2").style.display = "table-row";

		document.getElementById("password1").required = "1";
		document.getElementById("password2").required = "1";

	} else {
		document.getElementById("password1").removeAttribute("required");
		document.getElementById("password2").removeAttribute("required");
		
		document.getElementById("passwordrow1").style.display = "none";
		document.getElementById("passwordrow2").style.display = "none";

		
	}
}


function openNews( id ) {
	document.getElementById(id+'Control').innerHTML = "" +
	"<a href=\"javascript:closeNews("+id+");\">" +
	"<img src=\"/images/overview/opened.gif\"/>Hide news for this case</a>" +
	"&nbsp;&nbsp;|&nbsp;&nbsp;<a href=\"/cases/detail/?id="+id+"\">" +
	"<img src=\"/images/ecofact/link.gif\"/>" +
	"Go to this case</a>";
	showDiv(id);
}

function closeNews( id ) {
	document.getElementById(id+'Control').innerHTML = "" +
	"<a href=\"javascript:openNews("+id+");\">" +
	"<img src=\"/images/overview/closed.gif\"/>Show news for this case</a>"+
	"&nbsp;&nbsp;|&nbsp;&nbsp;<a href=\"/cases/detail/?id="+id+"\">" +
	"<img src=\"/images/ecofact/link.gif\"/>" +
	"Go to this case</a>";
	hideDiv(id);
}

/**
 * 
 * @param id
 */
function addtobasket(id) {


	document.getElementById("added"+id).innerHTML="<img src=\"/images/overview/ajax-loader.gif\">";

	if (window.XMLHttpRequest) {
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	} else {// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}

	xmlhttp.onreadystatechange=function()
	{
		if (xmlhttp.readyState==4 && xmlhttp.status==200)
		{
			document.getElementById("added"+id).innerHTML=xmlhttp.responseText;
			// update total if appropriate
			if (document.getElementById("totalprice")!=null) {

				document.getElementById("totalprice").innerHTML="<img src=\"/images/overview/ajax-loader.gif\">";
				if (window.XMLHttpRequest) {
					// code for IE7+, Firefox, Chrome, Opera, Safari
					xmlhttp2=new XMLHttpRequest();
				} else {// code for IE6, IE5
					xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
				}

				xmlhttp2.onreadystatechange=function()
				{
					if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
					{
						document.getElementById("totalprice").innerHTML=xmlhttp2.responseText;
					}
				};

				xmlhttp2.open("POST","/library/webshop/total.php");
				xmlhttp2.send();
			}
		}
	};
	xmlhttp.open("POST","/library/webshop/basket.php?id="+id+"&action=add");
	xmlhttp.send();


}

function removefrombasket(id, resubmit) {

	document.getElementById("added"+id).innerHTML="<img src=\"/images/overview/ajax-loader.gif\">";
	if (window.XMLHttpRequest) {
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	} else {// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}

	xmlhttp.onreadystatechange=function()
	{
		if (xmlhttp.readyState==4 && xmlhttp.status==200)
		{
			document.getElementById("added"+id).innerHTML=xmlhttp.responseText;
			if (resubmit) {
				location.reload(true);
			}
		}
	};	

	xmlhttp.open("POST","/library/webshop/basket.php?id="+id+"&action=remove");
	xmlhttp.send();

}

/**
 * Take an entity and add it to a certain watchlist
 * @param id
 * @param watchlist
 * @param type
 * @param userteam
 * @param userid
 */
function addtowatchlist(id, watchlist, type, userteam, userid) {

	if (watchlist == "") {

		document.getElementById("added").innerHTML="<img title=\"Invalid watchlist\" src=\"/images/overview/state-0.gif\">";
		return;
	}


	document.getElementById("added").innerHTML="<img src=\"/images/overview/ajax-loader.gif\">";

	if (window.XMLHttpRequest) {
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	} else {// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}

	xmlhttp.onreadystatechange=function()
	{
		if (xmlhttp.readyState==4 && xmlhttp.status==200)
		{
			document.getElementById("added").innerHTML=xmlhttp.responseText;
		}
	};
	xmlhttp.open("POST","/library/overview/addtowatchlist.php?w="+watchlist+"&i="+id+"&t="+type+"&ut="+userteam+"&u="+userid, true);
	xmlhttp.send();


}

function removefromwatchlist(id, watchlist, type, userteam, userid) {

	if (watchlist == "") {

		document.getElementById("added").innerHTML="<img title=\"Invalid watchlist\" src=\"/images/overview/state-0.gif\">";
		return;
	}


	document.getElementById("added").innerHTML="<img src=\"/images/overview/ajax-loader.gif\">";

	if (window.XMLHttpRequest) {
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	} else {// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}

	xmlhttp.onreadystatechange=function()
	{
		if (xmlhttp.readyState==4 && xmlhttp.status==200)
		{
			document.getElementById("added").innerHTML=xmlhttp.responseText;
		}
	};
	xmlhttp.open("POST","/library/overview/removefromwatchlist.php?w="+watchlist+"&i="+id+"&t="+type+"&ut="+userteam+"&u="+userid, true);
	xmlhttp.send();


}

function showDiv( id ) { 
	document.getElementById(id).style.display = 'block'; 
	document.getElementById(id).focus(); 

} 
function hideDiv( id ) { 
	document.getElementById(id).style.display = 'none';
}

function showBankersDiv() {
	showDiv("bankersDiv");
	hideDiv("assetmanagersDiv");
	hideDiv("supplychainmanagersDiv");
	hideDiv("internationalsDiv");
}

function showAssetManagersDiv() {
	showDiv("assetmanagersDiv");
	hideDiv("bankersDiv");
	hideDiv("supplychainmanagersDiv");
	hideDiv("internationalsDiv");
}

function showSupplyChainManagersDiv() {
	hideDiv("bankersDiv");
	hideDiv("assetmanagersDiv");
	showDiv("supplychainmanagersDiv");
	hideDiv("internationalsDiv");
}

function showInternationalsDiv() {
	hideDiv("bankersDiv");
	hideDiv("assetmanagersDiv");
	hideDiv("supplychainmanagersDiv");
	showDiv("internationalsDiv");
}


//Form checking ---------------------------------------------------------------
function formCheck(inFormId, inErrorField, inErrorMessage) {

	// Get form
	var formObj = document.getElementById(inFormId);

	// Init state
	var emailpattern  = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
	var allowSubmit   = true;
	var radioCheckbox = [];

	if (document.getElementById("password1").required) {
		if (document.getElementById("password1").value!=document.getElementById("password2").value) {
			// Get label field & possible format
			var labelField = document.getElementById(document.getElementById("password2").getAttribute("label")); 
			allowSubmit &= false;
			if (labelField) labelField.className = "errormessage";
		}
	}

	// Loop over all fields
	for (var i=0; i<formObj.elements.length; i++) {

		// Check if that field is required
		if (formObj.elements[i].getAttribute("required") == 1) {

			// Get label field & possible format
			var labelField = document.getElementById(formObj.elements[i].getAttribute("label"));  
			var format     = formObj.elements[i].getAttribute("format");  

			// Switch by tag type
			switch (formObj.elements[i].tagName) {

			case "select": // Multiple select is not implemented
			case "SELECT":
				var selectedIndex = formObj.elements[i].options.selectedIndex;
				var selectedValue = formObj.elements[i].options[selectedIndex].value;

				if (selectedValue.length > 0) {
					allowSubmit &= true;
					if (labelField) labelField.className = "";
				} else {
					allowSubmit &= false;
					if (labelField) {
						labelField.className = "errormessage";
					} 
				}
				break;

			case "input":
			case "INPUT":
				switch (formObj.elements[i].type) {

				case "checkbox":
				case "radio":
					// Create entry for radio / checkbox
					radioCheckbox[formObj.elements[i].name] = (radioCheckbox[formObj.elements[i].name])?(radioCheckbox[formObj.elements[i].name]):(false);

					// If checked, override value with true
					if (formObj.elements[i].checked) {
						radioCheckbox[formObj.elements[i].name] |= true;
					}
					break;

				case "file":
					break;

				case "text":
				case "hidden":
				case "submit":
				default:
					if ((formObj.elements[i].value.length > 0) && ((format=="email")?(emailpattern.test(formObj.elements[i].value)):(true))) {
						allowSubmit &= true;
						if (labelField) labelField.className = "";
					} else {
						allowSubmit &= false;
						if (labelField) labelField.className = "errormessage";
					}
				break;
				}
				break;

			case "textarea":
			case "TEXTAREA":
			default:
				if (formObj.elements[i].value.length > 0) {
					allowSubmit &= true;
					if (labelField) labelField.className = "";
				} else {
					allowSubmit &= false;
					if (labelField) labelField.className = "errormessage";
				}
			break;
			}
		}
	}

	// Post-process radio / checkbox (error hilighting for radios & checkboxes is not implemented)
	for (fieldName in radioCheckbox) {
		allowSubmit &= radioCheckbox[fieldName];
	}

	// Set error message
	if (!allowSubmit) {
		document.getElementById(inErrorField).innerHTML     = inErrorMessage;
		document.getElementById(inErrorField).style.display = "inline";
	} else {
		document.getElementById(inErrorField).innerHTML     = "";
		document.getElementById(inErrorField).style.display = "none";
	}

	// Return result anyway
	return allowSubmit;
}

//Userguide handling ----------------------------------------
function userguide(inUrl) {
	window.open(inUrl, "", "location=0,menubar=0,scrollbars=1,status=0,toolbar=0,width=800,height=540,resizable=1");
}

//Print handling --------------------------------------------
function printVersion() {
	window.open("/print" + location.pathname + location.search, "", "location=0,menubar=0,scrollbars=1,status=0,toolbar=0,width=800,height=600,resizable=1");
}

//Popup -----------------------------------------------------------------------
function popup(inPage, inSubpage, inArgs) {
	window.open("/popup/" + inPage + "/" + inSubpage + "/?" + inArgs, "", "location=0,menubar=0,scrollbars=1,status=0,toolbar=0,width=800,height=600,resizable=1,dependent=1,centerscreen=1");
}

//Image swapping --------------------------------------------
function imageSwap(inObj, toSrc) {
	inObj.src = toSrc;
}


//Navigation handling ---------------------------------------
function navRollOver(inObj) {
	if (inObj.className == "navigationHeader")
		inObj.className = "navigationHeaderOver";
	else
		inObj.className = "navigationItemOver";
}

function navRollOut(inObj) {
	if (inObj.className == "navigationHeaderOver")
		inObj.className = "navigationHeader";
	else
		inObj.className = "navigationItem";
}

function navLink(inUrl) {
	location.href = inUrl;
}


//Tooltips -------------------------------------------------
var tooltip_obj     = null;
var tooltip_content = null;

function tooltip_init(tooltipId, contentId) {
	tooltip_obj     = document.getElementById(tooltipId);
	tooltip_content = document.getElementById(contentId);
}

function tooltip_show(event, message) {

	if (tooltip_obj && message) {
		if (self.event) {
			x  = self.event.clientX;
			y  = self.event.clientY;

			self.event.cancelBubble = true;
		} else {
			x  = event.clientX;
			y  = event.clientY;

			event.stopPropagation();
		}

		tooltip_content.innerHTML = message;
		tooltip_obj.style.display = "block";

		tooltip_obj.style.top =  y - tooltip_content.offsetHeight - 15 + document.body.scrollTop;
		tooltip_obj.style.left = x - 163 + document.body.scrollLeft;

	}
	return false;
}

function tooltip_hide() {
	if (tooltip_obj) {
		tooltip_content.innerHTML = "";
		tooltip_obj.style.top = 0;
		tooltip_obj.style.left = 0;
		tooltip_obj.style.display = "none";
	}
	return false;
}


//Emails --------------------------------------------------
function mailto(inEmail) {
	location.href="mailto:" + reverse(inEmail);
}

function reverse(inText) {
	var outText = "";
	for (var i=inText.length-1; i>=0; i--) {
		outText+= inText.substr(i,1);;
	}
	return outText;
}


//Form checking ------------------------------------------
function checkForm(inForm, inFields, inMessage) {

	var complete = true;
	for (var i=0; i<inFields.length; i++) {
		complete &= (inForm.elements[inFields[i]].value.length > 0);
	}

	if (!complete) {
		document.getElementById("formMessage").innerHTML = inMessage;
		return false;
	} else {
		return true;
	}
}


//Dynamic data loading -----------------------------------
var serverPresent   = location.hostname;
var requestQueue    = [];
var request         = null;
var requestTarget   = 0;
var requestCallback = "";
var requestRunning  = false;
function distributeContent() {
	if (request.readyState == 4) {
		if (request.status == 200 || !serverPresent) {

			// Javascript transfer hack
			if (request.responseText.indexOf("javascript:") === 0) {
				eval(request.responseText.substr(11));
			} else {
				var targetObj = document.getElementById(requestTarget);
				targetObj.innerHTML = request.responseText;
			}

			// Invoke callback
			if (requestCallback) {
				eval(requestCallback);
			}

			// Reset request state
			requestRunning = false;
			loadContent();
		}
	}
}

function loadContent() {

	// Check wheter a request is running
	if (!requestRunning && requestQueue.length) {

		// Lock requesting
		requestRunning = true;

		// Get last queued request
		var thisRequest = requestQueue.shift();
		var inUrl       = thisRequest[1];
		var inTargetId  = thisRequest[0];
		var inCallback  = thisRequest[2];

		// Load last queue
		requestTarget   = inTargetId;
		requestCallback = inCallback;
		if (window.XMLHttpRequest) {
			request = new XMLHttpRequest();
		} else if (window.ActiveXObject) {
			request = new ActiveXObject("Microsoft.XMLHTTP");
		}
		request.open("GET", inUrl, true);
		request.onreadystatechange = distributeContent;
		request.send(null);
	}
}

function queueContent(inTargetId, inUrl, inCallback) {
	// Queue the request
	requestQueue.push([inTargetId, inUrl, inCallback]);

	// Load last queue
	loadContent();
}


