// fuse interactive 2006
// Glinda Girls
/* code for url encoding/decoding */
/**
*
* URL encode / decode
* http://www.webtoolkit.info/
*
**/

var Url = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}

// old start
if (window.XMLHttpRequest){
		var xmlHttp = new XMLHttpRequest()
	}
	else if (window.ActiveXObject){
		var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	}

function selectVariation(vari_name,vari_price,vari_image,pro_id){


		$('#photoLink').attr({href: "http://www.glindagirls.com/images/products/"+ pro_id +"/" + vari_image + "_large.jpg"}).fadeIn("slow");
		$('#photo').attr({src: "http://www.glindagirls.com/images/products/"+ pro_id +"/" + vari_image + ".jpg" }).fadeIn("slow");
		$('li').removeClass("selectedVari");
		$('#' + vari_image).addClass("selectedVari").fadeIn("slow");
		$('#item_name').attr({value: "" + vari_name});
		$('#amount').attr({value: "" + vari_price});
		$('#sub_photoLinks').find("a").removeClass("selected_photoLink");
		$('#sub_photoLink_' + vari_image).addClass("selected_photoLink");
		$('#product_Price').empty().append("$" + vari_price).fadeIn("slow");
	}

function selectAttribute(attribute,attr_number){


		$('li').removeClass("selectedAttr");
		$('#attr_' + attr_number).addClass("selectedAttr").fadeIn("slow");
		$('#item_name').attr({value: "" + attribute});
	}

function changeProductPhoto(pro_id,vari_image){

		$('#photo').attr({src: "http://www.glindagirls.com/images/products/"+ pro_id +"/" + vari_image + ".jpg" }).fadeIn("slow");
		$('#photoLink').attr({href: "http://www.glindagirls.com/images/products/"+ pro_id +"/" + vari_image + "_large.jpg"}).fadeIn("slow");
		$('#sub_photoLinks').find("a").removeClass("selected_photoLink");
		$('#sub_photoLink_' + vari_image).addClass("selected_photoLink");

	}

function addToCart(productid,productname){

		var allSelected = false;
		var price = "noprice";
		var variation = "novariation";
		var attribute = "noattribute";
		var quantity = 1;

		if($("ul.variations").children().is("li") || $("ul.attributes").children().is("li")){
			//check for selected variations
			if($("ul.variations").children().is("li.selectedVari")){
				allSelected = true;
				 variation = $("li.selectedVari").find("span.product_name").text();
				 price = $("li.selectedVari").find("span.product_price").attr("id");
			}
			else {

				price = $("h6.product_Price").attr("id");
				$('#product_RightInfo').find("div.missinginfo").remove();
				$('#vari_head').after("<div class=\"missinginfo\">Please select one of the available options</div>").fadeIn("slow");}

			//check for selected attributes
			if($("ul.attributes").children().is("li.selectedAttr")){
				allSelected = true;
				attribute = $("li.selectedAttr").text();
			}
			else {
				$('#product_RightInfo').find("div.missinginfo").remove();
				$('#attr_head').after("<div class=\"missinginfo\">Please select one of the available options</div>").fadeIn("slow");}
			//add it
			if(allSelected){

				quantity = $('#quantity').val();
				$('#shoppingBag').css("background-color","#fe2e7e").fadeIn("fast");
				$('#shoppingBag').css("color","#ffffff").fadeIn("fast");
				
				$('#cartAlert').css("display", "block").fadeIn("fast");
				$('#cartAlert').html('You have added ' + Url.decode(productname) + ' to your cart. <a href="/cart/">Checkout</a>');				
				var url = "http://www.glindagirls.com/addToCart.php?productid=" + productid + "&productname=" + productname + "&variation=" + variation + "&attribute=" + attribute + "&price=" + price + "&quantity=" + quantity;
				xmlHttp.open("GET", url, false);
				xmlHttp.send(null);

				}

		}
		else{
			quantity = $('#quantity').val();

			$('#shoppingBag').css("background-color","#fe2e7e").fadeIn("fast");
			$('#shoppingBag').css("color","#ffffff").fadeIn("fast");
			
			$('#cartAlert').css("display", "block").fadeIn("fast");
			$('#cartAlert').html('You have added ' + Url.decode(productname) + ' to your cart. <a href="/cart/">Checkout</a>');			
			var url = "http://www.glindagirls.com/addToCart.php?productid=" + productid + "&productname=" + productname + "&variation=" + variation + "&attribute=" + attribute + "&price=" + price + "&quantity=" + quantity;
			xmlHttp.open("GET", url, false);
			xmlHttp.send(null);
			}

	//alert(productname);
	//alert(url);

	}

function addToCart_Overview(productid,productname,productprice){

		//put it into the shopping bag
		$('#shoppingBag').css("background-color","#fe2e7e").fadeIn("fast");
		$('#shoppingBag').css("color","#ffffff").fadeIn("fast");
		
		$('#cartAlert').css("display", "block").fadeIn("fast");
		$('#cartAlert').html('You have added ' + Url.decode(productname) + ' to your cart. <a href="/cart/">Checkout</a>');
		var url = "http://www.glindagirls.com/addToCart.php?productid=" + productid + "&productname=" + productname + "&variation=novariation&attribute=noattribute&price=" + productprice + "&quantity=1";
		xmlHttp.open("GET", url, false);
		xmlHttp.send(null);

	}

function removeProductFromCart(itemid){

		var item_id = itemid+1;
		$('#item_'+ item_id).slideUp("slow");
		var url = "http://www.glindagirls.com/removeFromCart.php?itemid=" + itemid;
		xmlHttp.open("GET", url, false);
		xmlHttp.send(null);
		document.location.reload( true );

	}

function checkOut(){

		if($('#item_1').children().is("td")){
			}
		else{
				$('#shopping_bag').find("h2").after("<div class=\"missinginfo\">There are no items in your shopping bag.</div>").fadeIn("slow");
				return false;


			}

	}

function changeCurrency(currency){


		if(currency == 'ca'){
			currency = "CAD";
			$('#us_flag').removeClass("currentCurrency");
			$('#ca_flag').addClass("currentCurrency");

		}
		else {
			currency = "USD";
			$('#ca_flag').removeClass("currentCurrency");
			$('#us_flag').addClass("currentCurrency");
		}

		var url = "http://www.glindagirls.com/changeCurrency.php?currency=" + currency;
		xmlHttp.open("GET", url, false);
		xmlHttp.send(null);
		document.location.reload( true );

	}

function validateDiscountCode(oldtotal,currentcurrency){

		var discountcode = $('#discountcode').val();

		var url = "http://www.glindagirls.com/validatediscountcode.php?discountcode=" + discountcode + "&oldtotal=" + oldtotal + "&action=validate";

		xmlHttp.open("GET", url, true);
		xmlHttp.onreadystatechange = stateChangedDiscountCode;
		xmlHttp.send(null);

}

function stateChangedDiscountCode()
{
	$('#discountproblem').remove();

	if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete")
	{
		if (xmlHttp.responseText == "error")
		{
			$('#shopping_bag').find("h2").after("<div id=\"discountproblem\" class=\"missinginfo\">The discount code couldn't be applied.</div>").fadeIn("slow");
			return false;
		}
		else if (xmlHttp.responseText == "badcode")
		{
			$('#discountproblem').remove();
			$('#shopping_bag').find("h2").after("<div id=\"discountproblem\" class=\"missinginfo\">This discount code isn't valid</div>").fadeIn("slow");
			return false;
		}
		else if (xmlHttp.responseText > 0)
		{
			//var oldtotal = $('#totalPrice').attr("title");
			//var newtotal = Math.round(oldtotal*(100 - xmlHttp.responseText))/100;
			//$('#shopping_bag').find("input.trnAmount").attr("value", function() { return Math.round(this.value *(100 - xmlHttp.responseText))/100; });

			document.getElementById('ordItemPrice').value = Math.round((document.getElementById('ordItemPrice').value * (100 - xmlHttp.responseText) / 100) * 100)/100;
			document.getElementById('ordTax1Price').value = Math.round((document.getElementById('ordItemPrice').value / 100 * 6) * 100)/100;

			document.getElementById('trnAmount').value = Math.round((Number(document.getElementById('ordShippingPrice').value) + Number(document.getElementById('ordTax1Price').value) + Number(document.getElementById('ordItemPrice').value)) * 100)/100;


			$('#shopping_bag').find("h2").after("<div id=\"discountproblem\" class=\"discountinfo\">Discount was applied to your total order.</div>").fadeIn("slow");
			$('#discountCodeButton').attr({onclick: ""});

			function formatAsMoney(mnt) {
			    mnt -= 0;
			    mnt = (Math.round(mnt*100))/100;
			    return (mnt == Math.floor(mnt)) ? mnt + '.00'
			              : ( (mnt*10 == Math.floor(mnt*10)) ?
			                       mnt + '0' : mnt);
			}

			$('#tax').empty().append('Tax: $' + formatAsMoney(document.getElementById('ordTax1Price').value) + '&nbsp;');
			if ($('#currency_code').val() == 'CAD') $('#tax').append('CAD');
			$('#tax').addClass("highlight");

			$('#totalPrice').empty().append('Total: $' + formatAsMoney(document.getElementById('trnAmount').value) + '&nbsp;');
			if ($('#currency_code').val() == 'CAD') $('#totalPrice').append('CAD');
			$('#totalPrice').addClass("highlight");
		}
	}
}

function tax(in_canada)
{
	taxval = $('#ordItemPrice').val() / 100 * 6;
	taxval = Math.round(taxval * 100) / 100;
	taxval = taxval.toFixed(2);

	if (in_canada == 'yes')
	{
		$('#in_canada_tax').html(taxval);
		$('#ordTax1Price').attr({value: taxval});
	}
	else
	{
		$('#in_canada_tax').html('0');
		$('#ordTax1Price').attr({value: 0});
	}

	total = parseFloat($('#ordShippingPrice').val()) + parseFloat($('#ordItemPrice').val()) + parseFloat($('#ordTax1Price').val());
	total = total.toFixed(2);
	$('#trnAmount').attr({value: total});
	$('#total').html(total);
}