//RELOAD WINDOW
	function reloadWin(){
	
	var w=window.open("", "managerpopup"); //get handle of Window1
	//alert(w.location.href); //check URL - test only
	w.location.reload(true);  //reload it
	w.focus();
	self.close();
	}
	
	function reloadManagerPopup(id){	
	var w=window.open('/ssl/extranet/licence/manager/index.cfm?eventname=adminconsole&LicenceID='+id+'&','managerpopup','width=930,height=880,top=20,left=20,resizable=1,menubar=0,status=1,scrollbars=1,panel=0,addressbar=0'); 
	w.focus(); 
	self.close();
	}
	


//CHECK INTEGER
	function isInteger(s)
{
	if(s=='') return false;
	return Math.ceil(s) == Math.floor(s);
}


//ROUND TO 2 DECIMAL POINTS
	function dp_2(amt){ 
			
		amt=parseFloat(amt);
		return amt.toFixed(2);
	}


//ADD / TOTAL GST	
	function TotalGst(amt) {
		amt=dp_2(amt);
		total=amt*1.15;
		return total.toFixed(2); // to do should come from application.gst ....
	}


//CALCULATE GST AMOUNT	
	function CalcGst(amt) {
		//needs to format to 2 dp
		amt=dp_2(amt);
		gst=amt*.15;
		return gst.toFixed(2);
	}


//CALCULATE LICENCE PRICES
	var priceCalc = function(){ 

		var p = new pricing(); 
		var pForm=document.forms["purchase"];
		var ordertype=pForm.licenceType.value;
		var priceRes='';
		

		if (pForm.term.value == 0) {
			pForm.price.value = '$'+dp_2(0);
			pForm.gst.value = '$'+CalcGst(0);
			pForm.total.value = '$'+TotalGst(0);
			setFormField(pForm.dealerprice,'$'+dp_2(0));
			setFormField(pForm.dealergst,'$'+CalcGst(0));
			setFormField(pForm.dealertotal,'$'+TotalGst(0));
			show('ccDiv');
			show('invoice_button');
			return;
		}
		
		
		//show('ccDiv');
			
		if (document.getElementById('invoice_button')) 
			show('invoice_button');		

		if (ordertype == 'I') { //increase

			//check increase value is an interger if not alert and hide buttons
			
			if(! IsNumeric(pForm.increase_quantity.value)) {
				alert('Increase quantity must be a valid number');
				hide('ccDiv');
				hide('invoice_button');
				return 0;}
				
			priceRes=p.getIncreasePriceRemote(pForm.productid.value,pForm.quantity.value,pForm.remainingtermindays.value,pForm.increase_quantity.value);			

			pForm.new_quantity.value = parseInt(pForm.increase_quantity.value)+parseInt(pForm.quantity.value);

		}
		
		else if(ordertype == 'U'){ //upgrade

			priceRes=p.BindPrice(pForm.upgradeProductid.value,pForm.term.value,pForm.quantity.value,pForm.licenceType.value,pForm.promocode.value,pForm.cd.value); }
		else if(ordertype == 'C'){
			priceRes=p.BindPrice(pForm.productid.value,pForm.term.value,pForm.quantity.value,'N',pForm.promocode.value,pForm.cd.value); }
		else if(ordertype == 'D'){ //decrease
			if (parseInt(pForm.quantity.value)-parseInt(pForm.decrease_quantity.value) <= 0) { 
				alert('New quantity can not be less than 1'); pForm.decrease_quantity.value=1; hide('ccDiv'); return false ;}				
				
				pForm.new_quantity.value = parseInt(pForm.quantity.value)-parseInt(pForm.decrease_quantity.value); 
				return true;}
		else {
			priceRes=p.BindPrice(pForm.productid.value,pForm.term.value,pForm.quantity.value,pForm.licenceType.value,pForm.promocode.value,pForm.cd.value); 
		}



		pForm.price.value = '$'+dp_2(priceRes);
		pForm.gst.value = '$'+CalcGst(priceRes);
		pForm.total.value = '$'+TotalGst(priceRes);

		var discount=pForm.resellerdiscount.value;

		var dealerPrice = priceRes-(priceRes*discount/100);
		
		if (pForm.dealerprice) {
			pForm.dealerprice.value = '$'+dp_2(dealerPrice);
			pForm.dealergst.value = '$'+CalcGst(dealerPrice);
			pForm.dealertotal.value = '$'+TotalGst(dealerPrice);
		}
		

		if (priceRes == 0) {
			hide('ccDiv');
			hide('invoice_button'); 
			alert('Invalid quantity and pricing. Please try a different quantity.');
		} else {
			show('priceDiv'); 		
			show('ccDiv');
		}
			
			
	}

	
//GET LICENCE DETAILS AND SET UP PAGE
	var licenceCheck = function(id){ 

	if (id=='') return 0;

	var lic = new licence(); 	
	
	// read the licence 
	var licenceResult=lic.ReadLicenceJson(id); 
	
	// TURN THE JSON RETURNED RESULTS BACK TO JS OBJECT
	var licenceResultObj = eval("(" + licenceResult + ")");

	var pForm=document.forms["purchase"];

	//SET THE FORM VARS AND DISPLAY SPANS
	setLicenceArgs(pForm,licenceResultObj);

	if(pForm.orderTypeid==3) { //increase
		document.getElementById('remainingterm').innerHTML = licenceResultObj[0]["remaining_term_in_days"]; 
		pForm.remainingtermindays.value = licenceResultObj[0]["remaining_term_in_days"];
	}
	
	pForm.resellerdiscount.value = licenceResultObj[0]["discount"];


	licenceValidationResult=licenceValidation(pForm,licenceResultObj);

	if (! licenceValidationResult) return 0;

	document.getElementById('guiLicenceResult').innerHTML = '<img src="/images/tick.jpg" />';
	document.getElementById('guiLicenceResultMsg').innerHTML = 'Valid licence. <br>Please check details below before submitting.';
	document.getElementById('guiLicenceResultMsg').style.height=20+"px";
	show('ccDiv');
	show('licenceDiv');
	show('priceDiv');
	
	if (licenceResultObj[0]["mandatoryordernumber"] == 1)	
		document.getElementById('ordernumber').style.borderLeft=3+"px solid #5D0303";
	// these are only set for convert to trial orders
	if (pForm.orderTypeid.value == '8') {
		pForm.EmailAddress.value = licenceResultObj[0]["licencee_email"];
		pForm.City.value = licenceResultObj[0]["city"];
	
	}



	// PRICING 
	priceCalc();

}

		
//PUBLIC SHOP LICENCE CHECK
	var shopLicenceRenewCheck = function(un,pw){ 	
	if (un=='') return 0;

	// GET LICENCE DETAILS
	var lic = new licence(); 	
	
	// CHECK LICENCE IS VALID 
	var licenceResult=lic.licenceByUsernamePassword(un,pw); 
	
	// TURN THE JSON RETURNED RESULTS BACK TO JS OBJECT
	var licenceResultObj = eval("(" + licenceResult + ")");

	// THE FORM WE ARE DEALING WITH
	var pForm=document.forms["purchase"];


	// LICENCE CHECKS
	licenceValidationResult=licenceValidation(pForm,licenceResultObj);

	if (! licenceValidationResult) return 0;
		

	if (pForm.orderTypeid.value == 8)
		setConvertLicenceArgs(pForm,licenceResultObj);
	else
		setLicenceArgs(pForm,licenceResultObj);
		
	// PRICING 
	priceCalc();

} 

	
//CHECK PROMOCODE AND ADJUST PRICE
	var promocodeChecker = function(code){ 
	var promo = new promocode(); 
	
	// check promo is valid 
	var promoResult=promo.PromocodeCheck(code,1);  // 1 = return query as json
	
	var promoResultObj = eval("(" + promoResult + ")"); //json to jascript obj
	


	//if promo invalid show the cross 
	if (promoResultObj == false) {
		document.getElementById('guiPromocodeResult').innerHTML = '<img src="/images/cross.jpg">';

	//if promo valid show the tick and set the promocode discount value
	}
	else {
		document.getElementById('guiPromocodeResult').innerHTML = '<img src="/images/tick.jpg"> ('+promoResultObj[0]["discount"]+'%)';
		//document.getElementById('guiPromocode_discount').value = promoResultObj[0]["discount"];
	
		pForm=document.forms["purchase"];
		pForm.ResellerID.value = promoResultObj[0]["resellerid"];

	} 

	priceCalc();
}


//SET LICENCE ARGUMENTS
	function setLicenceArgs(pForm,licenceResultObj) {
	//SET THE FORM VARS AND DISPLAY SPANS
	setInnerHTML('guiProductName',licenceResultObj[0]["productname"]);
	setInnerHTML('guiEmail',licenceResultObj[0]["emailaddress"]);
	setInnerHTML('guiName',licenceResultObj[0]["licenceename"]);
	setInnerHTML('guiPhone',licenceResultObj[0]["phone"]);
	setInnerHTML('guiExpirydate',licenceResultObj[0]["expirydate"]);	

	setFormField(pForm.quantity,licenceResultObj[0]["licence_quantity"]);
	setFormField(pForm.ResellerID,licenceResultObj[0]["resellerid"]);
	setFormField(pForm.licenceid,licenceResultObj[0]["licenceid"]);
	setFormField(pForm.licenceeid,licenceResultObj[0]["licenceeid"]);
	setFormField(pForm.licenceeName,licenceResultObj[0]["licenceename"]);
	setFormField(pForm.productid,licenceResultObj[0]["productid"]);
	setFormField(pForm.productname,licenceResultObj[0]["productname"]);
	setFormField(pForm.countrycode,licenceResultObj[0]["countrycode"]);
	setFormField(pForm.LicenceeTypeid,licenceResultObj[0]["licenceetypeid"]);
	setFormField(pForm.dexterProductCode,licenceResultObj[0]["dexterprodid"]);
	setFormField(pForm.dayslastorder,licenceResultObj[0]["dayslastorder"]);
	setFormField(pForm.lastordertype,licenceResultObj[0]["order_type"]);

}


//SET LICENCE ARGUMENTS FOR CONVERT TO TRIAL LICENCE SPECIAL CIRCUMSTANCES
	function setConvertLicenceArgs(pForm,licenceResultObj) {
	document.getElementById('guiProductName').innerHTML = licenceResultObj[0]["productname"];
	pForm.quantity.value = licenceResultObj[0]["licence_quantity"];	
	pForm.ResellerID.value = licenceResultObj[0]["resellerid"];
	pForm.licenceid.value = licenceResultObj[0]["licenceid"];
	pForm.licenceeid.value = licenceResultObj[0]["licenceeid"];
	pForm.productid.value = licenceResultObj[0]["productid"];
	pForm.productname.value = licenceResultObj[0]["productname"];
	pForm.countrycode.value = licenceResultObj[0]["countrycode"];
	pForm.LicenceeTypeid.value = licenceResultObj[0]["licenceetypeid"];
	pForm.dexterProductCode.value = licenceResultObj[0]["dexterprodid"];
	pForm.dayslastorder.value = licenceResultObj[0]["dayslastorder"];
	pForm.lastordertype.value = licenceResultObj[0]["order_type"];	
	setFormField(pForm.licencekey,licenceResultObj[0]["licencekey"]);
	setFormField(pForm.password,licenceResultObj[0]["password"]);

	if(pForm.submitted.value==0) { 
		pForm.EmailAddress.value = licenceResultObj[0]["emailaddress"];
		pForm.Phone.value = licenceResultObj[0]["phone"];
		pForm.City.value = licenceResultObj[0]["city"];
	}
}	


//SET REQUIRED ADDRESS ON OR OFF
	function toggleRequiredAddress(trigger) {
		//trigger is selected index
		if (trigger==0) {
			document.getElementById('Address1').className = 'inputField';
			document.getElementById('Address2').className = 'inputField';
		} else {
			document.getElementById('Address1').className = 'required';
			document.getElementById('Address2').className = 'required';
		}
	}
	

//INCREASE FORM - HIDE CCDIV AND PRICEDIV
	function increaseHide() {
			hide('ccDiv');
			hide('priceDiv');
		}

			
//LICENCE VALIDATION BEHAVIOURS	
	function licenceValidation(pForm,licenceResultObj) {
		if (licenceResultObj == false) {
			document.getElementById('guiLicenceResult').innerHTML = '<img src="/images/cross.jpg">'; 
			document.getElementById('guiLicenceResultMsg').innerHTML = 'Invalid Licence';
			hide('ccDiv');
			hide('licenceDiv');
			hide('licenceeDiv');
			document.getElementById('guiLicenceResultMsg').style.height=20+"px";
			
			return 0;
		}


		// CAN'T UPGRADE OR INCREASE LESS THAN 30 DAYS OUT FROM TRIAL !!
		if ((pForm.licenceType.value == 'I') && licenceResultObj[0]["remaining_term_in_days"] < 30){
			document.getElementById('guiLicenceResult').innerHTML = '<img src="/images/exclamation.jpg" />';
			document.getElementById('guiLicenceResultMsg').innerHTML = 'Please renew your licence before increasing.';
			document.getElementById('guiLicenceResultMsg').style.height=20+"px";
			hide('ccDiv');
			hide('licenceDiv');
			hide('licenceeDiv');
			hide('priceDiv');
			return 0;
		}
		
		// ALREADY BOUGHT NEW FROM TRIAL!!
		if (pForm.licenceType.value == 'C' && licenceResultObj[0]["order_type"] == 'Buy_new_from_trial'){
			document.getElementById('guiLicenceResult').innerHTML = '<img src="/images/exclamation.jpg" />';
			document.getElementById('guiLicenceResultMsg').innerHTML = 'This licence has already been upgraded';
			document.getElementById('guiLicenceResultMsg').style.height=20+"px";
			hide('ccDiv');
			hide('licenceDiv');
			hide('licenceeDiv');
			return 0;
		}		
		

		// ALREADY UPGRADED TO ESS!!
		if (pForm.orderTypeid.value == '5' && licenceResultObj[0]["productid"] == 38){
			document.getElementById('guiLicenceResult').innerHTML = '<img src="/images/exclamation.jpg" />';
			document.getElementById('guiLicenceResultMsg').innerHTML = 'Sorry, this licence can not be upgraded.';
			document.getElementById('guiLicenceResultMsg').style.height=20+"px";
			hide('ccDiv');
			hide('licenceDiv');
			hide('licenceeDiv');
			return 0;
		}

		// MUST BUY FROM TRIAL FIRST
		if ((pForm.orderTypeid.value == '2' ||  pForm.orderTypeid.value == '3' || pForm.orderTypeid.value == '5') && licenceResultObj[0]["order_type"] == 'Trial') {
			document.getElementById('guiLicenceResult').innerHTML = '<img src="/images/exclamation.jpg" />';
			document.getElementById('guiLicenceResultMsg').innerHTML = 'Unable to action! Choose BUY FULL LICENCE from TRIAL option.';
			document.getElementById('guiLicenceResultMsg').style.height=20+"px";
			hide('ccDiv');
			hide('licenceDiv');
			hide('priceDiv');
			return 0;
		}		
		
		
		// EXPIRED TOO LONG - DON'T ALLOW
		if (licenceResultObj[0]["expired_days"] > 60){
			document.getElementById('guiLicenceResult').innerHTML = '<img src="/images/exclamation.jpg" />';
			document.getElementById('guiLicenceResultMsg').innerHTML = 'Your licence has passed the allowed renewal period. <br>Please purchase a new licence';
			document.getElementById('guiLicenceResultMsg').style.height=20+"px";
			hide('ccDiv');
			hide('licenceDiv');
			hide('licenceeDiv');
			return 0;
		}
		
		// ALREADY RENEWED TODAY - SHOW WARNING - DON'T ALLOW - THERE IS ALSO SERVERSIDE CHECKING IN THE PURCHASESERVICE.CFC
		if (licenceResultObj[0]["dayslastorder"] == 0 && licenceResultObj[0]["order_type"] == 'Renewal' && pForm.licenceType.value=='R'){
			document.getElementById('guiLicenceResult').innerHTML = '<img src="/images/exclamation.jpg" />';
			document.getElementById('guiLicenceResultMsg').innerHTML = 'This licence has already been renewed today. Licences can not be renewed twice on the same day.';
			document.getElementById('guiLicenceResultMsg').style.height=20+"px";
			hide('ccDiv');
			hide('licenceDiv');
			hide('licenceeDiv');
			return 0;
		}
		
		// NOT ACTIVE - DON'T ALLOW
		if (licenceResultObj[0]["licence_status_description"] != 'Active'){
			document.getElementById('guiLicenceResult').innerHTML = '<img src="/images/exclamation.jpg" />';
			document.getElementById('guiLicenceResultMsg').innerHTML = 'Your licence is no longer active. Please purchase a new licence or contact Chillisoft';
			document.getElementById('guiLicenceResultMsg').style.height=20+"px";
			hide('ccDiv');
			hide('licenceDiv');
			hide('licenceeDiv');
			return 0;
		}
		
	
		// CHILLISOFT OR RENEWAL DIVERT - DO ALLOW
		if (licenceResultObj[0]["licencee_resellerid"] == 8 || licenceResultObj[0]["licencee_reseller_renewal_divert"] !='') {
			document.getElementById('guiLicenceResult').innerHTML = '<img src="/images/tick.jpg" />';
			document.getElementById('guiLicenceResultMsg').innerHTML = 'Please check details below before submitting.';
			document.getElementById('guiLicenceResultMsg').style.height=20+"px";
			show('ccDiv');
			show('licenceDiv');
			show('licenceeDiv');
			return 1;
	
		// NON CHILLISOFT AND NON DIVERT - REFER TO RESELLER
		} else {
			document.getElementById('guiLicenceResult').innerHTML = '<img src="/images/exclamation.jpg" />';
			document.getElementById('guiLicenceResultMsg').innerHTML = 'Sorry, this licence needs to be renewed/upgraded via your original supplier:<br />'+licenceResultObj[0]["licencee_reseller_name"]+'<br />'+licenceResultObj[0]["licencee_reseller_phone"]+'<br />'+licenceResultObj[0]["licencee_reseller_websiteurl"]+'<br />or <a href="/contact.cfm" target="new">click here</a> for our contact details.';
			document.getElementById('guiLicenceResultMsg').style.height=100+"px";
			hide('ccDiv');
			hide('licenceDiv');
			hide('licenceeDiv');
			return 0;
		}	
	}

	
//HIDE PASSED ID	
	var hide = function(id) {
		if (isdefinedElement(id)) {
			document.getElementById(id).style.visibility='hidden';
			document.getElementById(id).style.display='none';
		}
	}


//SHOW PASSED ID
	var show = function(id) { 	
		if (isdefinedElement(id)) {
			document.getElementById(id).style.visibility='visible';
			document.getElementById(id).style.display='block';
		}
	}


//SHOW / HIDE DEALER PRICE	
	function toggleDealerPrice() {
	
		var dealerPrice1 = document.getElementById("dealerBuy1");
		var dealerPrice2 = document.getElementById("dealerBuy2");
		var dealerPrice3 = document.getElementById("dealerBuy3");
		var text = document.getElementById("controlText");
	
	
	
		if(dealerPrice1.style.visibility == "hidden") {
	    		show('dealerBuy1');
	    		show('dealerBuy2');
	    		show('dealerBuy3');
			text.innerHTML = "[hide]";
	
	  	}
		else {
	    		hide('dealerBuy1');
	    		hide('dealerBuy2');
	    		hide('dealerBuy3');
	
			text.innerHTML = "[show]";
		}
	
	}
	
	
//SET INNERHTML
	function setInnerHTML(id,value) {
	if (isdefinedElement(id)) 
		document.getElementById(id).innerHTML = value;
	}

//SET FORM FIELD VALUE
	function setFormField(field,value) {
	if (testIsValidObject(field)) 
		field.value=value;
	}
	

//TEST OUR OBJECT IS VALID
	function testIsValidObject(objToTest) {
		if (null == objToTest) {
			return false;
		}
		if ("undefined" == typeof(objToTest) ) {
			return false;
		}
		return true;

	}

//TEST OUR DOCUMENT ELEMENT IS VALID	
	function isdefinedElement(id) {
		if (document.getElementById(id) != null) {
			return true;
		} else {
			return false;
		}
	}
	
	
	
	
	
function IsNumeric(sText)
{
	var ValidChars = "0123456789";
	var IsNumber=true;
	var Char;
	
	
	for (i = 0; i < sText.length && IsNumber == true; i++) 
	{ 
	Char = sText.charAt(i); 
	if (ValidChars.indexOf(Char) == -1) 
	{
	IsNumber = false;
	}
	}
	if(sText=='') IsNumber = false;
	return IsNumber;

}


