/*
Functions for saving cart items to cookie

Dependencies: jquery
*/

// Number of days until cookie expires
cookieDays = 30;
cookieName = "products.array";

// Product object
function product(productid, pricingid, qty) {
	this.productid = productid;
	this.pricingid = pricingid;
	this.qty = qty;
}

function serializeProductArray(anArray) {
	// Simple name value pair serialization
	var serial = "";
	for (i in anArray) {
		if (serial.length > 0)
			serial = serial.concat("|");
		serial = serial.concat("productid=" + anArray[i].productid);
		serial = serial.concat("&");
		serial = serial.concat("pricingid=" + anArray[i].pricingid);
		serial = serial.concat("&");
		serial = serial.concat("qty=" + anArray[i].qty);
	}
	return serial;
}

function deserializeProductArray(serial) {
	// Simple name value pair deserialization
	var anArray = new Array();
	var items = serial.split("|");
	for (i in items) {
		var item = items[i];
		var start = item.indexOf("productid=")+10;
		var productId = item.substring(start,item.indexOf("&",start));
		start = item.indexOf("pricingid=")+10;
		var pricingId = item.substring(start,item.indexOf("&",start));
		start = item.indexOf("qty=")+4;
		var qty = item.substring(start);
		anArray[anArray.length] = new product(productId, pricingId, qty);
	}
	return anArray;
}

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 "";
}

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());
}

function addToCookieCart(productId, pricingId, qty) {
	if (this.products == null)
		this.products = new Array();
		
	var index = findProduct(productId);
	if (index > -1) {
		products[index].qty = Number(products[index].qty) + Number(qty);
	} else {
		this.products[this.products.length] = new product(productId, pricingId, qty);
	}
	setCookie(cookieName, serializeProductArray(this.products), cookieDays);
}

function removeFromCookieCart(productId) {
	if (this.products == null)
		return;
		
	var index = findProduct(productId);
	if (index > -1) {
		var newArray = new Array();
		for (i in this.products) {
			if (i != index) {
				newArray[i] = this.products[i];
			}
		}
		this.products = newArray;
	} else {
		return;
	}
	setCookie(cookieName, serializeProductArray(this.products), cookieDays);
}

function clearCookieCart() {
	this.products = new Array();
	setCookie(cookieName, "", cookieDays);
}

function loadCookieCart() {
	// Get the cookie
	var data = getCookie(cookieName);
	this.products = deserializeProductArray(data);
}

function updateCookieCart(items) {
	clearCookieCart();
	// comma-delimted name/value pairs
	var lines = items.split(",");
	for (i in lines) {
		var line = lines[i];
		var details = line.split("=");
		var productId = details[0];
		var pricingId = details[1];
		var qty = Number(details[2]);
		if (qty > 0) {
			addToCookieCart(productId, pricingId, qty);
		}
	}
}

function findProduct(productId) {
	var result = -1;
	for (i in products) {
		if (products[i].productid == productId) {
			result = i;
			break;
		}
	}
	return result;
}

function getCartSize() {
	return products.length;
}



/*
 Functions for main Cart
*/
function hideShowCart() {
	// Show the cart only if not empty
	$.post("getitemcount.htm", {dummy: "test"}, function(cnt) {
		if (cnt > 0) {
			showCart();
			$.post("getitems.htm", {dummy: "test"}, function(rdata) {
				$("#mini_cart_body").html(rdata);
			}, "html");
			$.post("getcarttotals.htm", {dummy: "test"}, function(rdata) {
				$("#mini_cart_totals").html(rdata);
			}, "html");
		}
		else {
			hideCart();
		}
	}, "text");
}

$(document).ready(function() {
	placeCartOnPage();

	hideShowCart();
	
	// Number of days until cookie expires
	cookieDays = 30;
	cookieName = "products.array";

	loadCookieCart();
});


var resizeTimeoutId;

window.onresize = function() {
    window.clearTimeout(resizeTimeoutId); 
    resizeTimeoutId = window.setTimeout('placeCartOnPage();', 100); 
};

function placeCartOnPage() {
	
	//alert("Howdy");
	
	var cartObj = document.getElementById("fixed-cart");
	var origPos = 792;
	var leftPos = origPos;
	if (document.width != undefined) {
		leftPos = ((document.width - 1000) / 2) + origPos;
	} else if (document.body.clientWidth != undefined) {
		leftPos = ((document.body.clientWidth - 1000) / 2) + origPos;
	}
	cartObj.style.position = 'fixed';
	cartObj.style.left = leftPos + 'px';
	cartObj.style.top = 190 + 'px';
}

function addToCart(item) {
	// Get the product and quantity
	var itemId = "" + item.id;
	//productid_xxx_pricingid_xxx
	var firstIndex = item.id.indexOf("productid_")+10;
	var secondIndex = item.id.indexOf("_", firstIndex);
	var thirdIndex = item.id.indexOf("pricingid_", secondIndex)+10;
	var productId = item.id.substring(firstIndex, secondIndex);
	var pricingId = item.id.substring(thirdIndex);
	var qtyVal = 0;
	$("#quantity_"+productId).each(function() {
		qtyVal = this.value;
	});

	if (qtyVal > 0) {
		addToCartExt(productId, pricingId, qtyVal);
	} else {
		alert("You must enter a quantity first!");
	}
}

function addToCartExt(productId, pricingId, qtyVal) {
	addToCookieCart(productId, pricingId, qtyVal);

	// send request and update cart
	$.post("addtocart.htm", {productId: productId, pricingId: pricingId, quantity: qtyVal}, function(rdata) {
		$("#mini_cart_body").html(rdata);
		
		$.post("getcarttotals.htm", {dummy: "test"}, function(rdata) {
			$("#mini_cart_totals").html(rdata);
		}, "html");
	}, "html");
	
	showCart();
}

function replaceInCartExt(replacedIds, productId, pricingId, qtyVal) {
	var ids = replacedIds.split(",");
	for (i in ids) {
		var id = ids[i];
		removeFromCookieCart(id);
	}
	addToCookieCart(productId, pricingId, qtyVal);

	// send request and update cart
	$.post("replaceincart.htm", {replacedIds: replacedIds, productId: productId, pricingId: pricingId, quantity: qtyVal}, function(rdata) {
		$("#mini_cart_body").html(rdata);
		
		$.post("getcarttotals.htm", {dummy: "test"}, function(rdata) {
			$("#mini_cart_totals").html(rdata);
		}, "html");
	}, "html");

	showCart();
}

function hideCart() {
	$("#mini_cart_div").each(function() {
		this.style.display = "none"; 
	});
	$("#mini_cart_div_spacer").each(function() {
		this.style.display = ""; 
	});
}

function showCart() {
	$("#mini_cart_div").each(function() {
		this.style.display = ""; 
	});
	$("#mini_cart_div_spacer").each(function() {
		this.style.display = "none"; 
	});
}

function clearCart() {
	clearCookieCart();

	// send request and update cart
	$.post("emptycart.htm", {dummy: "test"}, function(rdata) {
		$("#mini_cart_body").html(rdata);

		$.post("getcarttotals.htm", {dummy: "test"}, function(rdata) {
			$("#mini_cart_totals").html(rdata);
		}, "html");
	}, "html");

	showCart();
}

function collapseCart(toggle) {
	var state = "expanded";
	$("#mini_cart_body").each(function() {
		if (toggle) {
			if (this.style.display == "") {
				this.style.display = "none";
				state = "collapsed";
			} else {
				this.style.display = "";
				state = "expanded";
			}
		} else {
			this.style.display = "none";
			state = "collapsed";
		}
	});
	
	$("#mini_cart_collapse").each(function() {
		if (state == "collapsed") {
			this.src = this.src.replace("minus.png", "plus.png");
		} else {
			this.src = this.src.replace("plus.png", "minus.png");
		}
	});
}

function expandCart() {
	$("#mini_cart_body").each(function() {
		this.style.display = ""; 
	});
}


function removeFromCart(productid) {
	removeFromCookieCart(productid);

	// send request and update cart
	$.post("removefromcart.htm", {productid: productid}, function(rdata) {
		$("#mini_cart_body").html(rdata);

		$.post("getcarttotals.htm", {dummy: "test"}, function(rdata) {
			$("#mini_cart_totals").html(rdata);
		}, "html");
	}, "html");

	hideShowCart();
}

function updateCart() {
	$("#mini_cart_body").each(function() {
		var items = "";
		$("tr", this).each(function() {
			if (this.id != undefined) {
				var itemId = "" + this.id;
				if (itemId.length > 0) {
					//alert("Item id: " + this.id);
					var firstIndex = itemId.indexOf("productid_")+10;
					var secondIndex = itemId.indexOf("_",firstIndex);
					var thirdIndex = itemId.indexOf("pricingid_")+10;
					var productId = itemId.substring(firstIndex, secondIndex);
					var pricingId = itemId.substring(thirdIndex);
					var qty = 0;
					$(":input", this).each(function() {
						qty = Number(this.value);
					});
					
					if (items.length > 0)
						items = items + ",";
					items = items + productId + "=" + pricingId + "=" + qty;
				}
			}
		});
		//alert("Items: " + items);
		
		$.post("updatecart.htm", {lines: items}, function(rdata) {
			$("#mini_cart_body").html(rdata);

			$.post("getcarttotals.htm", {dummy: "test"}, function(rdata) {
				$("#mini_cart_totals").html(rdata);
			}, "html");
		}, "html");

		hideShowCart();
		
		updateCookieCart(items);
	});
}
