
///////////////////////////
//  account area functions
///////////////////////////

function SelectTab(name)
{
	var elt = document.getElementById(name);
	if (!elt) return;
	var eltstyle = elt.style;	
	eltstyle.backgroundColor="#995feb";
	eltstyle.color="#FFFFFF";
	eltstyle.fontWeight="bold";
}
function UnSelectTab(name)
{
	var elt = document.getElementById(name);
	if (!elt) return;
	var eltstyle = elt.style;	
	eltstyle.backgroundColor="";
	eltstyle.color="";
	eltstyle.fontWeight="";
}
function OnShowView(responseText,OnShowFunc)
{
	var okPatt = /^OK\t((?:.|\n|\r)*)/m;
	var errorPatt = /^ERROR\t((?:.|\n|\r)+)/m;
	var loginerrorPatt = /^LOGINERROR\t((?:.|\n|\r)+)/m;
	if (loginerrorPatt.test(responseText))
	{
		location.href = '$SECSCRIPT_PATH?account=0&message=' + encodeURIComponent(RegExp.$1);
	}
	else if (errorPatt.test(responseText))
	{
		window.alert(RegExp.$1);
	}
	else if (okPatt.test(responseText))
	{
		document.getElementById("MainContent").innerHTML = RegExp.$1;
		if (OnShowFunc != null) {
			OnShowFunc();
		}
	}
	else
	{
		window.alert(responseText);
	}
	document.body.style.cursor="default";

}
function ShowView(name,command)
{
	document.body.style.cursor="wait";
	UnSelectTab('generalTab');
	UnSelectTab('addressTab');
	UnSelectTab('ordersTab');
	UnSelectTab('clientordersTab');
	if (name == null)
	{
		var data = getCookie('accountCommand');
		if (data != null && data != "")
		{
			data = data.split("\t");
			name = data[0];
			command = data[1];
		}
	}
	if (name == null)
	{
		name = "general";
		command = "command=general";
	}
	SelectTab(name+"Tab");
	setCookie("accountCommand", name + "\t" + command, null, "/");
	var viewclientorderPatt = /command=viewclientorder/m;
	var addressPatt = /command=address/m;
	if (viewclientorderPatt.test(command))
	{
		GetAjaxData("shopservices.pl?"+command,"",OnShowView,OnShowClientOrder,"MainContent");
	}
	else if (addressPatt.test(command))
	{
		GetAjaxData("shopservices.pl?"+command,"",OnShowView,OnShowAddress,"MainContent");
	}
	else
	{
		GetAjaxData("shopservices.pl?"+command,"",OnShowView,null,"MainContent");
	}   	
}
function ProcessCommand(responseText)
{
	var okPatt = /^OK\t((?:.|\n|\r)*)/m;
	var errorPatt = /^ERROR\t((?:.|\n|\r)+)/m;
	var loginerrorPatt = /^LOGINERROR\t((?:.|\n|\r)+)/m;
	if (loginerrorPatt.test(responseText))
	{
		location.href = '$SECSCRIPT_PATH?account=0&message=' + encodeURIComponent(RegExp.$1);
	}
	else if (errorPatt.test(responseText))
	{
		window.alert(RegExp.$1);
		return false;
	}
	else if (okPatt.test(responseText))
	{
		return true;
	}
	else
	{
		window.alert(responseText);
		return false;
	}
}
function OnFilterOrders(responseText)
{
	if (ProcessCommand(responseText))
	{
		document.getElementById('orderArea').innerHTML = RegExp.$1;
	}
	document.body.style.cursor="default";
}
function FilterOrders(pageno,parentArea)
{
	document.body.style.cursor="wait";
	var ordersPerPageObj = document.getElementById('ordersPerPage');
	var ordersPerPage = ordersPerPageObj.options[ordersPerPageObj.selectedIndex].text;
	GetAjaxData("shopservices.pl?command=getorderlist&search="+document.getElementById('orderSearch').value+"&pageno="+pageno+"&ordersPerPage="+ordersPerPage,"",OnFilterOrders,null,parentArea);
}
function FilterClientOrders()
{
	document.body.style.cursor="wait";
	GetAjaxData("shopservices.pl?command=getclientorderlist&search="+document.getElementById('orderSearch').value,"",OnFilterOrders,null,"orderSearchButtonArea");
}

function moneyFormat(input)
{
	var num = Math.round(input*100)/100;
	if (Math.round(input) == num)
	{
		return num+'.00';
	}
	else if (Math.round(input*10) == num*10)
	{
		return num+'0';
	}
	else
	{
		return num+'';
	}
}
function updateSums(idx)
{
	for (var i=0;document.getElementsByName("Item" + i)[0] !=null;i++)
	{
		if (idx >= 0 && idx != i) continue;
		var Qty = document.getElementsByName("Qty" + i)[0].value;
		var Price = document.getElementsByName("Price" + i)[0].value;
		var VatRate = document.getElementsByName("VatRate" + i)[0].value;
		if (Price != "")
		{
			document.getElementsByName("Price" + i)[0].value = moneyFormat(Price);
			if (Qty == "")
			{
				Qty=1;
				document.getElementsByName("Qty" + i)[0].value =Qty;
			}
		}
		if (Qty == "" || Price == "")
		{
			document.getElementsByName("VatAmt" + i)[0].value = "";
			document.getElementsByName("Amount" + i)[0].value = "";
		}
		else
		{
			if (VatRate == "")
			{
				VatRate=document.getElementsByName("DefaultVatRate")[0].value;
				document.getElementsByName("VatRate" + i)[0].value = VatRate;
			}
			var Amount =  moneyFormat(Qty*Price);
			var VatAmt =  moneyFormat(Amount*VatRate/100);
			document.getElementsByName("VatAmt" + i)[0].value = VatAmt;
			document.getElementsByName("Amount" + i)[0].value = moneyFormat(Amount);
		}
	}
	var SubTot = 0;
	var TotVat = 0;
	for (var i=0;document.getElementsByName("Item" + i)[0] !=null;i++)
	{
		var Amount = document.getElementsByName("Amount" + i)[0].value;
		var VatAmt = document.getElementsByName("VatAmt" + i)[0].value;
		if (Amount != "")
		{
			SubTot += 1*Amount;
			TotVat += 1*VatAmt;
		}
	}
	document.getElementsByName("SubTot")[0].value = moneyFormat(SubTot);
	document.getElementsByName("TotVat")[0].value = moneyFormat(TotVat);
	document.getElementsByName("GrandTotal")[0].value = moneyFormat(1*SubTot + 1*TotVat);
}
function HideOrShowNewBox(field,newfield)
{
	document.getElementsByName(newfield)[0].style.visibility = (document.getElementsByName(field)[0].selectedIndex == 1 ? "visible":"hidden");
}
function OnUpdateDefaultNameData(responseText)
{
	var data = responseText.split("\t");
	document.getElementsByName('Address')[0].value = data[0];
	document.getElementsByName('Email')[0].value = data[1];
}
function UpdateDefaultNameData(Type)
{
	var NameObj = document.getElementsByName('Name')[0];
	var AddressObj = document.getElementsByName('Address')[0];
	var EmailObj = document.getElementsByName('Email')[0];
	if (NameObj.selectedIndex<2)
	{
		AddressObj.value = "";
		EmailObj.value = "";
	}
	else
	{
		AddressObj.value = "loading ...";
		EmailObj.value = "loading ...";
		GetAjaxData("shopservices.pl?command=getDefaultNameData&Type="+Type+"&Name="+NameObj.value,"",OnUpdateDefaultNameData,null,"AddressContainer");
	}
}
function OnSaveDefaultAddress(responseText)
{
	window.alert(responseText);
}
function SaveDefaultAddress()
{
	var NameObj = document.getElementsByName('Name')[0];
	if (NameObj.selectedIndex>1 && confirm("would you like to update the Default Details for this contact?"))
	{
		var AddressObj = document.getElementsByName('Address')[0];
		var EmailObj = document.getElementsByName('Email')[0];
		GetAjaxData("shopservices.pl?command=saveDefaultAddress&Name="+NameObj.value+"&Address="+encodeURIComponent(AddressObj.value)+"&Email="+encodeURIComponent(EmailObj.value),"",OnSaveDefaultAddress,null,"AddressContainer");
	}
}
function OnUpdateDefaultVatRate(responseText)
{
	var DefaultVatRateObj = document.getElementsByName('DefaultVatRate')[0];
	DefaultVatRateObj.value = responseText;
}
function UpdateDefaultVatRate()
{
	var NameObj = document.getElementsByName('Name')[0];
	var DefaultVatRateObj = document.getElementsByName('DefaultVatRate')[0];
	if (NameObj.selectedIndex<2)
	{
		DefaultVatRateObj.value = "";
	}
	else
	{
		DefaultVatRateObj.value = "wait";
		GetAjaxData("shopservices.pl?command=getDefaultVatRate&Name="+NameObj.value,"",OnUpdateDefaultVatRate,null,"DefaultVatRateContainer");
	}
}
function OnSaveDefaultVatRate(responseText)
{
	window.alert(responseText);
}
function SaveDefaultVatRate()
{
	var NameObj = document.getElementsByName('Name')[0];
	if (NameObj.selectedIndex>1 && confirm("would you like to update the Default Vat Rate for this contact?"))
	{
		var DefaultVatRateObj = document.getElementsByName('DefaultVatRate')[0];
		GetAjaxData("shopservices.pl?command=saveDefaultVatRate&Name="+NameObj.value+"&DefaultVatRate="+encodeURIComponent(DefaultVatRateObj.value),"",OnSaveDefaultVatRate,null,"DefaultVatRateContainer");
	}
}
function OnSubmitClientOrder(responseText,message)
{
	if (ProcessCommand(responseText))
	{
		if (message) alert(message);
		ShowView('clientorders','command=viewclientorder&ID='+RegExp.$1);
	}
}
function ReceivePayment(ID,Type)
{
	GetAjaxData("shopservices.pl?command=payinvoice&ID="+ID+"&Date="+encodeURIComponent(document.getElementById('Date').value),"",OnSubmitClientOrder,null,"TasksArea");
}
function DeletePayment(ID,Type)
{
	if (confirm('Are you sure you want to revert this '+Type+' to Unpaid?'))
	{
		GetAjaxData("shopservices.pl?command=deletepayment&ID="+ID,"",OnSubmitClientOrder,null,"TasksArea");
	}
}
function ChangeStatus(ID,status)
{	
	GetAjaxData("shopservices.pl?command=changestatus&ID="+ID+"&status="+status,"",OnSubmitClientOrder,null,"TasksArea");
}
function OnDeleteClientOrder(responseText)
{
	if (ProcessCommand(responseText))
	{
		ShowView('clientorders','command=clientorders');
	}
}

function DeleteClientOrder(ID,Type)
{
	if (confirm('Are you sure you want to delete this '+Type+'?'))
	{
		GetAjaxData("shopservices.pl?command=deleteclientorder&ID="+ID,"",OnDeleteClientOrder,null,"TasksArea");
	}
}
function ValidateSubmission(Type,ID)
{
	return (ID == "" || confirm("You are about to update this "+Type+". Continue?"));
}
function OnShowClientOrder()
{
	updateSums(-1);
	HideOrShowNewBox('Name','NewName');
}	
function SubmitClientOrder(message)
{
	var form = document.getElementById('ClientOrderForm');
	var command = "shopservices.pl?command=submitclientorder";
	for (var i=0;i<form.length;i++)
	{
		command += "&" + form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value);
	}
	GetAjaxData(command,"",OnSubmitClientOrder,message,"SubmitClientOrderArea");
}
function OnUpdateClientInvoiceAddr(responseText)
{
	if (ProcessCommand(responseText))
	{
		alert('Your Company Details have been updated.');
	}
	else
	{
		var form = document.getElementById('ClientInvoiceAddrForm');	
		form.reset();	
	}
}	
function UpdateClientInvoiceAddr()
{
	var form = document.getElementById('ClientInvoiceAddrForm');
	var command = "shopservices.pl?command=UpdateClientInvoiceAddr";
	for (var i=0;i<form.length;i++)
	{
		command += "&" + form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value);
	}
	GetAjaxData(command,"",OnUpdateClientInvoiceAddr,null,"ClientInvoiceAddrForm");
}
function OnUpdateBillAddr(responseText)
{
	if (ProcessCommand(responseText))
	{
		alert('Your Default Billing Address has been updated.\n\nIMPORTANT!! This will not change the billing address in your orders. Please modify your open orders directly.');
	}
	else
	{
		var form = document.getElementById('BillAddrForm');	
		form.reset();	
	}
}	
function UpdateBillAddr()
{
	var form = document.getElementById('BillAddrForm');
	var command = "shopservices.pl?command=UpdateBillAddr";
	for (var i=0;i<form.length;i++)
	{
		command += "&" + form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value);
	}
	GetAjaxData(command,"",OnUpdateBillAddr,null,"BillAddrForm");
}
function OnUpdateDelAddr(responseText)
{
	if (ProcessCommand(responseText))
	{
		var idx = document.getElementById("Delivery").selectedIndex;
		if (idx>0)
		{
			alert('Delivery Address has been updated.\n\nIMPORTANT!! This will not change the delivery address in your orders. Please modify your open orders directly.');
			ShowView('address','command=address&delIdx=' + idx);
		}
		else
		{
			alert('Delivery Address has been created.');
			ShowView('address','command=address&delIdx=' + document.getElementById("Delivery").length);
		}
	}
	else
	{
		var form = document.getElementById('DelAddrForm');	
		form.reset();	
	}
}	
function UpdateDelAddr()
{
	var form = document.getElementById('DelAddrForm');
	var idx = document.getElementById("Delivery").selectedIndex;
	var command = "shopservices.pl?command=UpdateDelAddr&delIdx=" + idx;
	for (var i=0;i<form.length;i++)
	{
		command += "&" + form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value);
	}
	GetAjaxData(command,"",OnUpdateDelAddr,null,"DelAddrForm");
}

function OnUpgradeAccount(responseText)
{
	if (ProcessCommand(responseText))
	{
		alert('Your upgrade request has been submitted. You will be notified when this has been done');
		ShowView('general','command=general');
	}
}	
function UpgradeAccount()
{
	if (!document.getElementById('businessterms').checked)
	{
		alert('please tick box to confirm that you have read and understood our business terms and conditions');
		return;
	}
	var command = "shopservices.pl?command=UpgradeAccount2";
	GetAjaxData(command,"",OnUpgradeAccount);
}

function OnDeleteDelAddr(responseText)
{
	if (ProcessCommand(responseText))
	{
		alert('Delivery Address has been deleted.');
		ShowView('address','command=address');
	}
	else
	{
		var form = document.getElementById('DelAddrForm');	
		form.reset();	
	}
}	
function DeleteDelAddr()
{
	if (confirm('Are you sure you want to delete this address?'))
	{
		var form = document.getElementById('DelAddrForm');
		var idx = document.getElementById("Delivery").selectedIndex;
		GetAjaxData("shopservices.pl?command=DeleteDelAddr&delIdx=" + idx,"",OnDeleteDelAddr,null,"DelAddrForm");
	}
}
function OnShowAddress()
{
	UpdateDeliveryArea();
}	
function OnUpdateProfile(responseText)
{
	if (ProcessCommand(responseText))
	{
		alert('Your account profile has been updated.\n\nIMPORTANT!! This will not change the Contact Telephone Number in your orders. Please modify your open orders directly.');
	}
	else
	{
		var form = document.getElementById('ProfileForm');	
		form.reset();	
	}
}
function GetValue(elt)
{
	if (elt.type == 'checkbox')
	{
		return elt.checked ? elt.value : "";
	}
	else
	{
		return elt.value;
	}
}

function UpdateProfile()
{
	var form = document.getElementById('ProfileForm');
	var command = "shopservices.pl?command=UpdateProfile";
	for (var i=0;i<form.length;i++)
	{
		command += "&" + form.elements[i].name + "=" + encodeURIComponent(GetValue(form.elements[i]));
	}
	GetAjaxData(command,"",OnUpdateProfile,null,"ProfileForm");
}
function OnChangePassword(responseText)
{
	if (ProcessCommand(responseText))
	{
		alert('Your Password has been changed.');
	}
	else
	{
		var form = document.getElementById('PasswordForm');	
		form.reset();	
	}
}	
function ChangePassword()
{
	var form = document.getElementById('PasswordForm');
	var command = "shopservices.pl?command=ChangePassword";
	for (var i=0;i<form.length;i++)
	{
		command += "&" + form.elements[i].name + "=" + encodeURIComponent(GetValue(form.elements[i]));
	}
	GetAjaxData(command,"",OnChangePassword,null,"PasswordForm");
}
function CreateClientOrder(ID)
{
	ShowView('clientorders','command=viewclientorder&origOrder='+ID+'&Margin=' + document.getElementById('Margin').value);
}
function OnSendClientOrder(responseText)
{
	if (ProcessCommand(responseText))
	{
		alert('Your email has been sent.');
		ShowView('clientorders','command=viewclientorder&ID='+RegExp.$1)
	}
}	
function SendClientOrder()
{
	var form = document.getElementById('SendClientOrderForm');
	var command = "shopservices.pl?command=SendClientOrder";
	for (var i=0;i<form.length;i++)
	{
		command += "&" + form.elements[i].name + "=" + encodeURIComponent(GetValue(form.elements[i]));
	}
	GetAjaxData(command,"",OnSendClientOrder,null,"SendClientOrderForm");
}
function OnSendInvoice(responseText)
{
	if (ProcessCommand(responseText))
	{
		alert('Your invoice has been sent to the registered email address.');
		ShowView('orders','command=vieworder&transID='+RegExp.$1);
	}
}	
function SendInvoice(ID)
{
	var form = document.getElementById('SendClientOrderForm');
	var command = "shopservices.pl?command=SendInvoice2&ID="+ID;
	GetAjaxData(command,"",OnSendInvoice,null,"SendInvoiceArea");
}
function OnUpdateDeliveryArea(responseText)
{
	var data = responseText.split("\t");
	document.getElementsByName('DelName')[0].value = (responseText != "" ? data[0] : "");
	document.getElementsByName('DelNumber')[0].value = (responseText != "" ? data[1] : "");
	document.getElementsByName('DelAddr1')[0].value = (responseText != "" ? data[2] : "");
	document.getElementsByName('DelAddr2')[0].value = (responseText != "" ? data[3] : "");
	document.getElementsByName('DelStreet')[0].value = (responseText != "" ? data[4] : "");
	document.getElementsByName('DelCity')[0].value = (responseText != "" ? data[5] : "");
	document.getElementsByName('DelCountry')[0].value = (responseText != "" ? data[6] : "");
	document.getElementsByName('DelPostCode')[0].value = (responseText != "" ? data[7] : "");
}
function UpdateDeliveryArea()
{
	var idx = document.getElementById("Delivery").selectedIndex;
	GetAjaxData("../cgi-bin/submitOrdServices.pl?getDelAddress="+idx,"",OnUpdateDeliveryArea,null,"DelAddrForm");
}

function OnDeleteCard(responseText)
{
	if (ProcessCommand(responseText))
	{
		alert('Card details have been removed.');
		ShowView('general','command=general');
	}
}	
function DeleteCard()
{
	if (confirm('Are you sure you want to remove these card details?'))
	{
		var idx = document.getElementById("Card").selectedIndex;
		GetAjaxData("shopservices.pl?command=DeleteCard&idx=" + idx,"",OnDeleteCard,null,"CardArea");
	}
}

///////////////////////////
//  search box
///////////////////////////

var searchString = "";
function OnOpenSearchPopup(responseText,currentSearchString)
{
	//do not update if in the meantime searchstring has changed
	if (currentSearchString != searchString) {return;}
	document.getElementById('InfoBox').innerHTML = responseText;
}	
function OpenSearchPopup()
{
	var formElt = document.getElementById('searchBox');
	if (searchString == formElt.value)
		return;
	searchString = formElt.value;
	if (formElt.value.length<2)
		return;
	CreatePopup1('InfoBox',formElt,0,formElt,1);
	popupNClicks=1;//make sure windows closes on FIRST click
	GetAjaxData("searchservice.pl?searchString="+encodeURIComponent(formElt.value),"",OnOpenSearchPopup,formElt.value,'searchBoxArea');
}

function showDiscountInfoBox()
{
	var parentelt = document.getElementById('DiscountInfoBoxLink');
	CreatePopup1('DiscountInfoBox',parentelt,0,parentelt,1);
	GetAjaxData("shoputils.pl?command=discountInfoBox",'DiscountInfoBox');
}