// use a couple of globals to hold order id and service id
// must be a better way of doing this
// SG - 01/10/09 PAP Affiliate coupons with no discount value added in
var service_id;
var order_id;
function init(setup, oid, sid) {
	//	console.log("init()");
	order_id = oid;
	service_id = sid;
	//	console.log(service_id);
	checkform();
	//keepalive('order_id');
	if (setup == "full" || setup == "full2" || setup == "step2") {
		doChangePrice();
	}
}

function changelength() {
	//console.log("changelength()");
	//console.log(document.forms.order.Length.value);
	if (document.forms.order.Length.value >= 10000) {
		document.getElementById("li-lengthoptions").style.display = "block";
	} else {
		document.getElementById("li-lengthoptions").style.display = "none";
	}
}

loadstatus = 0;

function showError(inputID, errorID, checkID) {
	document.getElementById(inputID).style.border = "1px solid red";
	document.getElementById(errorID).style.display = "inline";
	document.getElementById(checkID).style.visibility = "hidden";
}

function showCheck(inputID, errorID, checkID) {
	document.getElementById(inputID).style.border = "1px solid green";
	document.getElementById(errorID).style.display = "none";
	document.getElementById(checkID).style.visibility = "visible";
}

function checkform(field) {
	//	console.log("checkform");
	if (typeof field == "undefined")
		field = "all";
	//	console.log(field);
	error = 0;
	if (field == "title" || field == "all") {
		if (document.getElementById("title")) {
			//Must have a title of at least 10 characters
			title = document.getElementById("title").value
			titleregex = /^.{10,}$/im;
			if (!title.match(titleregex)) {
				showError("title", "titleerror", "titlecheck");
				error = 1;
			} else {
				showCheck("title", "titleerror", "titlecheck");
			}
		}
	}

	if (field == "topic" || field == "all"){
		if (document.getElementById("topic")) {
			//Value must not be missed
			topic = document.getElementById("topic").value;
			if (topic == "missed") {
				showError("topic","topicerror","topiccheck");
				error = 1;
			} else {
				showCheck("topic","topicerror","topiccheck");

				if (topic == 45) {
					document.getElementById('othersubject').style.display = 'none';
					document.getElementById("lawdropdown").style.display = "inline";
					lawtopic = document.order.LawTopic.value;

					if (lawtopic == 'missed') {
						document.order.LawTopic.style.border = "1px solid red";
						error = 1;
					} else {
						document.order.LawTopic.style.border = "1px solid green";
					}

					if (lawtopic == 'Other') {
						document.getElementById("lawother").style.display = "inline";
					} else {
						document.getElementById("lawother").style.display = "none";
					}
				} else if (topic == 99) {
					document.getElementById('othersubject').style.display = 'block';
					document.getElementById("lawdropdown").style.display = "none";
					document.getElementById("lawother").style.display = "none";
					
					//if (field == "all") {
						if (document.getElementById('otherdropdown').value.replace(' ', '') === '') {
							showError('otherdropdown', 'otherdropdownerror', 'otherdropdowncheck');
							error = 1;
						} else {
							showCheck("otherdropdown","otherdropdownerror","otherdropdowncheck");
						}
					//}
				} else {
					document.getElementById('othersubject').style.display = 'none';
					document.getElementById("lawdropdown").style.display = "none";
					document.getElementById("lawother").style.display = "none";
				}
			}
		}
	}
	
	if (field == "email" || field == "all") {
		if (document.getElementById("email")) {
			//Email Must Be Valid
			email = document.getElementById("email").value
			emailregex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i ;
			if (!email.match(emailregex)) {
				showError("email", "emailerror", "emailcheck");
				error = 1;
			}
			else {
				showCheck("email", "emailerror", "emailcheck");
			}
		}
	}

	if (field == "name" || field == "all") {
		if (document.getElementById("name")) {
			//Must Include A Name
			name = document.order.name.value
			nameregex = /^.+$/i
			if (!name.match(nameregex)) {
				showError("name", "nameerror", "namecheck");
				error = 1;
			}
			else {
				showCheck("name", "nameerror", "namecheck");
			}
		}
	}

	if (field == "phone" || field == "all") {
		if (document.getElementById("phone")) {
			//Must Include Phone Numbers

			phone = document.order.phone.value
			phoneregex = /^.{3,}$/i ;
			if (!phone.match(phoneregex)) {
				showError("phone", "phoneerror", "phonecheck");
				error = 1;
			}
			else {
				showCheck("phone", "phoneerror", "phonecheck");
			}
		}
	}
}

function dosubmit() {
	//	console.debug("dosubmit()");
	checkform();
	if (error == 1){
		alert ("Oops! We think you missed something - please make sure you have filled in all the sections in red");
		return false;
	}
	else {
		// form has been completed correctly
		//		console.debug("submit the form");
		//BMS task 666. Disable submit button if the error check is fine to prevent multiple order submits.
		document.order.submit.disabled = true;
		document.order.submit.value = "Placing Order...";
		document.order.submit();
	}
}




function doChangePrice() { //Level 2 function, called by doChangeBase();
	//	console.debug("doChangePrice()");
	// this event handler is triggered when any of the pricing fields is changed
	// if saving is displayed, then price needs recalculating and discount needs applying
	// if saving is not displayed, just calculate price
	// NB: using offsetHeight to check for existence of box on form, this won't work if visibility is set to hidden as box is still there
	if (document.getElementById('liSaving').offsetHeight != 0) {
		//		console.debug("saving is displayed, doApplyDiscount");
		doApplyDiscount();
	}
	else {
		//		console.debug("saving is not displayed, doCalculatePrice");
		doCalculatePrice()
	}
}


function doApplyDiscount() { //Level 3 function, called by doChangePrice();
	//	console.debug("doApplyDiscount()");
	var level = document.forms.order.Level;
	var type = document.forms.order.Standard;
	var length = document.forms.order.Length;
	var delivery = document.forms.order.Type;
	var amendments = document.forms.order.Amendments;
	var inputDiscount = document.getElementById('inputDiscount');
	var email = document.forms.order.Email;
	// if discount code has been entered
	// could also do some other checking here like length, alphannumeric, etc
	if (inputDiscount.value != '') {
		document.getElementById('spanApplyingDiscount').style.display = 'inline';
		document.getElementById('applyDiscount').style.display ='none';

		AjaxRequest.get(
		{
			'url':'xhr_proxy.php',
			'parameters':{
				'req':'1',
				'code':inputDiscount.value,
				'email':email.value,
				'level':level.value,
				'type':type.value,
				'length':length.value,
				'delivery':delivery.value,
				'amendments':amendments.value,
				'service':service_id
			},
			'timeout':5000,
			'onSuccess':xhrResponseHandler1,
			'onTimeout':function(req){
				alert("The server is a bit busy at the moment, please try again!");
			}
		}
		);
	}
	else {
		hideDiscount();
	}
}


function xhrResponseHandler1(xhr) { //Level 4 function, called by doApplyDiscount();
	//	console.debug("xhrResponseHandler1()");
	var xml = xhr.responseXML.getElementsByTagName('coupon')[0];
	var discountValid = parseInt(xml.getElementsByTagName('valid')[0].childNodes[0].nodeValue);
	var couponID = xml.getElementsByTagName('id')[0].childNodes[0].nodeValue;
	var discountCode = xml.getElementsByTagName('code')[0].childNodes[0].nodeValue;
	var discountName = new String(xml.getElementsByTagName('name')[0].childNodes[0].nodeValue);
	var saving = xml.getElementsByTagName('saving')[0].childNodes[0].nodeValue;
	var price = xml.getElementsByTagName('price')[0].childNodes[0].nodeValue;

	if (discountValid) {
		document.forms.order.UKCost.value = price;
		document.forms.order.quote.value = price;

		document.forms.order.CouponID.value = couponID;
		document.forms.order.CouponSaving.value = saving;
		// SOB 29/04/09
		// there is a problem with the encoding of £ sign in XML so on the server any £ sign is replaced with its UNICODE equivalent
		// here we need to decode the urlencoded £ sign for display
		while (discountName.search("%A3") != -1) {
			discountName = discountName.replace("%A3", "\u00A3");
		}

		// SG - 01/10/09 If this is a proper coupon then show the discount
		// else if this is a PAP affiliate coupon then show the thanks section and no discount
		if (saving != 0) {
			document.getElementById('inputDiscountApplied').value = discountName;
			document.getElementById('inputSaving').value = saving;

			document.getElementById('liDiscountApplied'	).style.display = 'block';
			document.getElementById('liSaving').style.display = 'block';
			document.getElementById('spanApplyingDiscount').style.display = 'none';
			document.getElementById('applyDiscount').style.display ='inline';
		} else {
			// SG - PAP Integration 05/10/09
			//hideDiscount();
			document.getElementById('spanApplyingDiscount').style.display = 'none';
			document.getElementById('liThanks').style.display = 'block';
			document.getElementById('applyDiscount').style.display ='inline';
		}
	}
	else {
		alert ("Oops! That doesn't look like a valid discount code - please try again");
		hideDiscount();
	}
}


function hideDiscount() { //Level 5 function, called by xhrResponseHandler1()
	//	console.debug("hideDiscount()");
	document.getElementById('liDiscountApplied'	).style.display = 'none';
	document.getElementById('liSaving').style.display = 'none';
	document.getElementById('spanApplyingDiscount').style.display = 'none';
	document.getElementById('applyDiscount').style.display ='inline';
	document.getElementById('liThanks').style.display = 'none';
	document.forms.order.CouponID.value = 0;
	document.forms.order.CouponSaving.value = 0;
}




function doCalculatePrice() { // Level 3 function, called by doChangePrice();
	//	console.debug("doCalculatePrice()");
	var level = document.forms.order.Level;
	var type = document.forms.order.Standard;
	var length = document.forms.order.Length;
	var delivery = document.forms.order.Type;
	var amendments = document.forms.order.Amendments;

	document.getElementById('spanCalculatingPrice').style.display = 'inline';

	AjaxRequest.get(
	{
		'url':'xhr_proxy.php',
		'parameters':{
			'req':'2',
			'level':level.value,
			'type':type.value,
			'length':length.value,
			'delivery':delivery.value,
			'amendments':amendments.value,
			'service':service_id
		},
		'timeout':5000,
		'onSuccess':xhrResponseHandler2,
		'onTimeout':function(req){
			alert("The server is a bit busy at the moment, please try again!");
		}
	}
	);
}




function doPostPriceChange(price){
	var level = document.forms.order.Level;
	var type = document.forms.order.Standard;
	var length = document.forms.order.Length;
	var delivery = document.forms.order.Type;
	var amendments = document.forms.order.Amendments;
	var subject = document.forms.order.Topic;
	doChangePaymentOption(price);
	doChangeFinance(price);

}

function doChangePaymentOption(price) {

	var level = document.forms.order.Level;
	var type = document.forms.order.Standard;
	var length = document.forms.order.Length;
	var delivery = document.forms.order.Type;
	var amendments = document.forms.order.Amendments;
	var subject = document.forms.order.Topic;

	//check payment options exist on this form


	AjaxRequest.get(
	{
		'url':'xhr_proxy.php',
		'parameters':{
			'req':'3',
			'level':level.value,
			'type':type.value,
			'length':length.value,
			'delivery':delivery.value,
			'amendments':amendments.value,
			'service':service_id,
			'subject':subject.value,
			'price':price
		},
		'timeout':5000,
		'onSuccess':xhrResponseHandler4,
		'onTimeout':function(req){
			alert("The server is a bit busy at the moment, please try again!");
		}
	}
	);




	
}


function xhrResponseHandler4(xhr) { //Level 4 function, called by doChangePaymentOption
	//  console.debug("xhrResponseHandler2() xhr.reponsetext="+xhr.responseText);
	upfront_enabled = parseInt(xhr.responseText);
	if(upfront_enabled == 1){
		document.getElementById("fieldset-payment").style.display = "block";
		document.getElementById("fieldset-nopayment").style.display = "none";
		document.getElementById("submit").value = "Continue to Payment";
	}else{
		document.getElementById("fieldset-payment").style.display = "none";
		document.getElementById("fieldset-nopayment").style.display = "block";
		document.getElementById("submit").value = "Order Now";
		
	}

}


function xhrResponseHandler2(xhr) { //Level 4 function, called by doCalculatePrice
	//  console.debug("xhrResponseHandler2() xhr.reponsetext="+xhr.responseText);

	document.getElementById('spanCalculatingPrice').style.display = 'none';

	price = Math.round(xhr.responseText) - 0.0;

	document.forms.order.UKCost.value = price;
	document.forms.order.quote.value = price;
	doPostPriceChange(price);

}

function doChangeFinance(price) {
	if (price > 500) {
		var deposit = 0;
		var remaining = 0;
		var monthly = 0;
		var repayable = 0;
	
		deposit = Math.round((price / 3) * 100) / 100;
		remaining = price - deposit ;
		monthly = Math.round((((0.5 * 0.66) + 1) * (remaining / 6)) * 100) / 100 ;
		repayable = (monthly * 6);

		deposit = deposit.toFixed(2);
		remaining = remaining.toFixed(2);
		monthly = monthly.toFixed(2);
		repayable = repayable.toFixed(2);
		document.getElementById("financenote").innerHTML = "&pound;"+monthly+"";
		document.getElementById("deposit").innerHTML = "&pound;"+deposit+"";
		document.getElementById("monthly").innerHTML = "&pound;"+monthly+"";
		document.getElementById("repayable").innerHTML = "&pound;"+repayable+"";
		document.getElementById("credit").innerHTML = "&pound;"+remaining+"";
		document.getElementById('financediv').style.visibility = 'visible';
	} else {
		document.getElementById('financediv').style.visibility = 'hidden';
	}
}



function doChangeDiscount() {
	// this event handler is triggered when the discount code is changed
	//	console.debug("doChangeDiscount()");
	// if saving is displayed then hide discount and recalculate price
	// NB: using offsetHeight to check for existence of box on form, this won't work if visibility is set to hidden as box is still there
	if (document.getElementById('liSaving').offsetHeight != 0) {
		hideDiscount();
		doCalculatePrice();
	}
}



function doNewSubmit() {
	//	console.log("doNewSubmit()");
	var level = document.forms.order.Level;
	var type = document.forms.order.Standard;
	var length = document.forms.order.Length;
	var delivery = document.forms.order.Type;
	var amendments = document.forms.order.Amendments;
	var inputDiscount = document.getElementById('inputDiscount');
	var email = document.forms.order.Email;
	// if discount code has been entered
	// could also do some other checking here like length, alphannumeric, etc
	if (inputDiscount.value != '') {
		document.getElementById('spanApplyingDiscount').style.display = 'inline';
		document.getElementById('applyDiscount').style.display ='none';

		AjaxRequest.get(
		{
			'url':'xhr_proxy.php',
			'parameters':{
				'req':'1',
				'code':inputDiscount.value,
				'email':email.value,
				'level':level.value,
				'type':type.value,
				'length':length.value,
				'delivery':delivery.value,
				'amendments':amendments.value,
				'service':service_id
			},
			'timeout':5000,
			'onSuccess':xhrResponseHandler3,
			'onTimeout':function(req){
				alert("The server is a bit busy at the moment, please try again!");
			}
		}
		);
	}
	else {
		dosubmit();
	}

	return false;
}

function xhrResponseHandler3(xhr) {
	//  console.debug("xhrResponseHandler3()");

	var xml = xhr.responseXML.getElementsByTagName('coupon')[0];
	var discountValid = parseInt(xml.getElementsByTagName('valid')[0].childNodes[0].nodeValue);
	var couponID = xml.getElementsByTagName('id')[0].childNodes[0].nodeValue;
	var discountCode = xml.getElementsByTagName('code')[0].childNodes[0].nodeValue;
	var discountName = xml.getElementsByTagName('name')[0].childNodes[0].nodeValue;
	var saving = xml.getElementsByTagName('saving')[0].childNodes[0].nodeValue;
	var price = xml.getElementsByTagName('price')[0].childNodes[0].nodeValue;

	if (discountValid) {
		document.forms.order.UKCost.value = price;
		document.forms.order.quote.value = price;

		document.forms.order.CouponID.value = couponID;
		document.forms.order.CouponSaving.value = saving;
		document.getElementById('inputDiscountApplied').value = discountName;
		document.getElementById('inputSaving').value = saving;

		document.getElementById('liDiscountApplied'	).style.display = 'block';
		document.getElementById('liSaving').style.display = 'block';
		document.getElementById('spanApplyingDiscount').style.display = 'none';
		document.getElementById('applyDiscount').style.display ='inline';

		dosubmit();
	}
	else {
		alert ("Oops! That doesn't look like a valid discount code - please try again");
		hideDiscount();
	}
}

function show_my_div(hide,show) {
	document.getElementById(hide).style.display = 'none';
	document.getElementById(show).style.display = 'block';
}

filecount = 1;
function addfile() {
	br = document.createElement("BR");
	cleardiv = document.createElement("DIV");
	cleardiv.setAttribute("style","clear:both;");

	filecount = filecount + 1;

	clearbutton = document.createElement("DIV");
	clearbutton.innerHTML = "[clear]";
	clearbutton.setAttribute("onclick","document.getElementById('upload"+filecount+"').value='';document.getElementById('upload"+filecount+"').style.display = 'none'; document.getElementById('clearbut"+filecount+"').style.display = 'none'; document.getElementById('uploadname"+filecount+"').style.display = 'none'");
	clearbutton.setAttribute("style","cursor:pointer;width:10%;float:right;color:#0099FF");
	clearbutton.setAttribute("id","clearbut"+filecount+"");

	filebox = document.createElement("INPUT");
	filebox.setAttribute("type","file");
	filebox.setAttribute("name","upload"+filecount);
	filebox.setAttribute("id","upload"+filecount);
	filebox.setAttribute("onchange", "if(this.value!=''){document.getElementById('addbut').style.display = '';}document.getElementById('uploadname"+filecount+"').innerHTML = this.value");

	boxdiv = document.createElement("DIV");

	boxdiv.setAttribute("style","float:left;width:40%;");

	boxdiv.appendChild(filebox);

	filediv = document.createElement("DIV");
	filediv.setAttribute("id","uploadname"+filecount);
	filediv.setAttribute("style","float:right;width:48%;font-family:Arial Narrow;font-size:11px;");

	myparent = document.getElementById("uploads");
	myparent.appendChild(boxdiv);
	myparent.appendChild(clearbutton);
	myparent.appendChild(filediv);

	myparent.appendChild(cleardiv);
}

var loadstatus = 0;
var ordering = 0;

function checklogin(username,password) {
	login.location.replace("checkloginproxy.php?username="+username+"&password="+password+"");
}

function updateorder(field,value) {
	//	console.log("updateorder()");
	loadstatus = 0;
	ajax.location.href = 'http://www.aaorders.com/internal/db/forms/essaywritingorder/update.php?id='+order_id+'&field='+field+'&value='+value;
}

// SOB - I think this function might be redundant as updateorder() is called when each field loses focus, possibly retained as a catch all
function keepalive() {
	//	console.log("keepalive()");
	if (loadstatus == 1) {
		//		console.log("<?php echo FORM_WEBROOT ?>update.php?id=<?php echo $id; ?>&field=status&value=0");
		ajax.location.href = "http://www.aaorders.com/internal/db/forms/essaywritingorder/update.php?id="+order_id+"&field=status&value=0";
	}
	//setTimeout ("keepalive()","10000"); //10 seconds
}

function expand_collapse(id) {
	//	console.log("expand_collapse()");
	//	console.log(id);
	var el = document.getElementById(id);
	if ( el.style.display != 'none' ) {
		el.style.display = 'none';
	}
	else {
		el.style.display = '';
	}
}

$(document).ready(
	function() {
		document.order.submit.disabled = false;
	}
);
