var xmlHttpReq=null;
var g_validationTargets=new Array();		//contains ids of input controls
var g_busy=false;

///////////////////////////////////////////////////////////
function remspace(input)
{
	if(input==null || input.value==null) return '';
	var x=input.value.replace(new RegExp("\\s","g"),"");
	return x;

}

function trim(val)
{

	var x=val.replace(new RegExp("^\\s+"),'');
	var y=x.replace(new RegExp("\\s+$"),'');
	return y;

}
function validateNumber(input)
{
	var text=remspace(input);
	var re=new RegExp('(^£){0,1}[0-9]+([\.][0-9]+){0,1}$');
	var b=text.match(re);

	return b !=null;
}

function validateText(input)
{

	var b=remspace(input)!='';


	return b;

}

function validateDate(input)
{
	var text=remspace(input);
	var re=new RegExp('[0-9]{1,2}/[0-9]{1,2}/[0-9]{2,4}$');

	var b=text.match(re);

	return b!=null;
}

function validateEmail(input)
{
	var text=remspace(input);
	var re=new RegExp('[A-Z0-9._%-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}',"i");
	var b=text.match(re);
	return b !=null;
}
function validatePhone(input)
{
	var text=remspace(input);
	var re=new RegExp('[0-9]+');
	var b=text.match(re);
	b=b!=null && text.length>9;
	return b;
}

function validatePostcode(input)
{

	//Use text validation for now
	return validateText(input);
}


function formPostData(formId)
{
	var form=document.getElementById(formId);
	var txt='';
	var touchedRadios=new Object();

	for(var i=0;i<form.length;i++)
	{

		if(form.elements[i].name ==null || form.elements[i].name =='')
			continue;

		var val='';

		//Radio buttons require special handling
		//so do them and normal cases separately
		if(form.elements[i].type!='radio')
		{

			//treat as a normal case and get the value
			val=trim(form.elements[i].value);



		}
		else if(!touchedRadios[form.elements[i].name])
		{

			val='';
			//Go though all radio buttons with the same name
			//until the first checked one is encountered
			var radioGroup=form[form.elements[i].name];
			for(var iGroup=0; iGroup < radioGroup.length; iGroup++)
			{
				if(radioGroup[iGroup].checked)
				{
					//alert(radioGroup[iGroup].id + ' ' + radioGroup[iGroup].checked);
					val=trim(radioGroup[iGroup].value);
					break;
				}
			}
			//ensure we do this once only
			touchedRadios[form.elements[i].name]=true;
		}

		//add POST data entry. Ignore blanks
		if(val=='') 	continue;
		if(i>0)txt=txt + "&";
		txt=txt +  form.elements[i].name + '=' + val;
	}


	return txt;
}

function prosessCompletion(response)
{
	if(response.indexOf("Ok:")==0)
	{
		var caseRef=response.substr(3);
		document.location.href='case_created.php?caseid=' + caseRef;
		return true;
	}
	return false;
}

function HttpReq()
{
	//firefox, et al
	var xmlReq;
	if(window.XMLHttpRequest)
	{
		xmlReq=new XMLHttpRequest();
		//xmlReq.overrideMimeType("text/xml");
	}
	//IE
	else if(window.ActiveXObject)
	{
		xmlReq=new ActiveXObject("Microsoft.XMLHTTP");
	}

	return xmlReq;
}

function DocElement(objOrName)
{
	if(typeof objOrName === 'string')
	{
		divName=objOrName;
		return document.getElementById(objOrName);
	}
	return objOrName;
}

function IsOk(responseString)
{
	var s=trim(responseString).toUpperCase();
	return s=="OK:";
}

function OnResponseRecvd()
{
	if(xmlHttpReq.readyState==4)
	{
		//alert(xmlHttpReq.responseText);

		if(xmlHttpReq.status==200)
		{
			if(IsOk(xmlHttpReq.responseText))
			{
				document.location.reload(true);
				return;
			}

		}
	//	if(!prosessCompletion(xmlHttpReq.responseText))
			//alert(xmlHttpReq.responseText);
	}
}

function SubmitAction(formId)
{


	var rand=Math.random() + new Date().getTime() ;

	var form=document.getElementById(formId);

	//alert('Validating ' + formId);
	//if(!validator.Validate())
	//	return false;

	var formData=formPostData(formId);
	//alert(formData);

	 xmlHttpReq=	HttpReq();

	xmlHttpReq.open('POST','do_action.php?'+rand,true);
	xmlHttpReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xmlHttpReq.onreadystatechange=OnResponseRecvd;
	xmlHttpReq.send(formData);

}

function OnAddedCartItem()
{
	if(xmlHttpReq.readyState==4)
	{
		//alert(xmlHttpReq.responseText);

		if(xmlHttpReq.status==200)
		{
			//Ok:\s*(\d+(.\d+)*)
			var ms=xmlHttpReq.responseText.match(/Ok:\s*Amount=\s*(\d+(.\d+)*)/);

			if(ms)
			{
				val=ms[1];
				//alert(val);
				var tot=document.getElementById('basket_total');
				tot.innerHTML='&pound;' + parseFloat(val).toFixed(2);
			}
			else
			{
				//alert(" Unknown Response " + xmlHttpReq.responseText);
				alert("Error");
			}

		}
		//else
			//alert('Status: ' + xmlHttpReq.status + "; Text: " + xmlHttpReq.responseText);
	//	if(!prosessCompletion(xmlHttpReq.responseText))


	}
}

function validateInputs()
{
	//go thru array
	var bAllValid=true;
	for(i=0;i<g_validationTargets.length; i++)
	{

		var inputId=	g_validationTargets[i];
		var errDiv=document.getElementById(inputId + "_Error");
		var input=document.getElementById(inputId);
		if(input==null || errDiv==null) continue; //ignore if info is missing

		//get input type and validate
		var dataType=input.getAttribute("datatype");
		var bInvalid=false;
		if(dataType=="email")
		{
			 bInvalid=!validateEmail(input);
		}
		else if(dataType=="number")
		{
			 bInvalid=!validateNumber(input);
		}
		else if(dataType=="postcode"  )
		{
			 bInvalid=!validatePostcode(input);
		}
		else
		{
			//Default to text
			 bInvalid=!validateText(input);
		}

		//alert(inputId + ' is ' + dataType + ' and invalid=' +bInvalid);
		if(bInvalid)
		{
			errDiv.style.display="inline-block";
			bAllValid=false;
		}

	}


	return bAllValid;
}

function  clearErrors()
{
	//go thru array
	for(i=0;i<g_validationTargets.length; i++)
	{

		var inputId=	g_validationTargets[i];
		var errorDiv=document.getElementById(inputId + "_Error");
		if(errorDiv)
			errorDiv.style.display="none";
	}
}
function SubmitShopAction(formId,nextPage,errorCallback,callBack)
{

	if(IsBusy())
	{
		alert('Currently busy with an earlier request\r\nPlease wait for the request to complete.');
		return;
	}

	SetBusy(true);

	var rand=Math.random() + new Date().getTime() ;

	var form=document.getElementById(formId);
	clearErrors();
	if(!validateInputs())
	{
		//alert('Invalid inputs');
		return false;
	}

	//alert('Validating ' + formId);
	//if(!validator.Validate())
	//	return false;

	var formData=formPostData(formId);
	//alert(formData);

	 xmlHttpReq=	HttpReq();

	xmlHttpReq.open('POST','ajax_methods.php?'+rand,true);
	xmlHttpReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xmlHttpReq.onreadystatechange=function(){OnAjaxResponse(nextPage,errorCallback,callBack);};
	xmlHttpReq.send(formData);
	return true;

}

function CallPage(url,callBack)
{


	if(url.match(/\?/))
		url=url+ "&" + Rand();

	else
		url=url+"?" + Rand();



	xmlHttpReq=	HttpReq();

	xmlHttpReq.open('GET',url,true);
	xmlHttpReq.onreadystatechange=function(){OnAjaxResponse(null,null,callBack);};
	xmlHttpReq.send("");

}
/*
function SubmitQueryStringAction(qry)
{


	var rand=Math.random() + new Date().getTime() ;


	//alert(qry + "&" +rand);

	xmlHttpReq=	HttpReq();

	xmlHttpReq.open('GET','ajax_methods.php?'+qry + "&" +rand,true);
	//xmlHttpReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xmlHttpReq.onreadystatechange=OnAjaxResponse;
	xmlHttpReq.send(null);

}
*/

function OnAjaxResponse( nextPage,errorCallback,callBack)
{
	SetBusy(false);
	if(xmlHttpReq.readyState==4)
	{


		if(xmlHttpReq.status==200)
		{
			var resp=xmlHttpReq.responseText;
			var ms=resp.match(/Ok:\s*Cmd=\s*(\w+)/);
			if(!ms)
			{
				//	alert(" Unknown Response " + resp);
				Goto('error.php');

				return;
			}

			if(callBack!=null)
			{
				callBack(resp);
				return;
			}


			cmd=ms[1];
			if(cmd=="ADDCART")
			{
				Goto('basket.php?');

			}

			else if(cmd=="REMOVECART")
			{

				Goto('basket.php?');
			}
			else if(cmd=="UPDATECARTQTY")
			{
				Goto('basket.php?');
			}


			else if(cmd== "SAVEPSHOPPINGCUSTOMER")
			{
				if(nextPage)
				{
					Goto(nextPage);
				}
			}


			else if(cmd== "STARTORDER")
			{
			//	alert(resp);
				ms=resp.match(/\OrderId=\s*(\w+)/);
				if(ms)
				{
				//	alert('Order Id is ' + ms[1]);

					var paypalForm=document.getElementById("paypalForm");
					paypalForm['custom'].value=ms[1];
					//Submit paypal form here

					document.getElementById("paypalForm").submit();

					//send to the order view page to wait for completion
					//Goto(nextPage);
					//$nextPage="order_view.php?o="+ms[1];
					//alert($nextPage);
					// setTimeout("Goto('" + $nextPage +"')",5000); //Mimmick send for now
				}
			}

			else if(cmd=="CHECKSTOCK")
			{
		//		alert(resp);
				ms=resp.match(/\InStock=\s*(\w+)/);
				if(ms)
				{
					if(ms[1]=="Yes")
						Goto(nextPage);
					else
						Goto("order_stock_level.php");
				}
			}

			else if(cmd=="REGISTERCUSTOMER")
			{
					Goto(nextPage);

			}
			else if(cmd== "SAVEPREORDEREMAIL")
			{
				if(nextPage)
				{
					Goto(nextPage);
				}
			}
			else if (cmd=="STARTPREORDERCUSTOMERREGISTRATION")
			{
					ms=resp.match(/Error/);
				if(ms)
				{
					errorCallback(resp);
				}
				else
				{
					Goto(nextPage);
				}
			}
			else if(cmd=="LOGINSHOPPINGCUSTOMER")
			{
				ms=resp.match(/LoggedIn=\s*(\w+)/);
				if(ms && ms[1]=="1")
				{
					Goto(nextPage);
				}
				else
				{
					//TODO Display Login failed on screen
					errorCallback(resp);
				}

			}
			else if(cmd== "SETSHIPPINGOPTION")
			{
				if(nextPage)
				{
					Goto(nextPage);
				}
			}
			else if(cmd== "LOGOUTSHOPPER")
			{
				if(nextPage)
				{
					Goto(nextPage);
				}
			}
			else
			{
				//alert("Cmd returned Ok, but failed \r\nError : [Nextpage: " + nextPage + "]\r\n" +xmlHttpReq.responseText);
			}

		}
		else
		{
			//alert("Errror : [Nextpage: " + nextPage + "]\r\n" +xmlHttpReq.responseText);

			//alert("Error");
		}
	}
}
function SubmitNamedAction(formId,actionName)
{
	//For is assumed to have an input named "action"
	//Find the input and set the action name
	actionInput=document.getElementById("action");
	if(actionInput==null)
	{
		//alert('No action element found in form ' + formId);
		alert("Error");
		return;
	}

	actionInput.value=actionName;
	//Delegate submission
	SubmitAction(formId);
}

function SwapDivDisplay(divToDisplay, divToHide)
{
	DocElement(divToDisplay).style.display='block';
	DocElement(divToHide).style.display='none';
}

function Rand()
{
	return Math.random() + new Date().getTime() ;
}
function Goto(url)
{
	if(url.match(/\?/))
		url=url+ "&" + Rand();
	else
		url=url+"?" + Rand();

	document.location.href=url;
	//window.open(url,"_self",null,false);
}

function GotoPost(url)
{
	//Get or create post form
	var frm=document.getElementById("__PostForm");
	var referrerInp;
	if(frm==null)
	{
		//create form and add to document
		frm=document.createElement("Form");
		frm.setAttribute("id","__PostForm");
		frm.setAttribute("name","__PostForm");
		frm.method="POST";
		document.body.appendChild(frm);

		//var sub=document.createElement("input");
		//sub.type="submit";
		//frm.appendChild(sub);

	//	alert('Form created ' + frm);

		//include an input for the calling page's url
		referrerInp=document.createElement("input");
		referrerInp.setAttribute("name","referrer");
		referrerInp.setAttribute("type","hidden");
		referrerInp.setAttribute("id","referrer");
		frm.appendChild(referrerInp);
		//alert('referrer created ' + document.getElementById("referrer"));
	}

	//Include the sender
	referrerInp=document.getElementById("referrer");
	//alert(referrerInp);
	referrerInp.value=document.location;


	//Append query and submit
	if(url.match(/\?/))
		url=url+ "&" + Rand();
	else
		url=url+"?" + Rand();

	frm.action=url;
	//alert(url + " referrer is " +referrerInp.value);
	frm.submit();
}

function Back()
{
	//check current page is from the same url root

var ref=document.referrer;
	var here=document.location.href;
	var mRef=ref.match(/(http|https):\/\/[^\/]+/);
	var mHere=here.match(/(http|https):\/\/[^\/]+/);
	//alert(document.referrer + '\r\n' + mHere[0]); return;
	if(mRef!=null && mHere!=null && mRef[0]==mHere[0])
	{

		document.location.href=document.referrer;
	}
	else
	{

		document.location.href='shop.php';
	}

}
function SecureRelativeUrlRoot()
{
	//Get the full relative url root with the https protocol.
	//e.g http://mysite/page.html will return https://mysite
	http://mysite/subdir/page.html will return https://mysite/subdir
	var pos=location.href.lastIndexOf("/");
	if(pos==-1) pos=location.href.length;
	var sslUrl=location.href.substr(0,pos);
	sslUrl=sslUrl.replace(/http:/i,"https:");
	return sslUrl;
}

function BrowserLog(str)
{
	var win=window.open("", "plmv_brws","height=200,width=500,status=yes,toolbar=no,menubar=no,location=no,resizable=yes,scrollbars=yes");
	var dt=new Date();
	win.document.writeln(dt.toString() + "- " + str + "<br/>");
}



function ValidateEmailAndPassword(bValidatePwd)
{
	var email=document.getElementById("po_email");
	if(!email)email=document.getElementById("cu_email");
	if(!email)email=document.getElementById("email");
	var bValid=true;
	if(validateEmail(email)==false)
	{
		document.getElementById("invalidEmail").style.display='block';
		bValid=false;
	}

	var pwd=document.getElementById("pwd");

	if(bValidatePwd && pwd.value=="")
	{
		document.getElementById("badPassword").style.display='block';
		bValid=false;
	}

	return bValid;
}

function SetBusy(bBusy)
{
	g_busy=bBusy;
}

function IsBusy()
{
	return g_busy;
}
