// use a couple of globals to hold order id and service id
// must be a better way of doing this
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") {
		doCalculatePrice();
	}
}

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("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{
					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");
		document.order.submit();
	}
}

function doChangePrice() {
//	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 hideDiscount() {
//	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.forms.order.CouponID.value = 0;
	document.forms.order.CouponSaving.value = 0;
}

function doCalculatePrice() {
//	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 xhrResponseHandler2(xhr) {
//  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;
}

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 doApplyDiscount() {
//	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) {
//	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");
		}
		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 {
		alert ("Oops! That doesn't look like a valid discount code - please try again");
		hideDiscount();
	}
}

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 = '';
	}
}
