var quickorder = (function() {
					
var api=[]; // make object to attach methods to

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 qoTotal = 0; // numeric
var qoTotalBox; // DOM input box which includes £ sign
var qoObj = [];
var bestsellersObj = [];
var formHeight = 180;
var qo_top_wrapperHeight = 145;
var priceBoxAlignment = "center";
var qoHasBeenSent = false;
var defaultFirstLineAdded = false;
var best_sellers_messageDiv;

var errorLock = false;


function getElm(elm){
return document.getElementById(elm);	
}

api.setup = function(){
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");
best_sellers_messageDiv = document.getElementById("best_sellers_message");
qoObj = []; // in case of reset
deleteprior(qo_form); // ditto
qoHasBeenSent = false; // 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();
// timer for the benefit of IE
setTimeout(function(){
api.newline(); // make first line
var firstLine = qoObj[qoObj.length-1].wrapper; // need to set class of first blank line to "defaultBlankLine"
firstLine.setAttribute("className","defaultBlankLine");	
firstLine.setAttribute("class","defaultBlankLine");					
}, 500);
// 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: 631px; 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");
api.recalcTotal();
}


api.newline = function() {
write_log("Adding new line to form");
deleteprior(best_sellers_messageDiv);
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; // initally 180px
formHeight+= 20;
quick_order_formDiv.style.height = formHeight+"px";
// add extra height to qo_top_wrapper so elements remain correctly positioned
qo_top_wrapperHeight+=20;
qo_top_wrapper.style.height = qo_top_wrapperHeight+"px";
qoObj.push( new line_constructor() );
qo_form = getElm("quick_order_form");
qo_form.insertBefore(qoObj[qoObj.length-1].wrapper, qoTotalBox); // insert new line above Total Box
}


api.setPriceBoxAlignment = function(which){ priceBoxAlignment = which; };

api.qoSent =  function(){ return qoHasBeenSent };

api.defaultLine = function(){ return defaultFirstLineAdded };

function makeLabels(){
	var thesizes = new Array("65","300","135","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("className","qoLabel");
	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 thesizes = new Array("65","300","135","48","55");
	var wrapper = document.createElement("span");
	wrapper.style.display = "inline"; // we change this to 'none' when deleting which saves a lot of messing with the qoObj array
	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;
	this.size.isBestSeller = false; // add extra property so we can set it from outside constructor
	newinput.onfocus = function(){
		
		if(this.style.color == "rgb(255, 0, 0)"){
			this.value = ""; 
			this.style.color = "#000"; 
		}
		};
	newinput.onblur = function(){
		this.style.color = "#000";
		write_log("isBestSeller: " + this.isBestSeller)
		if(this.value == "" && this.isBestSeller){
		this.value = "Please fill in value";  
		this.style.color = "#ff0000"; 
		}
		};
	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 recalcTotal which multiplies the UnitPrice with quantity
		api.recalcTotal();
		}else{
		errorLock = true;
		}
	
	};
	break;
	case 4:
	this.priceBox = newinput;
	newinput.style.textAlign = "center"; // centred for manual 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);
	if(isNaN(amount)) amount = 0;
	this.value = amount.toFixed(2); // recalculated price
	api.recalcTotal();
	if($("#quick_order_form").children().hasClass("defaultBlankLine")){
	$(".defaultBlankLine").removeClass("defaultBlankLine").addClass("qoItem");
	bestsellers.displayItemCount(); // bump up to reflect that items has been added. Done subsequently by newline()
	}
	};
	break;	
	}
	wrapper.appendChild(newinput);
	}
	
	//create delete icon
	 var delete_icon = document.createElement("img");// create an image
	 delete_icon.style.cursor = "pointer";
	 delete_icon.src = 'images/delete_icon.png';
	 delete_icon.onclick = function(){this.parentNode.style.display = "none"; api.recalcTotal(); bestsellers.displayItemCount(); };
	 wrapper.appendChild(delete_icon); //append icon to its div
	 
	 
		this.wrapper = wrapper;
		this.total = 0; // added in recalcTotal()
}

	
	api.recalcTotal = function(){
	if(errorLock) return;
	var newTotal = 0;
	for(var i = 0; i <qoObj.length; i++) {
	if(qoObj[i].wrapper.style.display == "none") continue; // meaning the item has been deleted and shouldn't be counted 
	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;
	}
	
	api.getItemCount = function(){
	var count = 0;
	for(var i = 0; i <qoObj.length; i++) {
	var itsClass = qoObj[i].wrapper.getAttribute("class");
	if(qoObj[i].wrapper.style.display == "none" || itsClass == "defaultBlankLine") continue; // meaning the item has been deleted and shouldn't be counted 
	count++;
	}
	return (count > 0)? count : ""; // don't return a zero as it looks odd
	};
	
	
	
	api.addBestSeller = function(obj){
	if($("#quick_order_form").children().hasClass("defaultBlankLine")){
	$(".defaultBlankLine").removeClass("defaultBlankLine").addClass("qoItem"); // swap out 'defaultBlankLine' class as we are just about to use it	
	}else{
	api.newline(); 
	}
	if(obj.message){
	qoObj[qoObj.length-1].size.style.color = "#ff0000";
	}
	qoObj[qoObj.length-1].input_code.value = (obj.code);
	qoObj[qoObj.length-1].description.value = (obj.name);
	qoObj[qoObj.length-1].size.value = (obj.size);
	qoObj[qoObj.length-1].size.isBestSeller = true;
	qoObj[qoObj.length-1].quantity.value = (obj.quantity);
	qoObj[qoObj.length-1].priceBox.value = (obj.UnitPrice);
	qoObj[qoObj.length-1].priceBox.style.textAlign = "right";
	api.recalcTotal();
	}
	

	api.submit = function(){
	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 (not Inc. VAT): '+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");
	}
	}




	api.show_delivery_input = function(){
	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/order_confirmation_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);
	}
	


return api;
	  
}());

