// requirements:

// 3 required fields (cart_cylinder, cart_bgcolor, cart_color) // cart_color now removed

// call addCart(id, name) where id is a unique number, and name has no special characters including apostrophes and commas

// this requires the window.onload

PRICE_CA = 64;
PRICE_CYL_CA = 24;
PRICE_US = 64;
PRICE_CYL_US = 24;
TAX_CA = 0.12;
DISCOUNT_1 = 8;
DISCOUNT_2 = 16;

C_SHIPPING_US = 15;
C_SHIPPING_CA = 10;
C_SHIPPING_CYL_US = 6;
C_SHIPPING_CYL_CA = 6;

window.onload = function() {
    var store = window.location.toString().search(/\/store\//);
    if(store != -1) checkCountry(window.location.toString().substring(store+7));
	var loc = window.location.toString();
	if(loc.substr(loc.length-9) == "cart.html") {
		showCart();
	}
	else {
		//setNoCylinder();
	}
	// now using version 2 for immediate document write, and this one for onclick changes only!
	//setCartCount();
}



function loadPriceText() {
    if(getCookie("country") == "us") {
        document.write(PRICE_US);
    } else {
        document.write(PRICE_CA);
    }
}

function loadPriceText2() {
    var text = " + $";
    if(getCookie("country") == "us") {
        text += C_SHIPPING_US + " shipping";
    } else {
        var tax = (PRICE_CA + C_SHIPPING_CA) * TAX_CA;
        text += C_SHIPPING_CA + " shipping + $" + tax.toFixed(2) + " tax";
    }
    document.write(text);
}

function changePrice() {
	var div = document.getElementById('cart_cylinder');
    var price;
    var text = " + $";
	if(div) {
        if(div.value == "1") {
            // cylinder
            if(getCookie("country") == "us") {
                price = PRICE_CYL_US;
                text += C_SHIPPING_CYL_US + " shipping";
            } else {
                price = PRICE_CYL_CA;
                var tax = (PRICE_CYL_CA + C_SHIPPING_CYL_CA) * TAX_CA;
                text += C_SHIPPING_CYL_CA + " shipping + $" + tax.toFixed(2) + " tax";
            }
    	} else {
    	   // no cyl
    		if(getCookie("country") == "us") {
                price = PRICE_US;
                text += C_SHIPPING_US + " shipping";
            } else {
                price = PRICE_CA;
                var tax = (PRICE_CA + C_SHIPPING_CA) * TAX_CA;
                text += C_SHIPPING_CA + " shipping + $" + tax.toFixed(2) + " tax";
            }
    	}
    	document.getElementById('cart_price').innerHTML = '$' + price;
        document.getElementById('cart_taxshipping').innerHTML = text;
    }
}

function checkCountry(page) {

	var country=getCookie("country");

	if(country != "us" && country != "ca" && page != 'country.html') {

		setCookie("page",page,1);

		if(!getCookie("page")) {
			alert("You need to enable cookies for the shopping cart to work!");
		}

		var dir = "";
		if(window.location.toString().search(/\/store\//) == -1) dir = "store/";

		window.location=dir+"country.html";

		return false;

	}

	return true;

}



function goCountry(id) {

	setCookie("country", id, 1);

	var c = getCookie("page");

	if(c == "" || c.substr(c.length-12) == "country.html") c = "../index.html";

	window.location=c;

	return false;

}



function countQuantity(i, value, list) {

	if(list.length <= i || list[i] != value) return i

	return countQuantity(i+1, value, list);

}




function showCart() {

	var cart=getCookie("cart");

	var length = 0;

	if(cart != "") {

		cart = cart.split(",");

		length = cart.length

		cart = cart.sort();

	}

    var country=getCookie("country");

	var C_PRICE = (country == 'us' ? PRICE_US : PRICE_CA);

	var C_PRICE_CYL = (country == 'us' ? PRICE_CYL_US : PRICE_CYL_CA);

	var ship = (country == 'us' ? C_SHIPPING_US : C_SHIPPING_CA);

	var ship_cyl = (country == 'us' ? C_SHIPPING_CYL_US : C_SHIPPING_CYL_CA);

	var div=document.getElementById("cart_table");

	var item;

	var count = 1;

	var cyl_count = 0;

	var total_count = 0;

	var table;

	var paypal = "";

	var paypal_count = 1;

	var paypal_name;

	var price;

	var cylinder;

	var ship_p;

	var paypal_discount = 0;

	// cookie: name, id, cylinder, bgcolor, color

	if(div != null) {

		table = "<table cellspacing='0' id='confirm'><tr><th width='5%'></th><th width='40%'>Item</th><th width='30%'>Background Color</th><th width='10%'>Qty</th></tr>";//<th width='20%'>Top Color</th>

		for(i = 0; i < length; i+=count) {

			count = countQuantity(i+1, cart[i], cart) - i;

			item = cart[i].split('.');

			if(item[2] == "1") {

				item[0] += " (Cylinder Only)";

				cyl_count += count;

				price = C_PRICE_CYL;//-ship_cyl;

				ship_p = ship_cyl;

			}

			else {

				total_count += count;

				price = C_PRICE;//-ship;

				ship_p = ship;

			}

			table += "<tr><td><input name='Remove' type='checkbox' value='"+cart[i]+"' /></td><td>"+item[0]+"</td><td>"+item[3]+"</td><td>"+count+"</td></tr>"; //<td>"+item[4]+"</td>

			paypal_name = item[0];

			paypal += '<input type="hidden" name="quantity_'+paypal_count+'" value="'+count+'" /><input type="hidden" name="item_name_'+paypal_count+'" value="'+paypal_name+'" /><input type="hidden" name="item_number_'+paypal_count+'" value="'+item[1]+'" /><input type="hidden" name="amount_'+paypal_count+'" value="'+price.toFixed(2)+'" /><input type="hidden" name="shipping_'+paypal_count+'" value="'+ship_p+'" /><input type="hidden" name="shipping2_'+paypal_count+'" value="'+ship_p+'" /><input type="hidden" name="on0_'+paypal_count+'" value="Background Color" /><input type="hidden" name="os0_'+paypal_count+'" value="'+item[3]+'" />'; //<input type="hidden" name="on1_'+paypal_count+'" value="Top Color" /><input type="hidden" name="os1_'+paypal_count+'" value="'+item[4]+'" />

			paypal_count++;



		}

		var discount = 0;

		discount += DISCOUNT_1*Math.floor((1+total_count)/3);

		discount += DISCOUNT_2*Math.floor(total_count/3);

        var shipping = (ship*total_count)+(ship_cyl*cyl_count);

		var subtotal = (total_count*C_PRICE)+(cyl_count*C_PRICE_CYL);

		var gst = (shipping+subtotal)*TAX_CA;

		var total = shipping+subtotal+(country == 'us' ? 0 : gst)-discount;//+shipping

        //subtotal -= shipping; // so shipping can display separately, but it was already included in original price

		table += "</table><br /><table cellspacing='0' id='shipping'><tr><td>Sub-Total:</td><td><div align='right'>$"+subtotal.toFixed(2)+"</div></td><td>&nbsp;</td></tr><tr><td>Shipping:</td><td><div align='right'>$"+shipping.toFixed(2)+"</div></td><td>&nbsp;</td></tr><tr><td>Shipping Discount:</td><td><div align='right'>-$"+discount.toFixed(2)+"</div></td><td>&nbsp;</td></tr>"+(country == 'us' ? "" : "<tr><td>Tax:</td><td><div align='right'>$"+gst.toFixed(2)+"</div></td><td>&nbsp;</td></tr>")+"<tr><td>TOTAL:</td><td><div align='right'><strong>$"+total.toFixed(2)+"</strong></div></td><td>"+(country == 'us' ? 'USD' : 'CAD')+"</td></tr></table>"

		//document.getElementById("cart_form").value = getCookie("cart");

		//document.getElementById("amount_form").value = total-5;

		div.innerHTML = table;

        if(country != 'us') {
		  paypal += '<input type="hidden" name="tax_cart" value="'+gst.toFixed(2)+'" />';
        }

		if(discount > 0) {
			paypal += '<input type="hidden" name="discount_amount_cart" value="'+discount.toFixed(2)+'" />';
		}

	}

	paypal += '<input type="hidden" name="currency_code" value="'+(country == 'us' ? 'USD' : 'CAD')+'" />';

		document.getElementById('paypal_div').innerHTML = paypal;

}



function setCartCount() {

	var cart=getCookie("cart");

	var length = 0;

	if(cart != "") {

		length = cart.split(",").length

	}

	var text = " item";

	if(length != 1) text += "s";

	var div=document.getElementById("cart_count");

	if(div != null) {

		div.innerHTML = length + text;

	}

}

function setCartCount2() {

	var cart=getCookie("cart");

	var length = 0;

	if(cart != "") {

		length = cart.split(",").length

	}

	var text = " item";

	if(length != 1) text += "s";

	document.write(length + text);

}

// cookie: name, id, cylinder, bgcolor, color

function addCart(id, name) {

	var cart=getCookie("cart");

	if(cart != "") {

		cart+=",";

	}



	setCookie("cart", cart+name+"."+id+"."+document.getElementById("cart_cylinder").value+"."+document.getElementById("cart_bgcolor").value, 1);
//+"."+document.getElementById("cart_color").value


	setCartCount();

}



function remCart() {

	var cart=getCookie("cart").split(',');

	var boxes = document.getElementsByName("Remove");

	for(i = 0; i < boxes.length; i++) {

		if(boxes[i].checked) {

			for(j = cart.length-1; j >= 0; j--) {

				if(cart[j] == boxes[i].value) cart.splice(j, 1);

			}

		}

	}

	setCookie("cart", cart.toString(), 1);

	showCart();

	setCartCount();

}



function setCookie(c_name,value,expiredays) {

	var exdate=new Date();

	exdate.setDate(exdate.getDate()+expiredays);

	document.cookie=c_name+"="+escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString()+"; path=/");

}



function getCookie(c_name) {

	if (document.cookie.length > 0) {

		c_start=document.cookie.indexOf(c_name + "=");

		if (c_start!=-1) {

			c_start=c_start + c_name.length+1;

			c_end=document.cookie.indexOf(";",c_start);

			if (c_end==-1) c_end=document.cookie.length;

			return unescape(document.cookie.substring(c_start,c_end));

		}

	}

	return "";

}