var orderdata;  

var delvCharge = "0.00";
var percentage = "false";
var storeLimit = 0;
      
var basketSize = 4*1024;        
var gtot=0.00;
var prevCookieVal="";
var tmp_p_name, tmp_p_no, tmp_p_price, tmp_p_qty, tmp_p_skuname="", tmp_p_skuattr="";   
var allcookies="", basketTable;

var onButtons = 1;	
var allcookies="", basketTable;
var disablePurchase = false;    
var disableMessage = "To order this product, please call <B>Free</B><I>fone 0800 </I><B>309 080</B> <BR>between 8am and 6pm, Monday to Saturday.";      


function MyArray(length) {
	this.size = length;
	this.length = 0;
	for(var i=1; i<=this.size; i++) this[i] = null;
}

var exit = false;
var debugging = false;
var debug = false;
var debugg = false;

var names = new MyArray(0);
var values = new MyArray(0);



function updateAttributes(name, val, no, pos) {
	//alert(name + " " + val + " " + no + " " + pos);
	var res = splitter(name, ":");
	names[pos] = res[2];
	if(debug) confirm("names[" + pos + "] = " + res[2]);
	values[pos] = val;
	if(debug) confirm("values[" + pos + "] = " + values[pos]); 
	tmp_p_no = no; 
	if (names.length < pos) names.length = pos;
}


function updateListAttributes(name, val, pos) {
	//alert(name + " " + val + " " + pos);
	var res = splitter(name, ":");

	values[pos] = val;
	names[pos] = res[2];

	//alert(values[pos] + " " + tmp_p_no);
	if (names.length < pos) names.length = pos;
}

function updateTextAttributes(name, val, pos) {
	var res = splitter(name, ":");
	values[pos] = val;
	names[pos] = name;

	//alert(values[pos] + " " + tmp_p_no);
	if (names.length < pos) names.length = pos;
}

function updateTextAreaAttributes(name, val, pos) {
	var res = splitter(name, ":");

	values[pos] = val;
	names[pos] = name;

	//alert(values[pos] + " " + tmp_p_no);
	if (names.length < pos) names.length = pos;
}





function processAttributes() {
	var result = "";

	if(debug) confirm("Entered processAttributes()");

	for(var count = 1; count <= names.length; count++) {
		result +=  names[count] + ":" + values[count] + ":"; 
	}
	if(debug) confirm("The result is: " + result);
	return result;
}


function findUnchangedAttributes(number, defaults) {
	names.length = number; 
	if(debug) confirm("Entered findUnchangedAttributes()");
	var tmpArr = splitter(defaults, ";");
	for(var count = 1; count <= names.length; count++) {
		var tmpArr1 = splitter(tmpArr[count-1], ":");
		if (names[count] == null) {
			if (debugg) confirm("Found an unset attribute");
			if (debugg) confirm("The value we're interested in is " + tmpArr[count-1]);	
			//if (tmpArr1[0] == "LIST") continue;
			if (tmpArr1[0] == "OTEXT") continue;
			if (tmpArr1[0] == "OTEXTAREA") continue;
			if ((tmpArr1[0] == "MTEXT")) alert(values[count]);
			if ((tmpArr1[0] == "MTEXT") && (values[count] == null)) {
				alert("Mandatory input field not completed for product: "
				+ tmpArr1[1]);
				exit = true;
			}
			if ((tmpArr1[0] == "MTEXTAREA") && (values[count] == null)) {
				alert("Mandatory input field not completed for product: "
				+ tmpArr1[1]);
				exit = true;
			}
 
			names[count] = tmpArr1[0];
			values[count] = tmpArr1[1];
			if (names.length < count) names.length = count;

		} else {
			if ((tmpArr1[0] == "MTEXT") && (values[count].length ==0)) {
				alert("Mandatory input field not completed for product: " + tmpArr1[1]);
				exit = true;
				return;
			}
			if ((tmpArr1[0] == "MTEXTAREA") && (values[count].length ==0)) {
				alert("Mandatory input field not completed for product: " + tmpArr1[1]);
				exit = true;
				return;
			}
		}
	}
}


function _get_version() {
	return parseFloat(navigator.appVersion);
}




function _get_os() {
	if (navigator.appVersion.indexOf("Win95") > 0) return "Win95";
	else if (navigator.appVersion.indexOf("Win16") > 0) return "Win16";
	else if (navigator.appVersion.indexOf("Mac") > 0) return "Mac";
	else if (navigator.appVersion.indexOf("X11") > 0) return "UNIX";
	else return "UNKNOWN";
}





function detectBrowser() {
	var browser = new Object();

	if (navigator.appName.substring(0, 8) == "Netscape") {
		browser.name = "NN";
		browser.version = _get_version();
		browser.os = _get_os();
	} 
	else if (navigator.appName.substring(0, 9) == "Microsoft") {
		browser.name = "MISE";
		browser.version = _get_version();
		browser.os = _get_os();
	} 
	else {
		browser.name = navigator.appName;
		browser.version = _get_version();
		browser.os = _get_os();
	}
	if (debugging)
		alert("Browser name = " + browser.name +
			"\nBrowser version = " + browser.version +
			"\nBrowser O/S = " + browser.os);
}




   
function splitter( mystr, splitchar )   {               
	           
	var tmp_arr = new Array();              
	var st_sp=0, end_sp = 0, i=0;           
	while( st_sp < mystr.length ) {                       
		end_sp = mystr.indexOf( splitchar, st_sp );
		if( end_sp == -1 ) end_sp = mystr.length;                  
		if( st_sp == end_sp ) tmp_arr[i] = "";                        
		else tmp_arr[i] = mystr.substring( st_sp, end_sp );                  

		                      
		st_sp = end_sp + 1;                     
		i++;            
	}               

	return tmp_arr; 
}




function Cookie( document, name, hours, path, domain, secure ){        
	this._document = document;      
	this._name = name;              
	path = "/";     

	if( hours )             
		this._expiration = new Date((new Date()).getTime() + hours*3600000);    
	else            
		this._expiration = null;        

	if( path )              
		this._path = path;      
	else            
		this._path = null;      

	if( domain )            
		this._domain = domain;  
	else            
		this._domain = null;    

	if( secure )            
		this._secure = secure;  
	else            
		this._secure = null;    

	     
	this.products = "";
}




function _Cookie_store(theForm) {
	if (debugging) alert("Entered _Cookie_store");
	var cookie;     
	var tmpobjval;  
	var cookieval = "";     
	

	if(debug) confirm("formArray = " + theForm);


	tmp_p_no = theForm.p_no.value;
	if(debug) confirm("Product numer = " + theForm.p_no.value);
	tmp_p_name = theForm.p_name.value;
	if(debug) confirm("Product name = " + tmp_p_name);
	tmp_p_price = theForm.p_price.value;
	if(debug) confirm("Product price = " + tmp_p_price);

	tmpobjval = theForm.qty.value;
	if(debug) confirm("Product quantity = " + tmpobjval);	

	// code added by MPJ to validate qty is 0-9 only
	for (cnt=0; cnt < theForm.qty.value.length; cnt++)
        {
                if ((tmpobjval.charAt(cnt) < "0") || 
			(tmpobjval.charAt(cnt) > "9"))
                {
                        alert("\nPlease enter a valid quantity value (i.e. digits only). ");
			theForm.qty.focus();
                        return false;
                }
        }

	// alert("POINT A");
	if( isNaN(parseInt( tmpobjval ) ) ) {               
		alert( "\nPlease enter a numeric value!" );             
		theForm.qty.focus();         
		return false;   
	}
	// alert("POINT B");
	if( tmpobjval == "" ) {
		alert( "\nPlease enter the quantity required!" );
		theForm.qty.focus();
		return false;
	}

	if( tmpobjval == 0 ) {               
		alert( "\nQuantity should be at least 1!" );             
		theForm.qty.focus();               
		return false;   
	}


	var attributes;
	attributes = processAttributes();

	this.products = "PROD:" + tmp_p_no + ":" + tmp_p_name + ":" + tmp_p_price + ":"
		+ theForm.qty.value + ":" + attributes;

	if(debug) confirm("The cookie is " + this.products);


	 
	if( isBasketFull() )    {               
		alert( "\nYour basket is Full.\nPlease Checkout." );            
		return false;    
	}       

	   
	if( isProductInBasket() ) {               
		alert( "\n"+theForm.p_name.value+" is already in basket.\n\nThis product has NOT been added to your basket." );            
		                
		return false;    
	}      


	for( var prop in this ) {               
		if( (prop.charAt(0) =='_') || ((typeof this[prop]) == 'function') )                     
			continue;               
		if( cookieval != "" )                   
			cookieval += '&';               

		         
		if( prop == 'products' ) {                       
			cookieval += prop + '|' + escape(this[prop]);           
		}       
	}

	     
	if( (prevCookieVal.length + cookieval.length) >= basketSize )   {               
		alert( "\nYour basket is Full.\nPlease Checkout." );            
		return false;    
	}       

	if( prevCookieVal != "" ) {
		if(debugging) alert("There is a pervious cookie in existance!  " + prevCookieVal);
		cookie = this._name + '=' + prevCookieVal + "&" + cookieval;    
	} else {
		cookie = this._name + '=' + cookieval;  
	}

	if( this._expiration )          
		cookie += '; expires=' + this._expiration.toGMTString();        

	if( this._path )                
		cookie += '; path=' + this._path;       

	if( this._domain )              
		cookie += '; domain=' + this._domain;   

	if( this._secure )              
		cookie += '; secure';   

	if (debugging) alert( "Finally cookie = " + cookie );

	this._document.cookie = cookie;

	if (cookie.length - this._document.cookie.length > 20) {
		exit = true;
		//alert("Exit set!");
		//alert(this._document.cookie + "\n\n\n\n" + cookie);
	}
	
	return true;
}




function _Cookie_load(){     
	allcookies = this._document.cookie;     
	if( isBasketEmpty() )           
		return false;   

	if( isBasketFull() ) {                       
		alert( "\nYour basket is Full.\nPlease Checkout." );            
		return false;   
	}       

	var start = allcookies.indexOf(this._name + '=');       
	if( start == -1 )               
		return false;   

	start += this._name.length + 1; 
	var end = allcookies.indexOf(';', start);       
	if( end == -1 )         
		end = allcookies.length;        

	prevCookieVal = allcookies.substring(start, end);       
	if (debug) confirm( "previous contents of basket = " + prevCookieVal  );
	initBasketTable();      
	return true;
}




function _Cookie_remove(){   
	var cookie;     
	cookie = this._name + '=';      

	if( this._path )                
		cookie += '; path=' + this._path;       
	if( this._domain )              
		cookie += '; domain=' + this._domain;   
	cookie += ';';  
	this._document.cookie = cookie;
}






new Cookie();

Cookie.prototype.store = _Cookie_store;
Cookie.prototype.load = _Cookie_load;
Cookie.prototype.remove = _Cookie_remove;



orderdata = new Cookie(document, "orderform" );


function loadBasket(){       
	orderdata.load();
}


function isBasketFull(){        
	if( allcookies.length >= basketSize )           
		return true;    
	else            
		return false;
}


function isBasketEmpty(){   
	      
	var stIndex = allcookies.indexOf(orderdata._name + '=');        
	if( stIndex == -1 ) {                       
		         
		return true;    
	}       
	stIndex += orderdata._name.length + 1;  
	if( stIndex == allcookies.length ) {               
		         
		               
		allcookies = "";                
		return true;    
	}       

	if( allcookies == "" )  {                       
		         
		return true;    
	} else            
		return false;
}


function initBasketTable() { 
	   
	basketTable = splitter( prevCookieVal, "&" );   
	var a = basketTable;    
	for(var i=0; i < a.length; i++)         
	basketTable[i] = splitter( a[i], "|" ); 
	for(var i = 0; i < basketTable.length; i++) {               
		
		basketTable[i][0] = ( unescape( basketTable[i][0] ) ).toString();               
		basketTable[i][1] = ( unescape( basketTable[i][1] ) ).toString();       
	}
}


function isProductInBasket(){   
	var tmpVar, startIndex=0, endIndex=0;   


	if( !isBasketEmpty() )  {              
		if(debugging) confirm("The basket is not empty"); 
		for(var i=0; i < basketTable.length; i++) {                       
			startIndex = ( basketTable[i][1].toString() ).indexOf( ":", 0 );      
			endIndex = ( basketTable[i][1].toString() ).indexOf( ":", startIndex + 1 );  
			tmpVar = basketTable[i][1].substring( startIndex+1, endIndex ); 

			if(debugging) confirm( "product no = " + tmpVar );
			if(debugging) confirm("tmp_p_no = " + tmp_p_no);
 
			
			if( tmpVar == tmp_p_no ) {
				if(debugging) confirm( "product nos match!...About to check attributes..." );
				startIndex = endIndex;
				startIndex =  ( basketTable[i][1].toString() ).indexOf( ":", startIndex + 1 );
 				startIndex =  ( basketTable[i][1].toString() ).indexOf( ":", startIndex + 1 );                          
				startIndex =  ( basketTable[i][1].toString() ).indexOf( ":", startIndex + 1 );   
				tmpVar = basketTable[i][1].substring( startIndex+1, basketTable[i][1].length );
				
				
				if(debugging) confirm("tmpvar = " + tmpVar);
				var current = processAttributes();
				if(debugging) confirm("Current Attributes = " + current);
				if (tmpVar == current) {
					return true;
				}
			}               
		}
		return false;               
	} else 
		return false;
}



function preProcessProduct() {       
	if (debugging) confirm("Entered preProcessProduct()");


	initBasketTable();
	for(var index =0; index < document.forms.length; index++) {
		for( i=0; i < document.forms[index].elements.length; i++ ) {
			
			
			if (debugging) confirm("Field name = " + document.forms[index].elements[i].name);
			if( (document.forms[index].elements[i]).name.indexOf( "MATT:" ) != -1 ) { 
				document.forms[index].elements[i].checked = true;
				if( (document.forms[index].elements[i]).checked ) { 
					if(debugging) confirm( "found the checked button!" );
					break;                  
				}
			}
		}      
	} 

 

}


function addToBasket(theForm) {
	if(debugging) confirm("The form = " + theForm); 

	if(exit) return false;
	if( !orderdata.store(theForm) ) {
		//document.theForm.submit();
		// change to return false instead of true by MPJ
		return false;
	} else {
		if (!exit)      
			// alert("\n"+theForm.p_name.value+" has been added to your basket.");
			alert("\n"+theForm.p_name.value+" has been added to your basket.\n\nPlease either select other product(s) for purchase or Proceed to Checkout.");
		else 
			alert("Product has NOT been added to your basket.");
	
		//top.location.href=thisURL;
		//document.theForm.submit();
		 // changed to return false by MPJ to prevent reload of page
                return false;
	}
	return false; 
}


function buyIt() {
	// next line added by MPJ
	displayBasket(); 
	document.orderform.action=buyURL;     
	document.orderform.submit();
}


function viewBasket() {
	
	if( !isBasketEmpty() )
	{
		top.location.href=basketURL;
	}
	else
	{
		alert( "\nYour Shopping Basket is Empty." );
		return false;
	}
}

function gotoCheckout() {
	var newURL="";

	if( !isBasketEmpty() )
	{
		newURL = basketURL+"?checkout";
		top.location.href=newURL;
	}
	else
	{
		alert( "\nYour Shopping Basket is Empty." );
		return false;
	}
}

// New Stuff

function displayBasket()
{
	//alert("Entered displayBasket()");

        if( !isBasketEmpty() )
        {
                for( cnt= 0; cnt < basketTable.length; cnt++ )
                        patchValues( (basketTable[cnt][1]).toString(), cnt );

		var delvChargePercent = delvCharge;
		if (!percentage) {
			
                	document.write( '<INPUT TYPE=HIDDEN NAME=\"PROD:ZZZ9999:Delivery Charge:' + delvCharge + '\" VALUE=1>' );
		} else {
			
			var delvChargeTmp = delvCharge;
			delvChargeTmp = gtot/100 * delvChargeTmp;
			delvChargeTmp *= 100;
			delvChargeTmp = Math.round(delvChargeTmp);
			delvChargeTmp /= 100;
                        // following line replaced by line below by MPJ
                        // var delvChargeTmp = delvCharge.toString();
                        var delvChargeTmp = new String(delvCharge);
                        if (delvChargeTmp.indexOf('.') == -1) delvChargeTmp += ".00";
                        if (delvChargeTmp.indexOf('.') == (delvChargeTmp.length-2)) delvChargeTmp += "0";

		}

		
		if (percentage) {
			delvCharge = delvChargePercent;
			gtot = (gtot/100) * (100 + delvCharge);
		}
		else {
			gtot += delvCharge;
		}
        }
        else
        {
		//alert("Your basket is empty.");
                //document.write( "<TR>" );
                //document.write( "<TD ALIGN=CENTER COLSPAN=5><B><BR><BR>" + "Shopping Basket is Empty!" + "</B><BR><HR SIZE=-1></TD></TR>" );
        }
                                
        gtot *= 100;
        gtot = Math.round( gtot );
        gtot /= 100;

	//Avoid Rounding Errors
	var gtotTmp = gtot;
	// following line replaced by line below by MPJ
	// gtotTmp = gtotTmp.toString();
	gtotTmp2 = new String(gtotTmp);
	// gtotTmp2 now used instead of gtotTmp
	if (gtotTmp2.indexOf('.') == -1) gtotTmp2 += ".00";
	if (gtotTmp2.indexOf('.') == gtotTmp2.length-2) gtotTmp2 += "0";

	gtotTmp = gtotTmp2;

        //if( gtot == 0 )
                //gtot = "0.00";

}

function patchValues( ckVal )
{

       	var qty; 
        var ckVal_lst = splitter( ckVal, ":" );

        tmp_p_skuname=""; tmp_p_skuattr="";
       
 
        tmp_p_no = ckVal_lst[1];
	if (debugging) confirm("The product number is " + tmp_p_no);

        
        tmp_p_name = ckVal_lst[2];
	if (debugging) confirm("The product name is " + tmp_p_no);

        
        tmp_p_price = ckVal_lst[3];
	if(debugging) confirm("The product price is " + tmp_p_price);
	
	//Avoid Rounding Errors
	var gtotTmp = gtot;
	// following line replaced by line below by MPJ
	// gtotTmp = gtotTmp.toString();
	gtotTmp2 = new String(gtotTmp);
	// gtotTmp2 now used instead of gtotTmp
	if (gtotTmp2.indexOf('.') == -1) gtotTmp2 += ".00 ";
	if (gtotTmp2.indexOf('.') == gtotTmp2.length-2) gtotTmp2 += "0 ";

	gtotTmp = gtotTmp2;
	// gtotTmp = gtotTmp.toString();
	// if (gtotTmp.indexOf('.') == -1) gtotTmp += ".00 ";
	// if (gtotTmp.indexOf('.') == gtotTmp.length-2) gtotTmp += "0 ";

        
        if( ckVal_lst[4] != null )
                qty = ckVal_lst[4];
        else 
                qty = 1;

	if (debugging) confirm("The quantity is = " + qty);

        document.write( "<INPUT TYPE=HIDDEN SIZE=2 MAXLENGTH=2 NAME=\"" + "PROD:" + tmp_p_no + ":" + tmp_p_name + ":" + tmp_p_price + "\" VALUE=" + qty + ">" );
        

        i = 5;
        while( i < ckVal_lst.length )
        {
                tmp_p_skuname = ckVal_lst[i];
                tmp_p_skuattr = ckVal_lst[i+1];

                if( (tmp_p_skuname != "") && (tmp_p_skuattr != "") )
                {
                        document.write( "<INPUT TYPE=HIDDEN NAME=" + "MATT:" + tmp_p_no + ":" + tmp_p_skuname + " VALUE=\"" + tmp_p_skuattr + "\">" );

                        //document.write( "<BR><FONT SIZE=-2><I>" + tmp_p_skuname + "</I> :- " + tmp_p_skuattr +"</FONT>" );
                }
                i += 2;
        }

        //document.write( "</TD>" );

        //document.write( "<TD ALIGN=RIGHT>" + tmp_p_price + "</TD>" );

        //document.write( "<TD ALIGN=CENTER><INPUT TYPE=TEXT SIZE=2 MAXLENGTH=2 NAME=qty VALUE=\"" + qty + "\" onChange=\'checkQty(this);\'> </TD>" );
        document.write( "<INPUT TYPE=HIDDEN SIZE=2 MAXLENGTH=2 NAME=qty VALUE=\"" + qty + "\">" );

        var tmp_p = qty * tmp_p_price;
        tmp_p *= 100;
        tmp_p = Math.round( tmp_p );
        tmp_p /= 100;

	var tmp_pp = tmp_p;
        // following line replaced by line below by MPJ
        // tmp_pp = tmp_pp.toString();
        tmp_pp2 = new String(tmp_pp);
        // tmp_pp2 now used instead of tmp_pp
        if (tmp_pp2.indexOf('.') == -1) tmp_pp2 += ".00";
        if (tmp_pp2.indexOf('.') == tmp_pp2.length-2) tmp_pp2 += "0";
 
        tmp_pp = tmp_pp2;
 
	// tmp_pp = tmp_pp.toString();
	// if (tmp_pp.indexOf('.') == -1) tmp_pp += ".00 ";
	// if (tmp_pp.indexOf('.') == tmp_pp.length-2) tmp_pp += "0 ";

        //document.write( "<TD ALIGN=RIGHT>" + tmp_pp + "</TD>" );

        //document.write( "<TD ALIGN=CENTER><INPUT TYPE=checkbox NAME=removeproduct></TD>" );
        
        //document.write( "</TR>" );

        //document.write( '<TR><TD ALIGN = RIGHT COLSPAN=5><HR SIZE=-1></TD></TR>' );


        gtot += tmp_p;
}


