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

timeToKeep = 180000000; // 50 Hours
expires = new Date();
expires.setTime(expires.getTime() + timeToKeep);

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

function init(typeid)
{	
		var prnt, cartid;
		
		//set the carts
		var carts = getElementsByClassName("cart_image");
		for (var y = 0; y<carts.length; y++)
		{
			prnt = carts[y].parentNode;
			cartid = prnt.id.replace("img2", "");
			for (var u = 0; u<itemids.length; u++)
			{
				if (cartid == itemids[u])
				{
					setCartIcon(cartid,"remove");
				}
			}
		}
}

function setCartIcon(id,value)
{
	alt = "";
	node = document.getElementById("cart"+id);
	if (value == "add")
	{
		alt = "Add To Cart";
	}
	else if (value == "remove")
	{
		alt = "Remove From Cart";
	}
	node.alt = alt;
	node.src = 'Images/cart_'+value+'.png'; ;
}

function setArrowIcon(id, value)
{
	node = document.getElementById("img"+id);
	node.src = "Images/arrow_"+value+".gif";
	return false;
}

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 getMenuItem(id)
{
		var itm = false;
		if(document.getElementById)
				itm = document.getElementById(id);
		else if(document.all)
				itm = document.all[id];
		else if(document.layers)
				itm = document.layers[id];

		return itm;
}

function toggleMenuItem(id)
{
		itm = getMenuItem(id);

		if(!itm)
				return false;

		if(itm.style.display == 'none')
				itm.style.display = '';
		else
				itm.style.display = 'none';
}
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 changeIcon(obj)
{
	if(!obj)
		return false;
	
	if(stringRight(obj.firstChild.src,8) == "down.gif")
	{
		obj.firstChild.src = 'Images/arrow_up.gif';
	}
	else if (stringRight(obj.firstChild.src,6) == "up.gif")
	{
		obj.firstChild.src = 'Images/arrow_down.gif';
	}
	return false;
}

function Cart(obj)
{
	if(!obj)
		return false;
	
	var myid = obj.id.replace("img2", "");
	
	if(stringRight(obj.firstChild.src,7) == "add.png")
	{
		
		setCartIcon(myid, "remove");
		
		//add item
		var num = next_entry(itemids);
		itemids[num] = myid;
		set_array(cookieName, itemids, expires);
	}
	else if (stringRight(obj.firstChild.src,10) == "remove.png")
	{
		setCartIcon(myid, "add");
		var temparray = new Array();
		
		//remove item
		for (var a = 0; a<itemids.length; a++)
		{
				if (itemids[a] != myid)
				{
					temparray.push(itemids[a]);
				}
		}
		itemids = "";
		itemids = init_array();
		itemids = temparray;
		temparray = "";
		set_array(cookieName, itemids, expires);
	}
	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 parseFloat(newString);
}


function calculateTotals()
{
	var subtotal = 0;
	var gst = 0;
	var pst = 0;
	var total = 0;
	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;
	
	for (var x=0;x<itemids.length;x++)
	{
		if (!itemids[x])
			continue;
		temp_quantity = document.getElementById("qty"+itemids[x]).value;
		subtotal += temp_quantity * parseFloat(getText(document.getElementById("price"+itemids[x])));
	}
	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((gst+pst+subtotal),2);
	setText(total_box, total);
					
}

function changeQuantity(obj, id)
{
	var price_box = document.getElementById("price"+id);
	var quantity = obj.value;
	var price = getText(price_box);
	var new_price = quantity * price;
	new_price = Math.round(new_price*100)/100;
	
	calculateTotals();
}

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');
		var subtotal = document.getElementById('hid_subtotal');
		var gst = document.getElementById('hid_gst');
		var pst = document.getElementById('hid_pst');
		var total = document.getElementById('hid_total');
		var quantities = document.getElementById('quantitiesstring');
		
		var subtotal_box = document.getElementById("subtotal");
		var gst_box = document.getElementById("gst");
		var pst_box = document.getElementById("pst");
		var total_box = document.getElementById("total");
		
		if (fname.value == '' || lname.value == '' || phone.value == '')
		{
			alert('You must enter your personal information to continue.');
			return false;
		}
		else if (!echeck(email.value))
		{
			alert('Please enter a valid email address');
			return false;
		}
		else if (itemids.length < 1)
		{
			alert('Your shopping cart is empty!');
			return false;
		}
		
		//loop through all items and get quantities
		var qtys = getElementsByClassName("qty_box");
		var q_string = "";
		for (var x=0; x<qtys.length; x++)
		{
			if (!isInt("1"))
			{
					alert("Please enter only valid numbers for the quantities");
					return false;
			}
			q_string += qtys[x].value + '^';
		}
		
		quantities.value = q_string;
		subtotal.value = getText(subtotal_box);
		gst.value = getText(gst_box);
		pst.value = getText(pst_box);
		total.value = getText(total_box);
		
		clearCart();
		return true;
		
}

function deleteItemFromCart(id)
{
	var pos = 0;
	for (var i=1; i<next_entry(itemids); i++) 
	{
		if (itemids[i] == id)
			pos = i;
	}
	del_entry(cookieName, itemids, pos, expires);
	window.location.href=window.location.href;
}

function clearCart()
{
	del_cookie(cookieName);
	itemids = "";
	itemids = init_array();
	get_array(cookieName, itemids);
}

function checkEmailForm() 
{
	var email = document.getElementById('youremail');
	var subject = document.getElementById('subject');
	var message = document.getElementById('message');
	
	
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (!filter.test(email.value)) 
	{
		alert('Please provide a valid email address');
		email.focus;
		return false;
	}
	else if (subject.value == '')
	{
		alert('Please provide a valid subject');
		subject.focus;
		return false;
	}
	else if (message.value == '')
	{
		alert('Please provide a valid message');
		message.focus;
		return false;
	}
	
	return true;
}