// I am trying to figure out why updateCookie dosen't work... having trouble turning the field sting into an object.
// Also need to figure out the pricing etc

var orderWin;
var path; 
var shopping_cart = new Array(); // This array is used to hold the cart catalog

function MM_openBrWindow(theURL,winName,features) { //v2.0
  newWindow=window.open(theURL,winName,features);
  newWindow.focus();
}

function swapImg(loc) {
	// handles image swap in popup windows
	getRawObj('lg_pic').src=loc;
}


function JCAD_readCookie(the_cookie) {
	
	mr_cookie = document.cookie;
	document.write(mr_cookie);
	document.close();
}

function handleError(msg) {
	alert(msg);
}

function getRawObj(elemID) {
	
	// returns either a W3C or IE reference for the object.
	
	if (document.all) {
		elem = document.all(elemID);
		return elem;
	} else if (document.getElementById) {
		elem = document.getElementById(elemID);
		return elem;
	} else 
		handleError('Browser does not support W3C or IE DOM... Please use IE4+ or Netscape 6+ as your web browser');
		return false;
}	

function requestOrder(obj) {

	// First we need to assess the values from the this row of the table
	// Work back up the object to find the table
	
	while (obj.nodeName != 'TR') {
		obj = obj.parentNode;
	}
	
	
	// Let's go find the values in the individual cells.

	var sku = obj.cells[0].innerHTML;
	var price = assessPrice(obj);
	var desc = assessDesc(obj);
	var color = assessColor(obj);

	// Now we build the product code cookie

	var product_code = "sku:" + sku + "&desc:" + desc + "&price:" + price + "&color:" + color + "&qty:1";

	// But first, lets read in to see if there is anything else in the cart. 

	var existingCookie = WM_readCookie('order_list');
	if (existingCookie) { 
		product_code = existingCookie + '@' + product_code;
	}	

    var the_cookie = "order_list=" + escape(product_code) + ";path=/"
    document.cookie = the_cookie;

	// Ok... now let's take the user to the order page to see what is in their basket.
    window.location.href= path + "catalog/order.html"
    
    return true;
}

function orderGeneric(sku,price,desc,color,max) {

	// Now we build the product code cookie
	var product_code = "sku:" + sku + "&desc:" + desc + "&price:" + price + "&color:" + color + "&qty:1";

	// But first, lets read in to see if there is anything else in the cart. 
	var existingCookie = WM_readCookie('order_list');

	if ((existingCookie) && !(existingCookie.match(sku))) { 
	  product_code = existingCookie + '@' + product_code;
	  var the_cookie = "order_list=" + escape(product_code) + ";path=/"
      document.cookie = the_cookie;
	 }	

 	// Ok... now let's take the user to the order page to see what is in their basket.
    window.location.href= path + "catalog/order.html"
      
    return true;
}



function assessPrice(obj) {
	
	var dollar_price = obj.cells[3].innerHTML;
	dollar_sign = dollar_price.indexOf('$');
	price = dollar_price.substring((dollar_sign + 1),(dollar_price.length));
	return price;
} 

function assessColor(obj) {

	var choice = "-"; 

	// step through the cell to find the select form... 
	if(obj.cells[2].firstChild) {
		selectForm = obj.cells[2].firstChild;			
		if (selectForm.nodeName == 'SELECT') {
		 	choice = selectForm[selectForm.selectedIndex].value;
		}	 	
	}
	return choice; 
}

function assessDesc(obj) {

	// Description should be in the second 
	var desc = obj.cells[1].innerHTML;
	var typeDesc = getRawObj("typeDesc")
	
	// Enhance the description with information from the typeDesc span in the header of the document.
	
	if (typeDesc) { 
		desc = desc + " " + typeDesc.innerHTML;
	}
	return desc;
}




function CookieToArray() {

	// Read order_list cookie, and check it's true
	order_list = WM_readCookie('order_list')
	if (!order_list) return false;
	
	// Cut up the item description into product sets
	var items = order_list.split('@');
	for (var y = 0; y < items.length; y++) {
		
		// Split each product set into desc/value pairs
		var info = new Array();
		var field_values = items[y].split('&');
					
		// Now build an associative array with these values
		for (var x = 0; x < field_values.length; x ++) { 
			var broken_field_values = field_values[x].split(':');
			var field = broken_field_values[0];
			var value = broken_field_values[1];
			info[field]=value;
			items[y]=info;	
		}
	}
	return items;
}

function ArrayToCookie() {

	// Check the array exists	
	if (shopping_cart) {

		// Kill the cookie
		WM_killCookie('order_list', '/');
		
		// Read from the array.. and rebuild the cookie
		var new_cookie = "";
		for (x=0; x < shopping_cart.length; x++) {
			if(x>0) new_cookie+='@';
			new_cookie+="sku:" + shopping_cart[x].sku + "&desc:" + shopping_cart[x].desc + "&price:" + shopping_cart[x].price + "&color:" + shopping_cart[x].color + "&qty:" + shopping_cart[x].qty; 
		}
	   	
	   	// Now write the cookie back.
	   	new_cookie = "order_list=" + escape(new_cookie) + ";path=/"
    	document.cookie = new_cookie; 
    }
}

function doTotals() {

	var factors = new Object();
	var discount_factor = readCode()
	
	if (discount_factor) 
		factors.discount = true;
	else 
		discount_factor = 1;
		
	factors.sub_total = 0;
	
	// loop through array adding quantities.
	for (var y = 0; y < (shopping_cart.length); y++) {
		factors.sub_total += shopping_cart[y].price * shopping_cart[y].qty * discount_factor;
	}

	// figure out subtotal... shipping... and total 
	factors.shipping = factors.sub_total * 0.15 // Shipping at 15% of purchase price
	if (factors.shipping < 10) factors.shipping=10;
	factors.total = factors.shipping + factors.sub_total;
	
	// prepare for output
	
	factors.sub_total =  DP2S(factors.sub_total);
	factors.shipping = DP2S(factors.shipping);
	factors.total = DP2S(factors.total);
	
	return factors;
}

// Functions below used and adapted from WebMonkey Javascript Library (http://www.hotwired.com/webmonkey/javascript/code_library/)
// This next little bit of code tests whether the user accepts cookies.
var WM_acceptsCookies = false;
if(document.cookie == '') {
    document.cookie = 'WM_acceptsCookies=yes'; // Try to set a cookie.
    if(document.cookie.indexOf('WM_acceptsCookies=yes') != -1) {
	WM_acceptsCookies = true; 
    }// If it succeeds, set variable
} else { // there was already a cookie
  WM_acceptsCookies = true;
}

function WM_setCookie (name, value, hours, path, domain, secure) {
    if (WM_acceptsCookies) { // Don't waste your time if the browser doesn't accept cookies.
	var not_NN2 = (navigator && navigator.appName 
		       && (navigator.appName == 'Netscape') 
		       && navigator.appVersion 
		       && (parseInt(navigator.appVersion) == 2))?false:true;

	if(hours && not_NN2) { // NN2 cannot handle Dates, so skip this part
	    if ( (typeof(hours) == 'string') && Date.parse(hours) ) { // already a Date string
		var numHours = hours;
	    } else if (typeof(hours) == 'number') { // calculate Date from number of hours
		var numHours = (new Date((new Date()).getTime() + hours*3600000)).toGMTString();
	    }
	}
	document.cookie = name + '=' + escape(value) + ((numHours)?(';expires=' + numHours):'') + ((path)?';path=' + path:'') + ((domain)?';domain=' + domain:'') + ((secure && (secure == true))?'; secure':''); // Set the cookie, adding any parameters that were specified.
    }
} 

function WM_readCookie(name) {
	
    if(document.cookie == '') { // there's no cookie, so go no further
    } else { // there is a cookie
	var firstChar, lastChar;
	var theBigCookie = document.cookie;
	firstChar = theBigCookie.indexOf(name);	// find the start of 'name'
	var NN2Hack = firstChar + name.length;
	if((firstChar != -1) && (theBigCookie.charAt(NN2Hack) == '=')) { // if you found the cookie
	    firstChar += name.length + 1; // skip 'name' and '='
	    lastChar = theBigCookie.indexOf(';', firstChar); // Find the end of the value string (i.e. the next ';').
	    if(lastChar == -1) lastChar = theBigCookie.length;
	    return unescape(theBigCookie.substring(firstChar, lastChar));
	} else { // If there was no cookie of that name, return false.
	    return false;
	}
    }	
} 

function WM_killCookie(name, path, domain) {
  var theValue = WM_readCookie(name); // We need the value to kill the cookie
  if(theValue) {
      document.cookie = name + '=' + theValue + '; expires=Fri, 13-Apr-1970 00:00:00 GMT' + ((path)?';path=' + path:'') + ((domain)?';domain=' + domain:''); // set an already-expired cookie
  }
}  

function DP2S(X) {
	// Rounds a number... truncates at two decimal places and returns as a string.
    return String((Math.round(X * 100) + (X < 0 ? -0.1 : 0.1)) / 100).replace(/(.*\.\d\d)\d*/, "$1");
}

function readCode() {

	var discount = 1;
	var discount_code = WM_readCookie('discountCode');
	
	if(discount_code) {
		switch(discount_code.substring(0,4)) {
			case 'GIVE' :
				discount=0.9;
				break;
			case 'CARE' :
				discount=0.95;
				break;
			case 'LOVE' :
				discount=0.85;
				break;
			default :
				discount=1;				
		}
	}		
	// Reads the profile for a code cookie, and returns the discount value, or false if there is no cookie. 
	return discount;
	
}

