/* library.js  -- JavaScript code for The Learning Bug
 * 2003-11-12 Added cents, laminationPromotion
 * 2003-11-21 Changed showAgeGradeState to work from cookie, not form.
 * 2004-03-02 Added alert to cartAdd to give positive feedback on adding an item.
 * 2006-01-16 Removed duplicate "theCart" definition.  Add ; at end of some lines so CuteHTML compiles clean.
 */
 
//******************************************************************
//*  Cookie support
//******************************************************************

// ***Global constants***
laminationPerFoot	 = .50; // could come from live database retail value of lamination.

var couponDiscount	 = .25; // how much does a customer save (ie: 25% off)

var CookieExpireTime = 12;	// The time in months before cookie expires


// ***Global variables***

var everyDept = 1;	//0 for current dept only, 1 for all departments

var searchType;		//tree, search, both




function expireDate(months) {
	var secs;
    var expires = new Date();

    secs = months * 30.44 * 24 * 60 * 60;
    expires = new Date(expires.getTime() + (secs * 1000));
    return expires;
}


function Get_Cookie(label) {
	var cookie;
    var start = document.cookie.indexOf(label + "=");
    if (start == -1) return null;	//cookie not found
    var len = start+label.length+1;
    var end = document.cookie.indexOf(";",len);
    if (end == -1) {
		cookie = document.cookie.substr(len);
		//end = document.cookie.length;
	}
	else{
		cookie = document.cookie.substring(len, end);
	}
	cookie = unescape(cookie);
	
    return cookie;
} 


function Set_Cookie(name, value, exp, path) {
	var exp = new Date();	    							//set new date object
	exp.setTime(exp.getTime() + (1000 * 60 * 60 * 24 * 7));	//set it 7 days ahead
	exp = "; expires=" + exp.toGMTString();

	// document.cookie = "learningBug" + "=" + escape("the new cart cookie") + "; path=/" + exp;
	document.cookie = name + "=" + escape(value) + "; path=/" + path + exp;
}
 

function resetCookie(name) {
	if(name == "cart")	path = "catalog";
	else				path = "";
	Set_Cookie(name, "", expireDate(-1), path);
}


function reloadPage() {
	//window.location.reload();
	history.go(0);
}



//*************************************

//	shoping cart support

//*************************************



// customerNumber is guaranteed unique and is found in customerDB via name & phone number
var cookieCustNumber    = "CustNumber";

var cookieShipMethod   = "ShipMethod";

var cookieSubmitMethod = "SubmitMethod";



var cookieCart = "cart";

var delimItem  = "|";

var delimField = "~";

var cartUPC      = 0;

var cartPrice    = 1;

var cartQuantity = 2;

var cartDesc     = 3;

var cartVendor   = 4;

var cartStyle    = 5;

var cartColor    = 6;

var cartSize     = 7;

var cartInStock  = 8;

// change tax rates in library.php too
var AZtax = 0.06725;

var FlagstaffTax = 0.01721;



var cookie;

var cart;

var item;

var total;

var nItem;

var lineTotal;

var orderTotal;



//Add an item to the shopping cart. Vendor, color, and size are optional.
// NOTE: quantity is actually a pointer to the field [name], not a numeric value
// inStock comes from OH + OO so some of the "in stock" quantity may be in transit from supplier
function cartAdd(UPC, price, quantity, description, vendor, style, color, size, qtyFieldName, inStock) {
	
	var cart;
	var cookie;
	var item;
	var n;
	
	// set quantity to add from user input
	quantity = document.userAddInfo[qtyFieldName].value;
	
	//See if this item is already in the cart
	cookie = Get_Cookie("cart");

	if (cookie != null && cookie != "") {
		cart = cookie.split(delimItem);
		for (n = 0; n < cart.length; ++n) {
			item = cart[n].split(delimField);
			if (item[cartUPC]+ item[cartStyle] == UPC + style) {
				//already there
				alert("This product is already in your shopping cart.  Open the shopping cart to change the quantity desired.");
				return false;
			}
		}
		if (cart.length > 0) cookie += delimItem;
	}
	else cookie = "";

	cookie += UPC        + delimField
	       + price       + delimField
	       + quantity    + delimField
	       + description + delimField
	       + vendor      + delimField
	       + style       + delimField
	       + color       + delimField
	       + size       + delimField
	       + inStock;
	
	Set_Cookie(cookieCart, cookie);
	
	return true;
}




function cents(x) {
	x = (Math.round(x*100)/100).toString();
	if (isNaN(x)) {
		return x;
	}
	else if (x.indexOf(".") < 0) {
		x += ".00";
	}
	else {
		var last = x.length - 1;
		if (x.charAt(last) == ".")
			x += "00";
		else if (x.charAt(last-1) == ".")
			x += "0";
	}
	return x;
}


//Return the lamination promotion tag line

function laminationPromotion(unitFeet){	
	// if no unitFeet was sent, but the function was called:
	if(laminationPromotion.arguments.length == 0) {
		return("");
	}
	if(unitFeet < 0){
		msg = "<p>Laminate this item for only " + (laminationPerFoot * 100) + " cents per foot</p>";
	}
	if (unitFeet == 0) {
		return("");
	}
		
	// calculate the total price for lamination
	totalLamFee = unitFeet * laminationPerFoot;

	// format message to use either "cents" or "$X.XX
	if(totalLamFee < 1){
		totalLamFee = Math.ceil(totalLamFee * 100);
		msg = "<p>Laminate this item for only " + totalLamFee + " cents.</p>";
	}else{
		msg = "<p>Laminate this item for only $" + cents(totalLamFee) + "</p>";
	}
	
	return (msg);
}




// open sized window with a provided URL for "more info" window (item.php)
function openMoreInfo(url, style) {
	window.open(url, "LB_item","menu=yes,status=yes,width=372,height=530,scrollbars=yes,left=16,top=16");
}




// open sized window with a provided URL for "shopping cart" window (shopcart.php)
function openShopCart() {
	window.open("shopcart.php", "shopcart","menu=yes,status=yes,width=615,height=460,scrollbars=yes,left=8,top=8");
}




// return string detailing how many of a given UPC are in the current shopping cart
function quantityInCart (theUPC) {
	var theCart = Get_Cookie(cookieCart);
	
	if (theCart != null && theCart != "") {
		theCart = theCart.split(delimItem);
 	  	for(n=0; n<theCart.length; n++){
 	  		// UPC; Price; QTY; Title; Vendor; Style; Color; Size
 	  		theItem = theCart[n].split(delimField);
 	  		if (theUPC == theItem[cartUPC]) {
 	  			return "<strong>" + theItem[cartQuantity] + "</strong> in cart";
 	  		}else{
 	  			// keep looking return "";
 	  			// maybe a catalog item? (if UPC is blank)
 	  		}
 	  	}
 	  	return ""; // wasn't found in cart
	}else{
		return ""; // cart doesn't even exist
	}
}

