/*
CART.JS - cart cookie storage and presentation code.
Careful here, the cart cookie has keys. Keys are case sensitive,
i.e. cartCookie('Items') is not the same thing as cartCookie('items').
*/
var cartCookie = ''; // this global cookie object gets initialized in the page header
var defaultGatewayId = ''; // this global cookie object gets initialized in the page header
var siteMaintPopup = null; // store maintenance popup message (if present). siteMaintPopup is a popUpDiv object usually coded into site_header.asp (see global.js for details).


function addToCart(searchId, productId, qty){
	if(!cartCookie || !cartCookie.get('Init')) return true; // abort here if the browser is not setting cookies.
	setBg('cartContentsDiv', 'DDD'); // flash cart background when adding an item.
	setTimeout('setBg(\'cartContentsDiv\',\'FFF\')', 1500);
	// Look up the requested product Id from the js Products array in the page header
	var arrProduct = getProduct(searchId,productId);
	if(!arrProduct)return; // skip items with bad or missing database id
	// if(arrProduct[5]==0)return; // if no price, item is not for sale
	qty = parseInt(qty)>0?parseInt(qty):1;
	var productId = arrProduct[3];
	var price = arrProduct[5];
	var itemGatewayId = arrProduct[6];
	setGatewayId(itemGatewayId); // lookup the item's gatewayid before adding the item.
	// Load cart and add the item only if cart does not contain the item already.
	// Load the correct cart cookie value for the current gateway.
	var cartStr = cartCookie.get('Items'+getGatewayId());
	var arrCart = cartStr!=''?cartStr.split('|'):[];
	for(var i=0;i<arrCart.length;i++){
		var arrItem = arrCart[i].split(',');
		if(arrItem.length>1) if(arrItem[0]==productId) break;
	}
	if(i==arrCart.length) arrCart[arrCart.length] = [productId, qty];
	saveCart(arrCart);
	showCart();
	if(siteMaintPopup)siteMaintPopup.show(); // activates store maintenance popup message if present. dragDiv is usually coded into site_header.asp
	return false;
}

// recalculates cart quantities.
function updateCart(frm, fldname, norefresh){
	var arrCartNew = []; fld='';
	var cartStr = cartCookie.get('Items'+getGatewayId())
	var arrCart = cartStr!=''?cartStr.split('|'):[];
	for(var i=0;i<arrCart.length;i++){
		arrItem = arrCart[i].split(',');
		fld = fldname+arrItem[0].toString();
		val = parseInt(frm[fld]?frm[fld].value:0);
		if(!isNaN(val)){
			val=val>10?10:val;
			if(val>0) arrCartNew[arrCartNew.length]=[arrItem[0],val];
		}
		else arrCartNew[arrCartNew.length]=[arrItem[0],0];
	}
	saveCart(arrCartNew);
	if(!norefresh)document.location.reload();
}

function saveCart(arrCart){
	var cartStr = arrCart.join('|');
	cartCookie.set(cartStr?cartStr:'','Items'+getGatewayId());
}

function validateCart(frm, fldname){
	var currentGatewayId;
	currentGatewayId = getGatewayId();
	updateCart(frm, fldname, 1, currentGatewayId);
	if(cartCookie.get('Items'+currentGatewayId)=='')document.location.reload();
}

// Right nav cart object. Always displays default gateway unless specified.
function showCart(gatewayId){

	gatewayId = (gatewayId)?gatewayId:getGatewayId();
	var strCart = cartCookie.get('Items'+gatewayId);
	var arrCart = strCart?strCart.split('|'):[];
	if(arrCart.length==0)return;
	var subtot = 0;
	var htm = '';
	var i = arrCart.length-1;
	if(i>-1) do {
		var arrItem = arrCart[i].split(',')
		if(arrItem.length>1){
			var productId = arrItem[0];
			var qty = arrItem[1];
			var arrProduct = getProduct(0, productId);
			if(arrProduct.length>0){
				htm += '<a href="/store2/product.asp?p='+productId+'" class="red vs"><b>'+arrProduct[0]+'</b></a><br>'
				subtot += arrProduct[5]*qty;
			}
		}
	} while (i--);
	htm += '<div style="margin:6 0">Subtotal: $' + moneyFormat(subtot) +'</div>';
	var lyr = getRef('cartContentsDiv');
	if(lyr)if(lyr.innerHTML)lyr.innerHTML = htm;
}

// getGatewayId() - retreives the current gatewayid, defaults to defaultGatewayId set in site_header.inc
function getGatewayId(currentGatewayId){
	if(!cartCookie || !cartCookie.get('Init')) return defaultGatewayId;
	currentGatewayId = cartCookie.get('currentGatewayId');
	return currentGatewayId>0?currentGatewayId:defaultGatewayId;
}

// setGatewayId() - set the current gatewayid
function setGatewayId(gatewayId){
	if(!cartCookie || !cartCookie.get('Init')) return true;
	cartCookie.set(gatewayId>0?gatewayId:defaultGatewayId, 'currentGatewayId');
}


function clearCart(oLnk,i){
	clearCart.clear=clearCart.clear==0?1:0;
	with(document.cart){
		if(clearCart.clear>0) {
			oLnk.innerHTML='clear all';
			reset();
		}
		else {
			for(i=0;i<elements.length;i++)if(elements[i].name.indexOf('qty')==0)elements[i].value=0;
			oLnk.innerHTML='reset';
		}
	}
}

function getProduct(searchId, productId){
	var i = Products.length-1;
	if(searchId>0) { do if(Products[i][2]==searchId)return Products[i]; while(i--) }
	else do if(Products[i][3]==productId) return Products[i]; while(i--);
	return 0;
}

function moneyFormat(n){
	n = parseFloat(n).toString().split('.');
	n[1] = n[1]?n[1]:''; while(n[1].length<2)n[1]=n[1]+'0';
	n[1]=n[1]>=100?Math.round(n[1]/Math.pow(10,n[1].length-2)):n[1];
	return (n[0]?n[0]:'0')+'.'+n[1];
}

function isRequired(fld, fields){
	fld = fld.toLowerCase()+',';
	fields = fields.toLowerCase()+',';
	if(fields.indexOf(fld)>-1) return true;
	return false;
}

function isLen(val,max){return val.length>=(max?max:1)}
function selVal(fld){return fld.options[fld.selectedIndex].value}
function isEmail(e){
	var eml=[e.substring(0,e.indexOf('@')+1)];
	eml[1]=e.substring(e.indexOf('@')+1,e.lastIndexOf('.')+1);
	eml[2]=e.substring(e.lastIndexOf('.')+1,e.length);
	return (eml[0] && eml[1] && eml[2] && e==eml[0]+eml[1]+eml[2]);
}

function loadPreview(asx){
	with(document)(document.getElementById?getElementById('previewFrame'):all['previewFrame']).src=asx;
	return false;
}

