/* -------------------- */
/*   Option Functions   */
/* -------------------- */

function selectProductOption(key, changed) {
	// initialize variables
	var link       = urlPrefix + "://" + CGI["http_host"] + "/store/remote/cart.cfm/mode/getNextOptionType";
	var params     = "json=1&key=" + key;
	var numOptions = parseInt(jQuery("form#pendingForm input#optioncount_" + key).val());
	var selOptions = "";
	var thisOption = "";

	changed = parseInt(changed);

	// Did we select the last option or a previous?
	if(numOptions > changed) {
		for( var d = numOptions; d > changed; d-- ) {
			jQuery("table#option" + d + "table_" + key).remove();
		}

		numOptions = changed;

		jQuery("form#pendingForm input#optioncount_" + key).val(numOptions);
	}

	// If we selected a blank option, do nothing.
	if(jQuery("form#pendingForm select#option" + changed + "_" + key).val() == "") return false;

	for( var o = 1; o <= changed; o++ ) {
		thisOption = jQuery("form#pendingForm select#option" + o + "_" + key).val();

		if(thisOption != "") {
			if (selOptions == "") {
				selOptions = thisOption;
			} else {
				selOptions += "," + thisOption;
			}
		}
	}

	params = params + "&selected=" + selOptions;

	jQuery.ajaxSetup ({ cache: false });

	jQuery.post(link, params, function(json) {
		if(json.recordcount > 0) {
			// Update the option count.
			numOptions += 1;
			jQuery("form#pendingForm input#optioncount_" + key).val(numOptions);

			var newOptionBlock = jQuery("div#optionblock").html();
			var optionType     = "";
			var optionHTML     = "";
			var iRegEx         = new RegExp("%i%", "g");
			var keyRegEx       = new RegExp("%key%", "g");
			var typeRegEx      = new RegExp("%type%", "g");

			newOptionBlock = newOptionBlock.replace(iRegEx, numOptions);
			newOptionBlock = newOptionBlock.replace(keyRegEx, key);

			for(var i = 0; i < json.recordcount; i++) {
				optionType = json.data.option_type[i];

				// Build the options as a string...
				optionHTML += "<OPTION VALUE='" + json.data.option_id[i] + "'>" + json.data.option_name[i] + "</OPTION>\n";
			}

			newOptionBlock = newOptionBlock.replace(typeRegEx, optionType);

			jQuery("div#optionDiv_" + key).append(newOptionBlock);
			jQuery("form#pendingForm select#option" + numOptions + "_" + key).append(optionHTML);
		} else {
			// If results are blank, there are no more options. We should validate the current combination.
			checkOptionCombo(key);
		}

		jQuery.ajaxSetup ({ cache: true });
	}, "json");
}

function checkOptionCombo(key) {
	// initialize variables
	var link       = urlPrefix + "://" + CGI["http_host"] + "/store/remote/cart.cfm/mode/validateOptions";
	var params     = "json=1&key=" + key;
	var numOptions = parseInt(jQuery("form#pendingForm input#optioncount_" + key).val());
	var selOptions = "";
	var thisOption = "";

	for( var o = 1; o <= numOptions; o++ ) {
		thisOption = jQuery("form#pendingForm select#option" + o + "_" + key).val();

		if(thisOption != "") {
			if(selOptions == "") {
				selOptions = thisOption;
			} else {
				selOptions += "," + thisOption;
			}
		}
	}

	params = params + "&optionIds=" + selOptions;

	jQuery.ajaxSetup ({ cache: false });

	// Ajax Post
	jQuery.post(link, params, function(json) {
		if(json.recordcount == 1) {
			var result     = json.data.result[0];
			var picture    = json.data.picture[0];
			var finalPrice = json.data.finalprice[0];
			var subTotal   = json.data.subtotal[0];

			if(result == 1) {
				if(picture != "") {
					jQuery("img#pictureholder_" + key).attr("src", "/images/store/" + picture);
				} else {
					jQuery("img#pictureholder_" + key).attr("src", "/common/images/spacer.gif");
				}

				// Update any spans.
				jQuery("span#itemtotal_" + key).empty().html("$" + finalPrice.toFixed(2));
				jQuery("span#pending_subtotal").empty().html("$" + subTotal.toFixed(2));
			} else {
				alert("That is an invalid option combination. Please select another.");
			}
		} else {
			alert("There was an error. If this occurs frequently, please contact the site administrator.");
		}

		jQuery.ajaxSetup ({ cache: true });
	}, "json");
}

function resetOptions(key) {
	// initialize variables
	var link      = urlPrefix + "://" + CGI["http_host"] + "/store/remote/cart.cfm/mode/resetPendingOptions";
	var params    = "json=1&key=" + key;

	jQuery.ajaxSetup ({ cache: false });

	jQuery.post(link, params, function(json) {
		var link2   = urlPrefix + "://" + CGI["http_host"] + "/store/remote/cart.cfm/mode/getNextOptionType";
		var params2 = "json=1&key=" + key;

		if(json.recordcount == 1) {
			var result     = json.data.result[0];
			var picture    = json.data.picture[0];
			var finalPrice = json.data.finalprice[0];
			var subTotal   = json.data.subtotal[0];

			if(result == 1) {
				// Restore picture
				if(picture != "") {
					jQuery("img#pictureholder_" + key).attr("src", "/images/store/" + picture);
				} else {
					jQuery("img#pictureholder_" + key).attr("src", "/common/images/spacer.gif");
				}

				// Update any spans.
				jQuery("span#itemtotal_" + key).html("$" + finalPrice.toFixed(2));
				jQuery("span#pending_subtotal").html("$" + subTotal.toFixed(2));

				// Get the option types to repopulate the select.
				jQuery.post(link2, params2, function(json2) {
					if(json2.recordcount > 0) {
						// Delete the hidden fields with the selected options.
						var numOptions = parseInt(jQuery("form#pendingForm input#optioncount_" + key).val());

						for( var d = numOptions; d > 0; d-- ) {
							jQuery("table#option" + d + "table_" + key).remove();
						}

						// Delete the link that got up here.
						jQuery("#optionLink_" + key).remove();

						// Reset the option count.
						numOptions = 1;
						jQuery("form#pendingForm input#optioncount_" + key).val(numOptions);

						// Populate and create the initial option select.
						var newOptionBlock = jQuery("div#optionblock").html();
						var optionType     = "";
						var optionHTML     = "";
						var iRegEx         = new RegExp("%i%", "g");
						var keyRegEx       = new RegExp("%key%", "g");
						var typeRegEx      = new RegExp("%type%", "g");

						newOptionBlock = newOptionBlock.replace(iRegEx, numOptions);
						newOptionBlock = newOptionBlock.replace(keyRegEx, key);

						for(var i = 0; i < json2.recordcount; i++) {
							optionType = json2.data.option_type[i];

							// Build the options as a string...
							optionHTML += "<OPTION VALUE='" + json2.data.option_id[i] + "'>" + json2.data.option_name[i] + "</OPTION>\n";
						}

						newOptionBlock = newOptionBlock.replace(typeRegEx, optionType);

						jQuery("div#optionDiv_" + key).append(newOptionBlock);
						jQuery("form#pendingForm select#option" + numOptions + "_" + key).append(optionHTML);
					} else {
						alert("There was an error. If this occurs frequently, please contact the site administrator.");
					}
				}, "json");
			} else {
				alert("There was an error. If this occurs frequently, please contact the site administrator.");
			}
		} else {
			alert("There was an error. If this occurs frequently, please contact the site administrator.");
		}

		jQuery.ajaxSetup ({ cache: true });
	}, "json");
}

/* ----------------- */
/*   Add Functions   */
/* ----------------- */

function addToCart() {
	var link       = urlPrefix + "://" + CGI["http_host"] + "/store/remote/cart.cfm/mode/moveToCart";
	var key        = jQuery(this).attr("data-key");
	var params     = "json=1&key=" + key;
	var numOptions = jQuery("form#pendingForm input#optioncount_" + key).val();
	var optionList = "";
	var qty        = jQuery("form#pendingForm input#cartqty_" + key).val();

	if(qty == 0) {
		alert("You cannot add 0 items to the cart.");
		return false;
	}

	jQuery(this).attr("disabled",true).css("cursor","default").animate({opacity:0.4},"fast");

	for(var o = 1; o <= numOptions; o++) {
		if(optionList == "") {
			optionList = jQuery("form#pendingForm #option" + o + "_" + key).val();
		} else {
			optionList = optionList + "," + jQuery("form#pendingForm #option" + o + "_" + key).val();
		}
	}

	params = params + "&qty=" + qty;
	params = params + "&optionlist=" + optionList;

	jQuery.ajaxSetup ({ cache: false });

	jQuery.post(link, params, function(json) {
		if(json.recordcount == 1) {
			var DoCommit     = json.data.docommit[0];
			var definition   = json.data.definition[0];
			var pendingCount = json.data.pendingcount[0];
			var subTotal     = json.data.subtotal[0];

			if(DoCommit == 1) {
				var pendingMessage = pendingCount + " item";
	
				if(pendingCount != 1) {
					pendingMessage += "s";
				}

				// Hide things accordingly.
				if(pendingCount == 0) {
					jQuery("#pendingLayer").fadeOut("fast",function() {
						jQuery("#pendingLayer").empty().html("");
					});
				} else {
					jQuery("#pendingitem_" + key).fadeOut("fast",function() {
						jQuery("#pendingitem_" + key).empty().html("");
					});
				}

				// Update any spans.
				jQuery("span#pendingcount").empty().html(pendingMessage);
				jQuery("span#pending_subtotal").empty().html("$" + subTotal.toFixed(2));

				loadCart();
				loadSummary();
			} else {
				alert(definition);
			}
		} else {
			alert("There was an error. Please ensure you have checked all options before proceeding.");
		}

		jQuery("form#pendingForm input#add_" + key).removeAttr("disabled").css("cursor","pointer").animate({opacity:1},"fast");

		jQuery.ajaxSetup ({ cache: true });
	}, "json");
}

/* -------------------- */
/*   Delete Functions   */
/* -------------------- */

function deleteFromPending() {
	var link   = urlPrefix + "://" + CGI["http_host"] + "/store/remote/cart.cfm/mode/deletePending";
	var key    = jQuery(this).attr("data-key");
	var params = "json=1&key=" + key;

	jQuery(this).attr("disabled",true).css("cursor","default").animate({opacity:0.4},"fast");

	jQuery.ajaxSetup ({ cache: false });

	jQuery.post(link, params, function(json) {
		if(json.recordcount == 1) {
			var DoCommit     = json.data.docommit[0];
			var definition   = json.data.definition[0];
			var pendingCount = json.data.pendingcount[0];
			var subTotal     = json.data.subtotal[0];

			if(DoCommit == 1) {
				var pendingMessage = pendingCount + " item";
	
				if(pendingCount != 1) {
					pendingMessage += "s";
				}

				// Hide things accordingly.
				if(pendingCount == 0) {
					jQuery("#pendingLayer").fadeOut("fast",function() {
						jQuery("#pendingLayer").empty().html("");
					});
				} else {
					jQuery("#pendingitem_" + key).fadeOut("fast",function() {
						jQuery("#pendingitem_" + key).empty().html("");
					});
				}

				// Update any spans.
				jQuery("span#pendingcount").empty().html(pendingMessage);
				jQuery("span#pending_subtotal").empty().html("$" + subTotal.toFixed(2));
			} else {
				alert(definition);
			}
		} else {
			alert("There was an error removing this item from your pending purchases. The item has not actually been removed. Please refresh the page.");
		}

		jQuery.ajaxSetup ({ cache: true });
	}, "json");
}

function deleteFromCart() {
	var link   = urlPrefix + "://" + CGI["http_host"] + "/store/remote/cart.cfm/mode/deleteCart";
	var key    = jQuery(this).attr("data-key");
	var params = "json=1&key=" + key;

	jQuery(this).attr("disabled",true).css("cursor","default").animate({opacity:0.4},"fast");

	jQuery.ajaxSetup ({ cache: false });

	jQuery.post(link, params, function(json) {
		if(json.recordcount == 1) {
			var DoCommit   = json.data.docommit[0];
			var definition = json.data.definition[0];
			var cartCount  = json.data.cartcount[0];
			var subTotal   = json.data.subtotal[0];

			if(DoCommit == 1) {
				// Hide things accordingly.
				if(cartCount == 0) {
					jQuery("#cartLayer").empty().html("<DIV CLASS='body store_cart_definition' ALIGN='center'><B>There are currently no items in your cart.</B></DIV>");
				} else {
					jQuery("#cartitem_" + key).fadeOut("fast",function() {
						jQuery("#cartitem_" + key).empty().html("");
					});
				}

				loadSummary();

				// Update any spans.
				jQuery("span#cart_subtotal").empty().html("$" + subTotal.toFixed(2));
			} else {
				alert(definition);
			}
		} else {
			alert("There was an error removing this item from your pending purchases. The item has not actually been removed. Please refresh the page.");
		}

		jQuery.ajaxSetup ({ cache: true });
	}, "json");
}

/* --------------------------- */
/*   On Spin Event Functions   */
/* --------------------------- */

function pendingOnSpin(target) {
	var link   = urlPrefix + "://" + CGI["http_host"] + "/store/remote/cart.cfm/mode/updatePendingQty";
	var key    = jQuery(target).attr("data-key");
	var qty    = jQuery(target).val();
	var params = "json=1&key=" + key + "&qty=" + qty;

	jQuery.ajaxSetup ({ cache: false });

	jQuery.post(link, params, function(json) {
		if(json.recordcount == 1) {
			var DoCommit  = json.data.docommit[0];
			var itemTotal = json.data.itemtotal[0];
			var subTotal  = json.data.subtotal[0];

			if(DoCommit == 1) {
				// Update any spans.
				jQuery("span#itemtotal_" + key).empty().html("$" + itemTotal.toFixed(2));
				jQuery("span#pending_subtotal").empty().html("$" + subTotal.toFixed(2));
			} else {
				alert("There was an error updating the quantity of this item. The quantity has actually not changed. Please refresh the page.");
			}
		} else {
			alert("There was an error updating the quantity of this item. The quantity has actually not changed. Please refresh the page.");
		}

		jQuery.ajaxSetup ({ cache: true });
	}, "json");
}

function cartOnSpin(target) {
	var link   = urlPrefix + "://" + CGI["http_host"] + "/store/remote/cart.cfm/mode/updateCartQty";
	var key    = jQuery(target).attr("data-key");
	var qty    = parseInt(jQuery(target).val());
	var params = "json=1&key=" + key + "&qty=" + qty;

	jQuery.ajaxSetup ({ cache: false });

	jQuery.post(link, params, function(json) {
		if(json.recordcount == 1) {
			var DoCommit  = json.data.docommit[0];
			var itemTotal = json.data.itemtotal[0];
			var subTotal  = json.data.subtotal[0];

			if(DoCommit == 1) {
				loadSummary();

				// Update any spans.
				jQuery("span#itemtotal_" + key).empty().html("$" + itemTotal.toFixed(2));
				jQuery("span#cart_subtotal").empty().html("$" + subTotal.toFixed(2));
			} else {
				alert("There was an error updating the quantity of this item. The quantity has actually not changed. Please refresh the page.");
			}
		} else {
			alert("There was an error updating the quantity of this item. The quantity has actually not changed. Please refresh the page.");
		}

		jQuery.ajaxSetup ({ cache: true });
	}, "json");
}

/* -------------------------- */
/*   Content Load Functions   */
/* -------------------------- */

function loadCart() {
	var link   = urlPrefix + "://" + CGI["http_host"] + "/store/remote/cart.cfm/mode/loadCart?" + Math.round((new Date()).getTime() / 1000);
	var params = "ajax=1";

	if(jQuery("div#cartLayer").length == 0) return false;

	jQuery.ajaxSetup ({ cache: false });

	jQuery.get(link, params, function(results) {
		jQuery("div#cartLayer").empty().html(results);
		loadSpinners("cart");

		// Load jQuery Events
		jQuery("form#cartForm input[id^='remove_']").click(deleteFromCart);

		// Smooth Display
		jQuery("div#cartLayer").fadeIn("fast");

		jQuery.ajaxSetup ({ cache: true });
	}, "html");
}

function loadPending() {
	var link   = urlPrefix + "://" + CGI["http_host"] + "/store/remote/cart.cfm/mode/loadPending?" + Math.round((new Date()).getTime() / 1000);
	var params = "ajax=1";

	if(jQuery("div#pendingLayer").length == 0) return false;

	jQuery.ajaxSetup ({ cache: false });

	jQuery.get(link, params, function(results) {
		jQuery("div#pendingLayer").empty().html(results);
		loadSpinners("pending");

		// Load jQuery Events
		jQuery("form#pendingForm input[id^='remove_']").click(deleteFromPending);
		jQuery("form#pendingForm input[id^='add_']").click(addToCart);

		// Smooth Display
		jQuery("div#pendingLayer").fadeIn("fast");

		jQuery.ajaxSetup ({ cache: true });
	}, "html");
}

function loadSummary() {
	var link   = urlPrefix + "://" + CGI["http_host"] + "/store/remote/cart.cfm/mode/loadSummary";
	var params = "ajax=1";

	if(jQuery("div#cartSummaryLayer").length == 0) return false;

	jQuery.ajaxSetup ({ cache: false });

	jQuery.post(link, params, function(results) {
		jQuery("div#cartSummaryLayer").empty().html(results);
		jQuery.ajaxSetup ({ cache: true });
	}, "html");
}

function loadSpinners() {
	var type = (arguments.length > 0) ? arguments[0] : "both";
	if(type == "both" || type == "cart") jQuery("form#cartForm input[id^='cartqty_']").spinner({step:1,min:1,delay:500,mousewheel:'false',onChange:cartOnSpin});
	if(type == "both" || type == "pending") jQuery("form#pendingForm input[id^='cartqty_']").spinner({step:1,min:1,delay:500,mousewheel:'false',onChange:pendingOnSpin});
}

/* ------------------------- */
/*   jQuery Load Functions   */
/* ------------------------- */

jQuery(document).ready(function(){
	loadPending();
	loadCart();
	loadSummary();

	jQuery("div#calculatorLayer").fadeIn();
});
