var deliveryflag = false;// false means delivery address same as invoice
var qo_form, quick_order_formDiv, qo_background, qo_top_wrapper, qo_messageDiv,qo_newline;
var qoItemsCount = 0;
var qoTotal = 0; // numeric
var qoTotalBox; // DOM input box which includes £ sign
var qoObj = [];
var qoHasBeenSent = false;
var errorLock = false;


function qo_setup(){
qo_form = getElm("quick_order_form");
qo_background = getElm("qo_background");
quick_order_formDiv = getElm("quick_order_formDiv");
qo_top_wrapper = getElm("qo_top_wrapper");
qo_messageDiv = getElm("qo_messageDiv");
qo_newline = getElm("qo_newline");
qoObj = []; // in case of reset
deleteprior(qo_form); // ditto
qoHasBeenSent = false; // ditto
qoItemsCount = 0; // ditto
for(var i = 1; i <4; i++) {
img = new Image();
img.src = "images/qo_slices/qo_slice_0"+i+".png";
qo_background.appendChild(img);
}
makeLabels();
qoObj.push( new line_constructor() );
qo_form.appendChild(qoObj[qoObj.length-1].wrapper); // make first set of inputs
// make Total box
qoTotalBox = document.createElement("input");
qoTotalBox.id = "qoTotalBox";
qoTotalBox.setAttribute("type","text");
qoTotalBox.setAttribute("readonly","true");
qoTotalBox.setAttribute("tabindex","-1"); // attempt to stop tabindexes - don't think it works
qoTotalBox.style.cssText="width: 641px; text-align: right; height: 14px; padding: 1px; margin-right: 3px; margin-bottom: 3px; border: 1px solid #8c8d8e";
qo_form.appendChild(qoTotalBox);
qo_newline.setAttribute("tabindex","5");
qoRecalcTotal();
}
	
function qoNewline() {
img = new Image();
img.src = "images/qo_slices/qo_slice_fill.png";
qo_background.insertBefore(img, qo_background.getElementsByTagName("img")[1]);
// add extra image to background
var formHeight = quick_order_formDiv.offsetHeight;
quick_order_formDiv.style.height = formHeight+20+"px";
// add extra height to qo_top_wrapper so elements remain correctly positioned
qo_top_wrapper.style.height = qo_top_wrapper.offsetHeight+20+"px";
qoObj.push( new line_constructor() );
qo_form.insertBefore(qoObj[qoObj.length-1].wrapper,qoTotalBox); // insert new line above Total Box
}


function makeLabels(){
	var thesizes = new Array("60","330","120","48","55");
	var theLabels = new Array("Code","Product Description","Size/weight/colour","Quantity","Price Each");
	qo_form.style.position = "relative";
	// create lables
	var lableWrapper = document.createElement("span");
	for(var i = 0; i <5; i++) {
	var newinput = document.createElement("input");
	newinput.setAttribute("type","text");
	newinput.setAttribute("class","qoLabel");
	newinput.setAttribute("readonly","true");
	newinput.style.cssText = "color: #fff; font-size: 1.1em; background-color: #0066CC; width:"+thesizes[i]+"px; border: 1px solid #0066CC; margin-right: 3px; margin-bottom: 2px;";
	//newinput.style.width = +thesizes[i]+"px";
	newinput.value = theLabels[i];
	lableWrapper.appendChild(newinput);	
	qo_form.appendChild(lableWrapper);
	}	
	
}


function line_constructor(){
	var complete_order_formDiv = getElm("complete_order_formDiv");
	qoItemsCount++;
	if(qoItemsCount> 3){
		complete_order_formDiv.style.top = "131px"; // move to top so it doesn't overlap input form
	}else{
		complete_order_formDiv.style.top =  278 + (qoItemsCount * 20) +"px"; // calc pos at bottom of input form
	}
	var thesizes = new Array("60","330","120","48","55");
	var wrapper = document.createElement("span");
	for(var i = 0; i <5; i++) {
	//create input fields
	var newinput = document.createElement("input");
	newinput.setAttribute("type","text");
	newinput.style.cssText="width:"+thesizes[i]+"px; height: 14px;  padding: 1px; margin-right: 3px; margin-bottom: 3px; border: 1px solid #8c8d8e";
	switch(i){
	case 0:
	this.input_code = newinput;
	break;
	case 1:
	this.description = newinput;
	break;
	case 2:
	this.size = newinput;
	break;
	case 3:
	newinput.value = 1; // it would seem a good default
	this.quantity = newinput;
	newinput.onchange = function(){ 
	if(checkForNumeric(this.value)){
		errorLock = false; // errorLock is used to block qoRecalcTotal which multiplies the UnitPrice with quantity
		qoRecalcTotal();
		}else{
		errorLock = true;
		}
	
	};
	break;
	case 4:
	this.priceBox = newinput;
	newinput.style.textAlign = "center"; // start centred for easy input
	newinput.onblur = function(){
	this.style.textAlign = "right"; // align right so decimal points line up
	var amount = (encodeURIComponent(this.value.substr(0,1))=="%C2%A3")? Number(this.value.substr(1)) : Number(this.value);
	this.value = amount.toFixed(2); // recalculated price
	qoRecalcTotal()
	};
	break;	
	}
		
	
	wrapper.appendChild(newinput);
	}
		this.wrapper = wrapper;
		this.total = 0; // added in qoRecalcTotal()
}

	
	function qoRecalcTotal(){
	if(errorLock) return;
	var newTotal = 0;
	for(var i = 0; i <qoObj.length; i++) {
	var UnitPrice = (qoObj[i].priceBox.value)? qoObj[i].priceBox.value : 0; // if nothing has been input we use 0
	var total = qoObj[i].quantity.value * UnitPrice; // calc quantity against price
	qoObj[i].total = total; // save back to obj so we can pull it out later
	newTotal += parseFloat(total,10);	
	}
	newTotal = newTotal.toFixed(2);
	qoTotal = newTotal; // pass to global
	qoTotalBox.value = "Total (not Inc VAT): \u00A3"+newTotal;
	}

	function checkForNumeric(num){
	var numericExpression = /^[0-9]+$/; // reg expression for 0-9
	return (num.match(numericExpression))? true : false;
	}
	

function submit_quick_order(){
if(qoHasBeenSent){
 displayFormMessage("Sorry, you have already sent this order");
return;	
}
var error_flag = null;
var organisation = document.getElementById("organisation").value;
var invoice_address = document.getElementById("invoice_address").value.replace(/\r\n|\n/g,'<br />');
var delivery_address = document.getElementById("delivery_address").value.replace(/\r\n|\n/g,'<br />');
var account_num = document.getElementById("account_num").value;
var order_num = document.getElementById("order_num").value;
var email = document.getElementById("email").value;
var name = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
var spans = qo_form.getElementsByTagName("span"); // span is wrapper for inputs

if (!organisation)  error_flag = 1;
if (!invoice_address)  error_flag = 1;
if (!email) error_flag = 1;
if (!name) error_flag = 1;
if (!phone) error_flag = 1;
//build tables with order details
var thetables = "";
for(var i = 0; i <qoObj.length; i++) {
thetables += '<table width="100%" cellpadding="2" cellspacing="0" style="border: solid 1px #888; font-family:Arial,Helvetica,sans-serif;font-size:11px; margin-bottom:3px;"><tr>';
var thewidths = new Array(10,30,30,10,20);
for(var j = 0; j <5; j++) {
  switch(j){
	case 0:
	if (qoObj[i].input_code == "") error_flag = 1;
	thetables += '<td width="'+thewidths[j] +'%">'+qoObj[i].input_code.value+'</td>';
	break;
	case 1:
	thetables += '<td width="'+thewidths[j] +'%">'+qoObj[i].description.value+'</td>';
	break;
	case 2:
	thetables += '<td width="'+thewidths[j] +'%">'+qoObj[i].size.value+'</td>';
	break;
	case 3:
	thetables += '<td width="'+thewidths[j] +'%">'+qoObj[i].quantity.value+'</td>';
	break;
	case 4:
	thetables += '<td align="right" width="'+thewidths[j] +'%">'+qoObj[i].priceBox.value+'</td>'; 
	break;
  }
}
thetables += '</tr></table>';
}
thetables +='<div style="padding: 2px; text-align: right; font-family:Arial,Helvetica,sans-serif;font-size:11px;">Total: '+qoTotal+'</div>';		   
//thetables +=  '</body></html>';

if (!error_flag){
post_data_to_server(escape(organisation),escape(invoice_address),escape(delivery_address),escape(account_num),escape(order_num),escape(email),escape(name),escape(phone),escape(thetables));
}else{
 displayFormMessage("Sorry, a required item not been supplied");
}
}




function show_delivery_input(){
var input=document.getElementById("delivery_address");
var lable=document.getElementById("delivery_lable");
input.style.visibility="visible";
lable.style.visibility="visible";
deliveryflag = true;
}



	
	function post_data_to_server(organisation,invoice_address,delivery_address,account_num,order_num,email,name,phone,thetables){
	var img = new Image(220,19);
	img.src = "images/ajax-loader.gif";
	qo_messageDiv.appendChild(img);
	var ajaxRequest = setupAJAX();
	if (!ajaxRequest){
	displayFormMessage("Sorry, there is a problem, please try again later");
	return;
	}
	var sendstring = 'organisation='+organisation+'&invoice_address='+invoice_address+'&delivery_address='+delivery_address;
    sendstring+= '&account_num='+account_num+'&order_num='+order_num+'&email='+email+'&name='+name+'&phone='+phone+'&thetables='+thetables;
	ajaxRequest.open("POST", "php/quick_order_email.php", true); 
	ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	ajaxRequest.onreadystatechange = function() {
	if(ajaxRequest.readyState == 4){
		    if(ajaxRequest.status==200){
			displayFormMessage(ajaxRequest.responseText);
			if(ajaxRequest.responseText == "Thank you for your order") qoHasBeenSent = true;
			}else{
            displayFormMessage("Sorry, there was a server problem, please try again later");
			}
			
		}
	}
	ajaxRequest.send(sendstring);

	}
	
	function displayFormMessage(msg){
	qo_messageDiv.innerHTML = msg;
	setTimeout(function(){ deleteprior(qo_messageDiv) },6000);
	}
	
