//
// TODO
// This needs a elements cookie to record the number of products in the list.
// This wil make the getCookieArray loop until it has found all the cookies
//
today=new Date();
today.setTime(today.getTime() + (3600000));
today=today.toGMTString();
currentdate=new Date();
currentdate=currentdate.toLocaleString();
var expdate=new Date()
expdate.setDate(expdate.getDate()+5)
var productlist = new getCookieArray("gbproduct");

// Check out
function checkoutBasket( ) {
	if( isEmpty() ) {
		alert("You need to have items in your basket to checkout");
	} else {
		var frm = document.frmControler;
		frm.method.value = "checkoutBasket";
		gotoURL('/shoporder.php?method=checkoutBasket');
	}
}

// Add a value to the session
function productSelector( pid ) {
	//alert ("Call to addToBasket");
	var frm = document.frmProductSelector;
	frm.producttype.value = pid;
	frm.method.value = "";
	frm.submit();
}

// Add a value to the session
function addToBasket( pid, cost ) {
	//alert ("Call to addToBasket");
	var frm = document.frmProducts;
	frm.productid.value = pid;
	frm.method.value = "addToBasket";
	
	// Test for full basket
	var productlist = new getCookieArray("gbproduct");
	if( productlist.length >=10 ) {
		alert("You can only buy 10 products");
		return;
	}
	
	// Test to make sure the product is not already in the basket
	if ( checkExists( pid ) ) {
		alert("Product already in basket");
		return;
	}

	productlist = new setCookieArray("gbproduct", pid );
	var total = parseFloat(getCookie( "gbtotal"));
	
	if ( total>0 ) {
		total = ( total + parseFloat(cost) );
		producttoal = new setCookie("gbtotal", total, expdate  );
	} 
	else {
		total = parseFloat(cost);
		producttoal = new setCookie("gbtotal", total, expdate  );
	}
	frm.submit();
}

// Clears all values from the session
function refreshBasket( ) {
	//alert ("Call to emptyBasket");
	// Load the control form
	var frm = document.frmControler;
	frm.method.value ="refresh";
	frm.submit();
	return;
}

// Clears all values from the session
function emptyBasket( ) {
	//alert ("Call to emptyBasket");
	// Load the control form
	var frm = document.frmControler;
	frm.method.value ="emptyBasket";

	// See if there are any products within the basket
	if ( !isSet( productlist[1] ) ) {
		alert("There are no items in your baskets");
		return;
	}
	// Confirm the deletion of the basket
	if ( confirm( "Are you sure you wish to empty your basket?" ) ) {
			delCookie( "gbproduct");
			frm.submit();
	}
	return;
}

// Populated the cookies values using an array index
// This is used to store mulitiple PID with one cookie
function getCookie (name) {
	//alert ("Call to getCookie");
	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;
}

// Setup the default values for the cookie
function setCookie (name, value, expires) {
	//alert ("Call to setCookie");
        if (!expires) 
		expires = new Date();
	document.cookie = name + "=" + escape (value) + "; expires=" + expires.toGMTString() +  "; path=/";
}

// Removes the cookies from the system therefore emptying the basket
function delCookie (name) {
	var expireNow = new Date();
	var productlist = new getCookieArray("gbproduct");
	document.cookie = "gbtotal=; expires="+expireNow+"; path=/";
	for( var x=0;x<productlist.length; x++) {
		document.cookie = name + x + "=; expires="+expireNow+"; path=/";
	}
}

// Remove a product from the shopping basket
function delProduct( name, price ) {
	var expireNow = new Date();
	var productlist = new getCookieArray("gbproduct");
	var items = productlist.length; // Need to know how many items where in the basket
		
	for( var x=0;x<=items; x++) {
	// Cookie value is x-1 as it starts at 0
	var cookie_x = x-1;
		if (productlist[x] == name ) {
//			document.cookie = "gbproduct" + cookie_x + "=; expires="+expireNow+"; path=/";
			resetCookies( x );
		}
	}
	recalcTotal( price );
	refreshBasket( );	
	alert("Product removed from your basket");		
}

// Reset total
function recalcTotal( price ) {
	var total = parseFloat(getCookie( "gbtotal"));
	
	if ( total>=price ) {
		total = ( total - parseFloat(price) );
		producttoal = new setCookie("gbtotal", total, expdate  );
	} 
}

// Reorder the ADT
// If you delete a cookie that is in the middle of the array you need to bring the other
// cookies values in syc. This is a linklist ADT at its dirtiest. :)
// x if the cookie value that was deleted, note that cookie values start at 0
function resetCookies( node ) {
	var expireNow = new Date();
	var productlist = new getCookieArray("gbproduct");
	for(x=node;x<productlist.length;x++) {
		var cookie_x=x-1;
		document.cookie = "gbproduct" + cookie_x + "=" + productlist[x+1] + "; expires=" + expdate +  "; path=/";
	}
	x--;
	document.cookie = "gbproduct" + x + "=; expires=" + expireNow +  "; path=/";	
}

// Sets the values for the new cookie
// TODO Add a system that append the current cookie
function setCookieArray(name) {
	//alert ("Call to setCookieArray");
	// Load the cookie if it exists
var productlist = new getCookieArray("gbproduct");
// If the cookie is empty, create it and enter the product
	if( !isSet( productlist[1] ) ) {
        	this[0] = setCookieArray.arguments[1]
        	setCookie (name+"0", this[0], expdate);
	}
	// If the cookie exists move to the last elements an populate
	else {
		this.length = setCookieArray.arguments.length;	
		var i = productlist.length;	
      productlist[i] = setCookieArray.arguments[1];
      setCookie (name+i, productlist[i], expdate);
	}
}

// Returns the current cookie values, this is used in the main HTML to get the values
// Because we can only delete one product at a time we test to see if the next element is nul aswell.
// If it is then that must be the end of the list
// If a visitor deleted a product in the middle of a list then this method would stop at the element before the deleted
// Product. This is not the right procedure for this method. Therefore it does a double test
function getCookieArray(name){
	//alert ("Call to getCookieArray");
	var i = 0;
	var next = i+1;
        while (getCookie(name + i) != null ) {
        this[i + 1] = getCookie(name + i);
        i++; this.length = i; 
        }
}

// This method check to see if the product is already in the basket
// If it is we do not what them to add it again
function checkExists( name ) {
	var expireNow = new Date();
	var productlist = new getCookieArray("gbproduct");
	var items = productlist.length; // Need to know how many items where in the basket
		
	for( var x=0;x<=items; x++) {
	// Cookie value is x-1 as it starts at 0
		if (productlist[x] == name ) {
			return true;
			alert("Found");
		}
	}
	return false;
}

// Test if the cookie is empty
function isSet( value ) {
	//alert ("Call to isSet");
	if ( value == "undefined" || value ==null )
		return false;
	else
		return true;
}

// Test if the basket is empty
function isEmpty( ) {
	var productlist = new getCookieArray("gbproduct");	
	if ( isSet(productlist.length)){
		return false;
	} else {
		return true;
	}
}

// GoTO URL
function gotoURL( arg ) {
	window.location=arg;
}
	

// A general testing function
function test( arg ) {
	alert( "Test function call : " + arg );
}