// This file was written by OTBIS Limited

// Globals:
var gItem_num = 0;
var gItems_ordered = 0;
var MAXARRAY = 50
var gItemlist = new createArray(MAXARRAY);
var DEBUG = 0;

initialize_arrays(gItemlist)

//containers:
function product(code,price,desc,quan,url) {
	this.price = 0;
	this.code = code;
	this.price = price;
	this.desc = desc;
	this.quan = quan;
	this.url = url;
	return this;
}

//=============================================================================
// API functions:
//=============================================================================

//=========================================================
// Function: Add an item to the basket:
// Parameters: element ID, Product Code, price, Description
//
function addToBasket(itid,pcd,gbp,desc) {
	elm = document.getElementById(itid);
	var v_quant = elm.value;
	var v_url = document.location;
	additem(pcd,gbp,desc,v_quant,v_url);
	update_cart();
}

//=========================================================
// Function: Refresh the shopping cart:
// Parameters: none
//
function refreshCart() {
	if( DEBUG == 1 )
		alert("refreshCart");
	var v_output = "cart:\n";
	for(var ind=0; ind<MAXARRAY; ind++ ) {
		var v_id = "ind"+ind;
		var v_tmp = getCookie(v_id);
		if( v_tmp != null ) {
			var v_array = new Array();
			v_array = v_tmp.split('|');
			additem(v_array[3],v_array[2],v_array[0], v_array[1],document.location)
		}
		v_output +="\n";
	}
	update_cart();
}

//=========================================================
// Function: Modify cart items and rewrite cart page:
// Parameters: element ID, Product Code, price, Description
//
function modCartItem(itid,pcd,gbp,desc) {
	elm = document.getElementById(itid);
	var v_quant = elm.value;
	var v_url = document.location;
	if( gItem_num < 1 ) { // rebuild the list
		for(var ind=0; ind<MAXARRAY; ind++ ) {
			var v_id = "ind"+ind;
			var v_tmp = getCookie(v_id);
			if( v_tmp != null ) {
				var v_array = new Array();
				v_array = v_tmp.split('|');
				additem(v_array[3],v_array[2],v_array[0], v_array[1],document.location);
			}
		}
	}
	additem(pcd,gbp,desc,v_quant,document.location);
	storeShoppingCart();
	writeOrderPage();
}

//-----------------------------------------------------------------------------
// Shopping cart functions:
//-----------------------------------------------------------------------------

//=========================================================
// Function: add the item to the cart:
// Parameters: code,price,description,quantity,uri
//
function additem(codes,prices,descrip,quan,url) {
	if( DEBUG == 1 )
		alert("additem");
	var v_loc = check_if_in(codes);
	if (v_loc != -1) {
		// update existing item
		gItemlist[v_loc] = new product(codes,prices,descrip,quan,url);
	}
	else // new item
	{
		gItemlist[gItem_num] = new product(codes,prices,descrip,quan,url);
		gItems_ordered = gItem_num;
		gItem_num = gItem_num + 1;
	}
	remove_nil_items();
}

//=========================================================
// Function: Update the shopping cart:
// Parameters: none
//
function update_cart() {
	if( DEBUG == 1 )
		alert("update_cart");
	// show the cart to the page
	var v_str_out = '';
	var v_item_count = 0;
	for(var ind=0; ind<gItemlist.length; ind++ ) {
		if( gItemlist[ind] != undefined ) {
			if( gItemlist[ind].quan != 0 ) {
				v_str_out += '<p>' + gItemlist[ind].quan + ' x ' + gItemlist[ind].desc + ' : £' + gItemlist[ind].price + '</p>';
				v_item_count++;
			}
		}
	}

	if( v_item_count <= 0 ) {
		v_str_out += '<p>~ Your basket is empty ~</p>';
	}

	document.getElementById('goods').innerHTML = v_str_out;
	var v_tc = calcTotalPrice();
	document.getElementById('tot_cash').innerHTML = v_tc;
	document.getElementById('tot_item').innerHTML = calcTotalGoods();
	storeShoppingCart();
}

//=========================================================
// Function: Remove the null items:
// Parameters: none
//
function remove_nil_items() {
	if( DEBUG == 1 )
		alert("remove_nil_items");
	var v_i = 0; 
	var v_j = 0;
	var v_temp_array = new Array(MAXARRAY);
	gItems_ordered = 0;
	
	for( v_i=0; v_i<MAXARRAY; v_i++) {
		if( gItemlist[v_i] != undefined ) {
			
			if( typeof(gItemlist[v_i].quan) == "undefined" )
			{
				//Clear out any duff entries.
				gItemlist[v_i].quan = 0;
			}
			
			if (gItemlist[v_i].quan != 0) {
				v_temp_array[v_j] = gItemlist[v_i];
				gItems_ordered = v_j ;
				v_j+=1;
			}
			else {
				var v_cookie = getCookie("ind"+v_i);
				if( v_cookie != null ) {
					eraseCookie("ind"+v_i);
				}
			}
		}
	}
	gItemlist = v_temp_array;
	gItem_num = gItems_ordered + 1;
}

//=========================================================
// Function: Saves the cart to cookies:
// Parameters: none
//
function storeShoppingCart() {
	for(var ind=0; ind<gItemlist.length; ind++ ) {
		if( gItemlist[ind] != undefined ) {
			if( gItemlist[ind].quan != 0 ) {
				var v_name = "ind"+ind;
				var v_value = gItemlist[ind].desc+'|'+gItemlist[ind].quan+'|'+gItemlist[ind].price+'|'+gItemlist[ind].code;
				setCookie(v_name,v_value,0);
			}
		}
	}
}

//=========================================================
// Function: Calculates the total price of the cart:
// Parameters: none
//
function calcTotalPrice() {
	var v_total_item_price = 0;
	for(var ind=0; ind<gItemlist.length; ind++ ) {
		if( gItemlist[ind] != undefined ) {
			if( gItemlist[ind].quan != 0 ) {
				v_total_item_price += eval((gItemlist[ind].price * gItemlist[ind].quan));
			}
		}
	}
	return '&pound;'+v_total_item_price.toFixed(2);
}

//=========================================================
// Function: Calculate the total goods (num):
// Parameters: none
//
function calcTotalGoods() {
	var v_total_goods_count = 0;
	for(var ind=0; ind<gItemlist.length; ind++ ) {
		if( gItemlist[ind] != undefined ) {
			if( gItemlist[ind].quan != 0 ) {
				v_total_goods_count += eval(gItemlist[ind].quan);
			}
		}
	}
	return v_total_goods_count;
}

//-----------------------------------------------------------------------------
// Output functions:
//-----------------------------------------------------------------------------
function writeOrderPage() {
	var v_running_total = 0;
	var v_output = '<table><tr>';
	v_output += '<th width="400">Description</th>';
	v_output += '<th width="200">ppi</th>';
	v_output += '<th width="200">No.</th>';
	v_output += '<th width="200">amount</th></tr>';
	for(var ind=0; ind<MAXARRAY; ind++ ) {
		var v_tmp = getCookie("ind"+ind);
		if( v_tmp != null ) {
			var goods = v_tmp.split('|');
			v_output+='<tr><td>'+goods[0]+'&nbsp;&nbsp;(id#'+goods[3]+')</td>';
			v_output+='<td align="center">&pound;'+goods[2]+'</td>';
			v_output+='<td align="center">';
			v_output+='<input type="textbox" size="2" name="cartitem" id="item'+ind+'" value="'+goods[1]+'" />';
			v_output+='<input type="button" value="Update" onClick="modCartItem(\'item'+ind+'\',\''+goods[3]+'\',\''+goods[2]+'\',\''+goods[0]+'\');" />';
			v_itemtot = goods[1] * goods[2];
			v_output+='</td><td align="center">'+v_itemtot.toFixed(2)+'</td></tr>';
			v_running_total += v_itemtot;
		}
	}
	v_output+='<tr><td colspan="4" style="border-bottom:1px solid black;">&nbsp;</td></tr>';
	if( v_running_total > 0 ) {
		v_output+='<tr><td colspan="3" align="right"><b>TOTAL</b>&nbsp;&nbsp;</td><td align="center">&pound;'+v_running_total.toFixed(2)+'</td></tr>';
	}
	v_output += '</table><br />';
	document.getElementById('checkout').innerHTML = v_output;
}

function writeShippingPage() {
	//generateInvNo(
	var v_running_total = 0;
	var v_itemlist = "";
	var v_output = '<table><tr>';
	v_output += '<th width="400">Description</th>';
	v_output += '<th width="200">ppi</th>';
	v_output += '<th width="200">No.</th>';
	v_output += '<th width="200">amount</th></tr>';
	for(var ind=0; ind<MAXARRAY; ind++ ) {
		var v_cc = 1+ind;
		var v_tmp = getCookie("ind"+ind);
		if( v_tmp != null ) {
			var goods = v_tmp.split('|');
			v_output+='<tr><td>'+goods[0]+'&nbsp;&nbsp;(id#'+goods[3]+')</td>';
			v_output+='<td align="center">&pound;'+goods[2]+'</td>';
			v_output+='<td align="center">'+goods[1]+'</td>';
			v_itemlist+='<input type="hidden" name="item_name_'+v_cc+'" value="'+goods[0]+'">';
			v_itemlist+='<input type="hidden" name="amount_'+v_cc+'" value="'+goods[2]+'">';
			v_itemlist+='<input type="hidden" name="quantity_'+v_cc+'" value="'+goods[1]+'">';
			v_itemtot = goods[1] * goods[2];
			v_output+='<td align="center">'+v_itemtot.toFixed(2)+'</td></tr>';
			v_running_total += v_itemtot;
		}
	}
	v_output+='<tr><td colspan="4" style="border-bottom:1px solid black;">&nbsp;</td></tr>';
	if( v_running_total > 0 ) {
		v_output+='<tr><td colspan="3" align="right"><b>TOTAL</b>&nbsp;&nbsp;</td><td align="center">&pound;'+v_running_total.toFixed(2)+'</td></tr>';
	}
	v_output += '</table><br />';
	document.getElementById('checkout').innerHTML = v_output;
	document.getElementById('itemlist').innerHTML = v_itemlist; 	
}

//-----------------------------------------------------------------------------
// Cookie functions:
//-----------------------------------------------------------------------------

//=========================================================
// Function: Get the cart cookie:
// Parameters: cookie name
//
function getCookie (name) {
	var dcookie = document.cookie; 
	var cname = name + "=";
	var clen = dcookie.length;
	var cbegin = 0;

	while (cbegin < clen) {
		var vbegin = cbegin + cname.length;
		if( dcookie.substring(cbegin, vbegin) == cname ) { 
			var vend = dcookie.indexOf (";", vbegin);
			if (vend == -1) {
				vend = clen;
			}
			return unescape(dcookie.substring(vbegin, vend));
		}
		cbegin = dcookie.indexOf(" ", cbegin) + 1;
		if (cbegin == 0) break;
	}
	return null;
}

//=========================================================
// Function: Saves the cart as cookies:
// Parameters: name, value and exp.
//
function setCookie (name, value, expires) {
        if (!expires) {
		expires = new Date();
	}
	expires.setTime(expires.getTime()+(3*60*60*1000));
	document.cookie = name + "=" + escape (value) + "; expires=" + expires.toGMTString() +  "; path=/";
}

//=========================================================
// Function: Erase the cookie:
// Parameters: cookie name
//
function eraseCookie(name) {
	document.cookie = name + "=\"\"; expires=\"-1\"; path=/";
}

//-----------------------------------------------------------------------------
// Generic/Math functions:
//-----------------------------------------------------------------------------
function createArray(n) {               
	this.length = n;
	var i = 0;
	for( i = 1 ; i < n ; i++ ) {
		this[i] = null;
	}
	return this;
}

//=========================================================
// Function: Initialise any array:
// Parameters: the array to init.
//
function initialize_arrays(arraysa) {
	if( arraysa[0] == "null" )
	//if( typeof(arraysa[0].quant) == "undefined" || typeof(arraysa[0].desc) == "undefined" )
	{
		if( DEBUG == 1 ) {
			alert("First time init for array");
		}
		for (i = 1;i < MAXARRAY;i++) {
			arraysa[i] = new product('',0,'',0,'');
		}
	}
}

//=========================================================
// Function: Check the item is in the basket:
// Parameters: code
//
function check_if_in(code_check) {
	if( DEBUG == 1 )
		alert("checking for "+code_check);
	var v_i = 0;
	
	for( v_i = 0; v_i<gItem_num; v_i++ ) {
		if( gItemlist[v_i] != null ) {
			if( gItemlist[v_i].code == code_check ) {
				//alert("Found "+gItemlist[v_i].desc);
				return v_i;
			}
		}
	}
	return -1;
}

//=========================================================
// Function: generate the invoice number:
// Parameters: the element for the invno. to appear.
//
function generateInvNo( elm ) {

	var cca = new Array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
	var codelen = 8;

	var rc = "HH";
	for( i=0; i<codelen; i++ ) {
		var nc = Math.floor( (Math.random() * cca.length) ); // return a number between 0 and array length:
		if( nc > 9 ) {
			var rn = Math.floor( (Math.random() * 7) ); // 0 or 1:
			if( rn == 1 || rn == 5) {
				var c = cca[nc].toString();
				rc = rc + c.toUpperCase();
			}
			else {
				rc = rc + cca[nc];
			}
		}
		else {
			rc = rc + cca[nc].toString();
		}
	}
	document.getElementById(elm).value = rc;
}

//=============================================================================
//=============================================================================

