var item_info, timeToKeep, expires, cookieName;
var gst_rate = .05;
var pst_rate = .08;

timeToKeep = 180000000000;
expires = new Date();
expires.setTime(expires.getTime() + timeToKeep);

cookieName = 'items';
item_info = init_array();
get_array(cookieName, item_info);

function init_cart()
{	
		var prnt, cartid, carts, y, u;
		var aTmp = new Array();
		var iId, iQty;
		
		//set the carts
		carts = getElementsByClassName("cart_image");
		for (y = 0; y<carts.length; y++)
		{
			prnt = carts[y].parentNode;
			cartid = prnt.id.replace("img2", "");
			for (u = 0; u<item_info.length; u++)
			{
				if (item_info[u] == null)
					continue;
				aTmp = item_info[u].split("|");
				if (aTmp.length == 0)
					continue;
				iId = aTmp[0];
				iQty = aTmp[1];
				if (cartid == iId)
				{
					setCartIcon(cartid,"remove",1);
				}
			}
		}
		
		//set the product startup page new buttons
		carts = getElementsByClassName("cart_image2");
		for (y = 0; y<carts.length; y++)
		{
			prnt = carts[y].parentNode;
			cartid = prnt.id.replace("img2", "");
			for (u = 0; u<item_info.length; u++)
			{
				if (item_info[u] == null)
					continue;
				aTmp = item_info[u].split("|");
				if (aTmp.length == 0)
					continue;
				iId = aTmp[0];
				iQty = aTmp[1];
				if (cartid == iId)
				{
					setCartIcon(cartid,"remove",2);
				}
			}
		}
		
		//set the product startup page sale buttons
		carts = getElementsByClassName("cart_image3");
		for (y = 0; y<carts.length; y++)
		{
			prnt = carts[y].parentNode;
			cartid = prnt.id.replace("img3", "");
			for (u = 0; u<item_info.length; u++)
			{
				if (item_info[u] == null)
					continue;
				aTmp = item_info[u].split("|");
				if (aTmp.length == 0)
					continue;
				iId = aTmp[0];
				iQty = aTmp[1];
				if (cartid == iId)
				{
					setCartIcon(cartid,"remove",3);
				}
			}
		}
		
		//calculate small and full cart totals
		calcCurrent();
		calcTotals();
}

function setCartIcon(id,value,cartnum)
{	
	alt = "";
	pre = "cart_";
	
	if (cartnum > 1)
	{
		pre = "cart" + cartnum + "_";
	}
	
	node = document.getElementById(pre+id);
	if (value == "add")
	{
		if (stringRight(node.src,15) == 'cart_remove.png')
		{
			alt = "Add To Cart";
			node.alt = alt;
			node.src = 'images/cart_add.png';
		}
		else if (stringRight(node.src,20) == 'remove_from_cart.png')
		{
			alt = "Add to Cart";
			node.alt = alt;
			node.src = 'images/add_to_cart.png';
		}
	}
	else if (value == "remove")
	{
		if (stringRight(node.src,12) == 'cart_add.png')
		{
			alt = "Remove From Cart";
			node.alt = alt;
			node.src = 'images/cart_remove.png';
		}
		else if (stringRight(node.src,15) == 'add_to_cart.png')
		{
			alt = "Remove From Cart";
			node.alt = alt;
			node.src = 'images/remove_from_cart.png';
		}
	}
}

function getElementsByClassName(classname, node) 
{
	if(!node) node = document.getElementsByTagName("body")[0];
	var a = [];
	var re = new RegExp('\\b' + classname + '\\b');
	var els = node.getElementsByTagName("*");
	for(var i=0,j=els.length; i<j; i++)
	if(re.test(els[i].className))a.push(els[i]);
	return a;
}

function stringRight(str, n)
{
	if (n <= 0)
	 return "";
	else if (n > String(str).length)
		return str;
	else 
	{
		var iLen = String(str).length;
		return String(str).substring(iLen, iLen - n);
	}
}


function Cart(obj)
{
	if(!obj)
		return false;
	
	//remove focus
	obj.blur();
	
	var cartnum;
	if (obj.firstChild.id.substr(0,5) == 'cart_')
	{
		cartnum = 1;
	}
	else if (obj.firstChild.id.substr(0,6) == 'cart2_')
	{
		cartnum = 2;
	}
	else if (obj.firstChild.id.substr(0,6) == 'cart3_')
	{
		cartnum = 3;
	}
	
	var myid = obj.firstChild.id.replace("cart3_", "");
	myid = myid.replace("cart2_", "");
	myid = myid.replace("cart_", "");
	
	var aTmp = new Array();
	var iId, iQty
	
	if(stringRight(obj.firstChild.src,7) == "add.png" || stringRight(obj.firstChild.src,15) == "add_to_cart.png")
	{
		setCartIcon(myid, "remove", cartnum);
		//add item
		var num = next_entry(item_info);
		item_info[num] = myid + '|' + '1';
		set_array(cookieName, item_info, expires);
	}
	else if (stringRight(obj.firstChild.src,10) == "remove.png" || stringRight(obj.firstChild.src,20) == "remove_from_cart.png")
	{
		setCartIcon(myid, "add", cartnum);
		var temparray = new Array();
		temparray.push(null);
		
		//remove item
		for (var a = 0; a<item_info.length; a++)
		{
				if (item_info[a] == null)
					continue;
				aTmp = item_info[a].split("|");
				if (aTmp.length == 0)
					continue;
				iId = aTmp[0];
				iQty = aTmp[1];
				if (iId != myid)
				{
					temparray.push(item_info[a]);
				}
		}
		item_info = "";
		item_info = init_array();
		item_info = temparray;
		temparray = "";
		set_array(cookieName, item_info, expires);
	}
	
	calcCurrent();
	
	return false;
}

function getText(n)
{
  if('textContent' in n) {
    return n.textContent;
  } else if('innerText' in n) {
    return n.innerText;
  } else {
    // Call a custom collecting function, throw an error, something like that.
  }
}

function setText(n, value)
{
  if('textContent' in n) {
    n.textContent = value;
		return false;
  } else if('innerText' in n) {
    n.innerText = value;
		return false;
  } else {
    // Call a custom collecting function, throw an error, something like that.
  }
	return false;
}

function roundNumber(number,decimals) 
{
	var newString;// The new rounded number
	decimals = Number(decimals);
	if (decimals < 1) {
		newString = (Math.round(number)).toString();
	} else {
		var numString = number.toString();
		if (numString.lastIndexOf(".") == -1) {// If there is no decimal point
			numString += ".";// give it one at the end
		}
		var cutoff = numString.lastIndexOf(".") + decimals;// The point at which to truncate the number
		var d1 = Number(numString.substring(cutoff,cutoff+1));// The value of the last decimal place that we'll end up with
		var d2 = Number(numString.substring(cutoff+1,cutoff+2));// The next decimal, after the last one we want
		if (d2 >= 5) {// Do we need to round up at all? If not, the string will just be truncated
			if (d1 == 9 && cutoff > 0) {// If the last digit is 9, find a new cutoff point
				while (cutoff > 0 && (d1 == 9 || isNaN(d1))) {
					if (d1 != ".") {
						cutoff -= 1;
						d1 = Number(numString.substring(cutoff,cutoff+1));
					} else {
						cutoff -= 1;
					}
				}
			}
			d1 += 1;
		} 
		newString = numString.substring(0,cutoff) + d1.toString();
	}
	if (newString.lastIndexOf(".") == -1) {// Do this again, to the new string
		newString += ".";
	}
	var decs = (newString.substring(newString.lastIndexOf(".")+1)).length;
	for(var i=0;i<decimals-decs;i++) newString += "0";
	return newString;
}

function calcCurrent()
{
	var amount;
	$.get("ajax/calc_current.php", function(amount){
		setText(document.getElementById('mini_cart_total'), "$" + roundNumber(amount,2) );
	});
	return null;
}

function calcTotals()
{
	if (!document.getElementById("total")) return;
	
	var iId, iQty;
	var subtotal = 0;
	var gst = 0;
	var pst = 0;
	var total = 0;
	var qty_box;
	var subtotal_box = document.getElementById("subtotal");
	var gst_box = document.getElementById("gst");
	var pst_box = document.getElementById("pst");
	var total_box = document.getElementById("total");
	var temp_quantity;
	var new_array = new Array();
	new_array.push(null);
	
	for (var x=0;x<item_info.length;x++)
	{
		if (!item_info[x]){continue;}			
		var aTmp = item_info[x].split("|");
		if (aTmp.length < 2) {continue;}
			
		iId = aTmp[0];
		iQty = aTmp[1];
		
		qty_box = document.getElementById("qty"+iId);
		temp_quantity = qty_box.value;
		if (!isInt(temp_quantity) && temp_quantity != ''){ temp_quantity = 1; setText(qty_box, temp_quantity); }
		if (temp_quantity != iQty){ item_info[x] = iId+'|'+temp_quantity; }
		new_array.push(item_info[x]);
		subtotal += temp_quantity * parseFloat(getText(document.getElementById("price"+iId)));
	}
	
	item_info = "";
	item_info = init_array();
	item_info = new_array;
	new_array = "";
	set_array(cookieName, item_info, expires);
	
	subtotal = roundNumber(subtotal,2)
	setText(subtotal_box, subtotal);
	
	gst = roundNumber(gst_rate*subtotal,2);
	setText(gst_box, gst);
	
	pst = roundNumber(pst_rate*subtotal,2);
	setText(pst_box, pst);
	
	total = roundNumber(parseInt(gst)+parseInt(pst)+parseInt(subtotal),2);
	setText(total_box, total);
	
	return null;		
}

function echeck(str) 
{
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
		 return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		 return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
			return false
	}

	 if (str.indexOf(at,(lat+1))!=-1){
			return false
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
			return false
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
			return false
	 }
	
	 if (str.indexOf(" ")!=-1){
			return false
	 }

	 return true					
}

function isInt(x) 
{
	 var y=parseInt(x);
	 if (isNaN(y)) return false;
	 return x==y && x.toString()==y.toString();
} 

function checkOrderForm()
{
		var fname = document.getElementById('fname');
		var lname = document.getElementById('lname');
		var phone = document.getElementById('phone');
		var email = document.getElementById('email');
		var comments = document.getElementById('comments');
		
		if (phone.value == '' && email.value == '')
		{
			alert('You must enter your personal information to continue.');
			return false;
		}
		if (email.value != "" && !echeck(email.value))
		{
			alert('Please enter a valid email address');
			return false;
		}
		
		return true;
}

function deleteItemFromCart(id)
{
	var pos = 0;
	var iId, iQty;
	var new_array = new Array();
	new_array.push(null);
	for (var a=0; a<item_info.length; a++) 
	{
		if (item_info[a] == null)
			continue;
			
		var aTmp = item_info[a].split("|");
		if (aTmp.length == 0)
			continue;
			
		iId = aTmp[0];
		iQty = aTmp[1];
		
		if (iId != id)
		{
			new_array.push(item_info[a]);
		}
	}
	
	item_info = "";
	item_info = init_array();
	item_info = new_array;
	new_array = "";
	set_array(cookieName, item_info, expires);
	
	window.location.href=window.location.href;
}

function clearCart()
{
	del_cookie(cookieName);
}

function roll(img_src300, img_src600)
{
	var img300 = document.getElementById('img300');
	var a600 = document.getElementById('a600');
	
	img300.src = img_src300;
	a600.href= img_src600;
	
}
