// JavaScript Document
var smartTabsObj = []; // master obj
var numberOfItemsInBasket = 0; 
var offerPackagesLoaded = false;
var offersObj = []; 
var order_formDiv;
var orderHasBeenSent = false;
var smartTabsMessage_Div;
var tabCount = 0;
var activeTabCount = 0;

var optionPackages = [
			
	{code: "OPTION1", name: "football", imgID: "OPTION1", heading: "Football Offer", size: "-", quantity: 1, UnitPrice: "109.95", selected: false},
	{code: "OPTION2", name: "rugby", imgID: "OPTION2", heading: "Rugby Offer", size: "-", quantity: 1, UnitPrice: "109.95", selected: false},
	{code: "OPTION3", name: "basketball", imgID: "OPTION3", heading: "Basketball Offer", size: "-", quantity: 1, UnitPrice: "109.95", selected: false},
	{code: "OPTION4", name: "netball", imgID: "OPTION4", heading: "Netball Offer", size: "-", quantity: 1, UnitPrice: "109.95", selected: false}
			];


var offerPackages = []; // data loaded from mySQL database
					 
					 
function getElm(elm){
return document.getElementById(elm);	
}

// this is actioned when index page is loaded
	function getValuesFromServer(){
	var ajaxRequest = setupAJAX();	
	var url = "php/get_values.php";
		var bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime();
		ajaxRequest.open("GET",url+bustcacheparameter, true);
		ajaxRequest.onreadystatechange = function(){
			if(ajaxRequest.readyState == 4){
			if (ajaxRequest.status == 200) {
			var returned_data = ajaxRequest.responseText;
			//alert("From Smart Tabs: "+ajaxRequest.responseText)
			if(ajaxRequest.responseText.length > 0) makeOfferPackages(returned_data);
			}
			}
		}
		 ajaxRequest.send(null); 
	}

function makeOfferPackages(data){
var eachline = 	data.split("**");
var len = eachline.length
for(var i = 0; i <len-1; i++) {
var splits = eachline[i].split("|");
var the_code = splits[0];
var the_heading = splits[1];
var the_items = splits[2].replace(/\r\n|\n/g,"\n" );
var the_price = splits[3];
var the_backgroundCol = splits[4];
var static_img = splits[5];
var the_size = "-";
var the_quantity = 1; 
offerPackages.push( {
				   
				   code: the_code,
				   heading: the_heading,
				   items: the_items,
				   UnitPrice: the_price,
				   backgroundCol:the_backgroundCol,
				   imagegPath: (static_img)? static_img: false,
				   size: the_size,
				   quantity: the_quantity,
				   selected: false
				   
				   } );
}
offerPackagesLoaded = true;
}


function initOffers(){

if(!offerPackagesLoaded){
alert("Data not fully loaded! Please try again in a moment.");	
	return;
}
offersObj = [];
numberOfItemsInBasket = 0;
tabCount = 0; // key for all tabs static and active
activeTabCount = 0; // key for active tabs only
order_formDiv = getElm("order_formDiv"); // global
	// JQuery bindings
	$('#basket_mono').bind('click', function() {
		parse_for_basket();
  		$("#form_slideDownDiv").slideToggle(300);
		});
	
	$('#basket_mono2').bind('click', function() {
		parse_for_basket();
  		$("#form_slideDownDiv").slideToggle(300);
		});
	
	$('#more_offers_button').bind('click', function() {
		setTimeout(hideOffersPanelForOpera, 500); 
  		$("#offers_2_panelDiv").slideDown(300);
		updateBasketItemsDisplay(); // update
		});
	
	$('#back_arrow').bind('click', function() {
		getElm("offers_1_panelDiv").style.top= "30px";
  		$("#offers_2_panelDiv").slideUp(300);
		updateBasketItemsDisplay(); // update
		});
	
smartTabsMessage_Div = getElm("smartTabsMessage_Div");	
create_form_labels(); // for order form
setTimeout(embedTab, 200); // delay to allow DOM to settle down
}

// Opera has a bug where swf's tend to show through our shopping basket slidedown panel, so we temporarily move them out of the way
function hideOffersPanelForOpera(){
getElm("offers_1_panelDiv").style.top = "-1000px";	
}
// returned from static swf tab
function clickthrough(){
setTimeout(hideOffersPanelForOpera, 500); 
$("#offers_2_panelDiv").slideDown(300);
updateBasketItemsDisplay();
}

function displayCompleteForm(){
if(!numberOfItemsInBasket) return;
$("#complete_order_slideDownDiv").slideToggle(300);	
}

function closeBasketForm(){
$("#form_slideDownDiv").slideUp(300);	
}

function embedTab(){
var flashvars = {};
var params = {wmode:"opaque", AllowScriptAccess: "always"};
var attributes = {};
if(offerPackages[tabCount].imagegPath){
swfobject.embedSWF("swf/ball_offers_static_tab.swf", "smartTab"+tabCount, "250", "172", "9.0.0", false, flashvars, params, attributes, collectObj); // static tab
}else{
swfobject.embedSWF("swf/smart_tabs_display.swf", "smartTab"+tabCount, "250", "172", "9.0.0", false, flashvars, params, attributes, collectObj); // active tab
}
}

function collectObj(e){
	if(e.success){
	offersObj.push( {swf: e.ref, err: false, key: null} );	
	setTimeout(displayOffersText, 250); // delay to allow swf to embed
	}
}
	
function displayOffersText(){
		offerPackages[tabCount].div = offersObj[tabCount].swf;
		offerPackages[tabCount].div.style.cssText ="border: 2px solid #fff; padding: 2px;";
		
			try{
			offersObj[tabCount].swf.receiveValues(activeTabCount, offerPackages[tabCount].heading, offerPackages[tabCount].items, offerPackages[tabCount].UnitPrice, offerPackages[tabCount].backgroundCol);
			}catch(e){
			//offersObj[tabCount].swf.parentNode.innerHTML = '<h2 style="color: #5fceea; text-align: center;">Sorry this tab is unable to be shown</h2>';
			alert(e.message);
			offersObj[tabCount].err = true; // used for double checks
			}
			
			if(tabCount < 5){
			if(!offerPackages[tabCount].imagegPath){
			offersObj[tabCount].key = activeTabCount; // maps array key for 'active' tabs	
			activeTabCount++; // make sure activeTabCount key is correct as we need a key for active tabs
			}
			tabCount++;
			embedTab();
			}else{
			buildMasters();
			//setTimeout(doubleChecks, 200); // check that all swf's did embed and that their text loaded
			}
}

// this is a 'failsafe' if a swf fails to load we try sending text again
function doubleChecks(){
for(var i = 0; i <offersObj.length; i++) {
if(offersObj[i].err){
	
		try{
		offersObj[i].swf.receiveValues(offersObj[i].key, offerPackages[tabCount].heading, offerPackages[tabCount].items, offerPackages[tabCount].UnitPrice, offerPackages[tabCount].backgroundCol);
		}catch(e){
		offersObj[i].swf.parentNode.innerHTML = '<h2 style="color: #5fceea; text-align: center;">Sorry this tab is unable to be shown</h2>';
		}
}
}
}



// This receives clicked tabs key back from swf
function receiveSelected(key){
		smartTabsObj[key].toggleSelected();	// toggle border around div to show/hide its selection
		updateBasketItemsDisplay();
}

function updateBasketItemsDisplay(){
	getElm("goods_in_basket").innerHTML = (numberOfItemsInBasket>0)? numberOfItemsInBasket : "";
	getElm("goods_in_basket2").innerHTML = (numberOfItemsInBasket>0)? numberOfItemsInBasket : "";

}



function receiveSelectedOption(obj){
for(var i = 0; i <=4; i++) {
		if(obj.key == i){
			
			if(optionPackages[i].selected == true){
			obj.style.cssText = "border: 2px solid #fff; padding: 2px; cursor: pointer;";
			optionPackages[i].selected = false;
			numberOfItemsInBasket--;
			}else{
			obj.style.cssText = "border: 2px solid #cc6600; padding: 2px; cursor: pointer;";
			optionPackages[i].selected = true;
			numberOfItemsInBasket++;
			}
		}
	}
	updateBasketItemsDisplay();
}


// build master smartTabsObj array which contains DOM for display in form and values we can use in other parts of the program
function  buildMasters(){
	smartTabsObj = [];
	var key = 0;
	// build for offerPackages
	for(var i = 0; i < offerPackages.length; i++) {
		var thisObj = offerPackages[i];
		var UnitPrice = (encodeURIComponent(thisObj.UnitPrice.substr(0,1))=="%C2%A3")? thisObj.UnitPrice.substr(1) : thisObj.UnitPrice;// remove any £ sign ;
		if(!thisObj.imagegPath){
			smartTabsObj.push(new form_row_constructor(thisObj.code, thisObj.heading, thisObj.size, thisObj.quantity, UnitPrice, key, thisObj.div));
			key++;
		}
		}
		// and for optionPackages
		for(var i = 0; i < optionPackages.length; i++) {
		var thisObj = optionPackages[i];
		var div = getElm("OPTION"+(i+1));
		div.style.cssText ="border: 2px solid #fff; padding: 2px; cursor: pointer;";
		div.key = key; // so we can pass it in the following onclick
		div.onclick = function(){receiveSelected(this.key)};
		smartTabsObj.push(new form_row_constructor(thisObj.code, thisObj.heading, thisObj.size, thisObj.quantity, thisObj.UnitPrice, key, div));
		key++;
		}
		
	}
	
	
	

/*  Shopping Basket functions */
	
	
	function parse_for_basket(){
	numberOfItemsInBasket = 0;
	deleteprior(order_formDiv); // clear for new population
	for(var i = 0; i < smartTabsObj.length; i++) {
		var thisObj = smartTabsObj[i];
		if(thisObj.selected){
			order_formDiv.appendChild(thisObj.newrow);
			numberOfItemsInBasket++;
			}
			document.getElementById("intructionsDiv").style.display = "block";
			// create total price strip
			var newinput = document.createElement("input");
			var accrued_priceDiv = document.getElementById("accrued_priceDiv");
			deleteprior(accrued_priceDiv);
			newinput.setAttribute("type","text");
			newinput.setAttribute("readonly","true");
			newinput.id = "totalPrice";
			newinput.style.cssText = "width: 660px; color: black; background-color: #F5F5F5; text-align: right;";
			accrued_priceDiv.appendChild(newinput);
			recalc_form_height();
			recalcTotal();	
		}
		
	if(!numberOfItemsInBasket) {
		getElm("order_formDiv").innerHTML = "<p style='font-size: 12pt; font-weight: bold; text-align: center;'>Your basket is empty</p>";
		deleteprior(getElm("accrued_priceDiv")); // get rid of Total box if present
		getElm("intructionsDiv").style.display = "none";
	}
	}
	
	
	
	

	function deleteprior(div){
	if(!div) return;
	while (div.firstChild){
    div.removeChild(div.firstChild);
 	}
	}
	
	
	
	/* Order Form functions */
	
	
	function create_form_labels(){
	var labelsdiv = document.getElementById("form_labels");
	var thesizes = new Array("80","340","110","50","40");
	var thenames = new Array("Code","Product Description","Size/weight/colour","Quantity","Price");
	for(var i = 0; i <5; i++) {
	var newinput = document.createElement("input");
	newinput.setAttribute("type","text");
	newinput.setAttribute("readonly","true");
	newinput.style.cssText = "color: #FFFFFF; background-color: #3f3f3f; width:"+thesizes[i]+"px;";
	newinput.value =thenames[i];
	labelsdiv.appendChild(newinput);
	}
	}
	
	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 recalc_form_height(){
	var startHeight = 150 + 27;
	startHeight += numberOfItemsInBasket*18; // add total height of each line of data
	document.getElementById("form_slideDownDiv").style.height = startHeight+"px";
	}
	
	function form_row_constructor(input_code,description,size,quantity,UnitPrice, key, tab){
	this.selected = false; // has this tab associated with this row been clicked
	this.heading = description;
	var input = "";
	var newspan = document.createElement("span");
	var thesizes = new Array("80","340","110","30","60");
	for(var k = 0; k <5; k++) {
	var newinput = document.createElement("input");
	newinput.setAttribute("type","text");
	newinput.style.cssText="width:"+thesizes[k]+"px;";
	switch (k) {
	case 0:
	newinput.value = input_code;
	this.input_code = input_code;
	newinput.setAttribute("readonly","true");
	break;
	case 1:
	newinput.value = description;
	this.description = description;
	newinput.setAttribute("readonly","true");
	break;
	case 2:
	newinput.value = size;
	this.size = size;
	newinput.setAttribute("readonly","true");
	break;
	case 3:
	newinput.value = quantity;
	newinput.onchange = function(){recalcForChangedQuantity(this.value, UnitPrice, key);};
	this.quantity = quantity;
	break;
	case 4:
	// at this point UnitPrice is a string - it needs to be a number for calculations
	UnitPrice = Number(UnitPrice);
	this.UnitPrice = UnitPrice;
	var total = quantity * UnitPrice;
	newinput.value = total.toFixed(2);
	newinput.style.textAlign = "right";
	newinput.setAttribute("readonly","true");
	this.priceBox = newinput;
	newinput.onclick = function(){recalcUnitPrice(key)};
	break;	
	}
	newspan.appendChild(newinput);
	}
	this.toggleSelected = function(){
	if(this.selected){
	tab.style.cssText = "border: 2px solid #fff; padding: 2px";
	this.selected = false;
	numberOfItemsInBasket--;
	}else{
	tab.style.cssText = "border: 2px solid #cc6600; padding: 2px;";
	this.selected = true;
	numberOfItemsInBasket++;
	}
	}
	//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(){remove_line(key);};
	 newspan.appendChild(delete_icon); //append icon to its div
	this.newrow = newspan;
	}
	
	function recalcForChangedQuantity(quantity, UnitPrice, key){
	var priceBox = smartTabsObj[key].priceBox;
	var total = quantity * UnitPrice;
	priceBox.value = total.toFixed(2); // recalculated price
	smartTabsObj[key].quantity = quantity; // save back to master obj
	recalcTotal();
	}
	
	function recalcUnitPrice(key){
	var oldPrice = Number(smartTabsObj[key].UnitPrice).toFixed(2);
	var newValue = prompt("You can only change the Unit Price.\nPlease input a new price - which will be recalcuated against quantity.\n", oldPrice);
	if (newValue != "" && newValue != null) {
	smartTabsObj[key].UnitPrice = newValue;
	recalcForChangedQuantity(smartTabsObj[key].quantity, smartTabsObj[key].UnitPrice, key);
	}
	}
	
	function recalcTotal(){
	var newTotal = 0;
	for(var i = 0; i <smartTabsObj.length; i++) {
	if(smartTabsObj[i].selected) newTotal += parseFloat(smartTabsObj[i].priceBox.value);	
	}
	newTotal = newTotal.toFixed(2);
	document.getElementById("totalPrice").value = "Total (not Inc VAT): \u00A3"+newTotal;
	}
		
	function remove_line(key){
		smartTabsObj[key].toggleSelected();
		parse_for_basket();
		updateBasketItemsDisplay();
	}
	
	
	
	/* Send order */ 
	
	function submit_order(){
	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 order_formDiv = document.getElementById("order_formDiv");
	var spans = order_formDiv.getElementsByTagName("span");
	//form checking
	if (!valid_email_check(email)) error_flag = 2;
	if (!organisation)  error_flag = 1;
	if (!invoice_address)  error_flag = 1;
	if (!name) error_flag = 1;
	if (!phone) error_flag = 1;
	
		switch(error_flag){
		case 1:
	 	smartTabsMessage_Div.innerHTML = "Sorry, a mandatory field has not been completed.";
		return;
		break;
		case 2:
		document.getElementById("email").focus();
		smartTabsMessage_Div.innerHTML  = "Sorry, the e-mail address is incomplete or malformed.";
		return;
		break
		}
		
	if(orderHasBeenSent){
	smartTabsMessage_Div.innerHTML = "Sorry, this order has already been sent.";
	return;
	}
		
	if (!error_flag){
	
	//build tables for order details
	var thetables = '<table width="100%" cellpadding="2" cellspacing="1" style="border: solid 1px grey; font-family:Arial,Helvetica,sans-serif;font-size:11px; margin-bottom:3px;">';
					for(var i = 0; i <smartTabsObj.length; i++) {
					if(!smartTabsObj[i].selected) continue;
					thetables += '<tr>';
					thetables += '<td width="10%">'+smartTabsObj[i].input_code+'</td>';
					thetables += '<td width="40%">'+smartTabsObj[i].description+'</td>';
					thetables += '<td width="30%">'+smartTabsObj[i].size+'</td>';
					thetables += '<td width="20%">'+smartTabsObj[i].quantity+'</td>';
					thetables += '<td width="20%">'+smartTabsObj[i].priceBox.value+'</td>';
					thetables += '</tr>';
					}
	// add total price row
	var total=document.getElementById("accrued_priceDiv").firstChild.value;
	thetables += '<tr style="text-align: right;"><td colspan="5">' + total + '</td></tr>';
					   
	thetables +=  '</table></body></html>';

	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{
		
	}
	}
	
	function post_data_to_server(organisation,invoice_address,delivery_address,account_num,order_num,email,name,phone,thetables){
	smartTabsMessage_Div.innerHTML = "<img src='images/ajax-loader.gif' />";
	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;
	var ajaxRequest = setupAJAX();	
	ajaxRequest.open("POST", "php/send_html_email_to_woolmers.php", true); 
	ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	//Wait for response
	ajaxRequest.onreadystatechange = function() {
	if(ajaxRequest.readyState == 4){
		    if(ajaxRequest.status==200){
			var returned_message = ajaxRequest.responseText;
			if(returned_message == 1){
			smartTabsMessage_Div.innerHTML = "Thank you - Your order has been sent.";
			orderHasBeenSent = true;
			deleteprior(order_formDiv); // clear out data
			}else{
			smartTabsMessage_Div.innerHTML = "Sorry, there was a server problem, please try again later.\n\nIf the problem persists please use e-mail, fax or phone to send us your order.";	
			}
			}else{
            smartTabsMessage_Div.innerHTML = "Sorry, there was a server problem, please try again later.\n\nIf the problem persists please use e-mail, fax or phone to send us your order.";
			}
		}
	}
	ajaxRequest.send(sendstring);

	}
	
	/* Cookie stuff */
	
	function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+escape(value)+expires+"; path=/";
}

function readCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ';', len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
	}
	
function eraseCookie(name) {
	createCookie(name,"",-1);
}



  
// DHTML email validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
function valid_email_check(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    return false
		 }

 		 return true					
		}

		
		/* Printing Functions */

	function send_to_print(){
		if (smartTabsObj.length == 0) return; // no rows to print
		var printString = "";
		for(var i = 0; i <smartTabsObj.length; i++) {
		if(!smartTabsObj[i].selected) continue;	
		printString+= smartTabsObj[i].input_code+"|";
		printString+= smartTabsObj[i].description+"|";
		printString+= smartTabsObj[i].size+"|";
		printString+= smartTabsObj[i].quantity+"|";
		printString+= smartTabsObj[i].UnitPrice+"**";
		}
		createCookie("woolmerOffersBasket",printString,1); // cookie needed to pass data to print window
	
		window.open("printing_page.html","printWindow");	
	}

					
