/*****************************************
	MIGHTY LEAF Product Detail Script
	Author: James Van Arsdale III
	Created: 11/7/08
	* 
	* Modified for FreshFinds
	* JLP 2/25/09
*****************************************/
var frmOptions = {
	url: "/index.cfm",
	type: "post",
	dataType: "html",
	resetForm: false,
	timeout: 100000,
	beforeSubmit: validateOrder,
	success: showResponse,
	error: function(XMLHttpRequest, textStatus, errorThrown)
	{
		hideLoading();
		alert("Error1\nAn error occurred and we couldn't add your items, please try again or contact us for further assistance.");
	}
};

jQuery(document).ready(function() {
	
	jQuery(".vProduct-detailPageTemplate-productContainer .vProduct-productForm-container form .vProduct-productForm-controlsContainer input[type=image]").click(function(event) {
		jQuery(".vProduct-detailPageTemplate-productContainer .vProduct-productForm-container form").ajaxSubmit(frmOptions);
		event.preventDefault();		
		return false;
	 });
	
	jQuery(".vProduct-detailPageTemplate-productContainer .vProduct-packageProductsForm-container form .vProduct-packageProductsForm-controlsContainer input[type=image]").click(function(event) {
		jQuery(".vProduct-detailPageTemplate-productContainer .vProduct-packageProductsForm-container form").ajaxSubmit(frmOptions);
		event.preventDefault();
		return false;
	 });
	 
	 
	// dynamic "as selected" pricing
	if (jQuery(".vProduct-productOptionsFields-container select").length) {
		
		// enable the dynamic pricing and options
		jQuery(".vProduct-productOptionsFields-container .vProduct-productOptionsFields-options-reset-container").show();
		jQuery(".vProduct-productOptionsFields-price-container").show();
		
		// attach onClick handler for reset link
		jQuery(".vProduct-productOptionsFields-container .vProduct-productOptionsFields-options-reset-container #options-reset").click(function() {
			resetProductOptions();
		}); 
		
		// attach onClick handler for selects
		jQuery(".vProduct-productOptionsFields-container select").each(function() {
			jQuery(this).change(function() {
				// pull up the current product ID and prepare the queryString
				var currProductID = jQuery("input[name='productID']").attr('value');
				var queryString = 'fuseaction=product.ajaxOptionsGetAvailableWithPricing&productID=' + currProductID;

				var pricingProductOptionIDs = new Array();		// option id list for ajax pricing request
				
				// add the updated option id as first value in ajax pricing request
				var updatedOptionID = jQuery(this).attr('value');

				if(updatedOptionID.length == 0 ) {
					pricingProductOptionIDs.push(-1);
				}
				else {
					pricingProductOptionIDs.push(updatedOptionID);
				}

				// disable all the option selects to prevent simultaneous requests
				jQuery(".vProduct-productOptionsFields-container select").attr("disabled","disabled");
				
				// collect all selected options for ajax pricing and form submission
				jQuery(".vProduct-productOptionsFields-container select option:selected").each(function() {
					var selectedOptionID = jQuery(this).attr('value');

					// update id list for ajax pricing request
					if(selectedOptionID.length == 0 ) {
						pricingProductOptionIDs.push(-1);
					}
					else {
						pricingProductOptionIDs.push(selectedOptionID);
					}
				});
	
				// set the selected option
				if (updatedOptionID != -1) {
					jQuery(this).next("input[name^='selectedOption_']").val(updatedOptionID);
				}
				
				queryString += '&productOptionIDs=' + pricingProductOptionIDs.toString();

				ajaxGetOptionsAndPricing(queryString, false);
			})
		});
	}	 
});

function resetProductOptions () {
	if (jQuery(".vProduct-productOptionsFields-container select").length) {

		jQuery("input[name^='selectedOption_']").each(function() {
			jQuery(this).val('')
		});
		
		var currProductID = jQuery("input[name='productID']").attr('value');
		var queryString = 'fuseaction=product.ajaxOptionsGetAvailableWithPricing&productID=' + currProductID + '&reset=1&productOptionIDs=-1,-1,-1';
		
		ajaxGetOptionsAndPricing(queryString, true);		
	}
}


function ajaxGetOptionsAndPricing (queryString, isReset) {
	
	// submit ajax call to get updated data
	jQuery.ajax({url: '/index.cfm', 
				 data: queryString, 
				 dataType: 'json',
				 error: function() {
				 	jQuery('.vProduct-productOptionsFields-container select').attr('disabled','');
				 },
				 success: function(data) {
					try {
						// set pricing display	
						jQuery(".vProduct-productOptionsFields-price-container .price #priceDisplay").html(data.PRICETODISPLAY);

						// show selected SKU
						if (data.AVAILABLEOPTIONSADDITIONALSHIPPING.recordcount == 1) {
							jQuery(".vProduct-detailInfo-productid-container #selected-product-sku").html(' / ' + data.SELECTEDSKU);
							jQuery(".vProduct-detailInfo-productid-container #selected-product-sku").show();
						}
						else {
							jQuery(".vProduct-detailInfo-productid-container #selected-product-sku").html('');
							jQuery(".vProduct-detailInfo-productid-container #selected-product-sku").hide();
						}						
						
						// show additional shipping for selected SKU if there is any
						if (data.ADDITIONALSHIPPINGCHARGE.length > 0) {
							jQuery(".vProduct-productOptionsFields-price-container .price #additionalShippingDisplay").html('<br />(+ ' + data.ADDITIONALSHIPPINGCHARGE + ' additional shipping)');
							jQuery(".vProduct-productOptionsFields-price-container .price #additionalShippingDisplay").show();
						}
						else {
							jQuery(".vProduct-productOptionsFields-price-container .price #additionalShippingDisplay").html('');
							jQuery(".vProduct-productOptionsFields-price-container .price #additionalShippingDisplay").hide();
						}
						
						// update options fields
						if (jQuery(".vProduct-productOptionsFields-container select").length > 1 || data.RESETRESULT) {
							var lastOptionType = '';
							
							for (i = 0; i < data.AVAILABLEOPTIONS.data.optionid.length; i++) {
							
								if (lastOptionType != data.AVAILABLEOPTIONS.data.optiontype[i]) {
									currentSelectID = jQuery("option[name='" + data.AVAILABLEOPTIONS.data.optiontype[i] + "']").parent().attr('id');
									currentSelectedOption = jQuery('#' + currentSelectID + ' option:selected').attr('value');
									jQuery("option[name='" + data.AVAILABLEOPTIONS.data.optiontype[i] + "']").remove();
									lastOptionType = data.AVAILABLEOPTIONS.data.optiontype[i]
								}
								
								
								if (!isReset && data.AVAILABLEOPTIONS.data.optionid[i] == currentSelectedOption) {
									selected = 'selected';
								}
								else {
									selected = '';
								}
								
								jQuery('#' + currentSelectID).append('<option name="' + data.AVAILABLEOPTIONS.data.optiontype[i] + '" value="' + data.AVAILABLEOPTIONS.data.optionid[i] + '" ' + selected + '>' + data.AVAILABLEOPTIONS.data.optionaliasname[i] + '</option>');
							}
						}	
					} catch (err) {}
							
					jQuery('.vProduct-productOptionsFields-container select').attr('disabled','');
				}
							
			});		
}



// pre-submit callback 
function validateOrder(formData, jqForm, options) { 
	// formData is an array; here we use $.param to convert it to a string to display it 
	// but the form plugin does this for you automatically when it submits the data 
	var queryString = jQuery.param(formData); 
	var orderTotal = 0;
	var orderIsValid = true;
		
	if (jQuery(".vProduct-productForm-container .vProduct-productOptionsFields-container select").length) {

		jQuery(".vProduct-productForm-container .vProduct-productOptionsFields-container select option:selected").each(function() {

			var selectedOptionID = jQuery(this).val();

			if(selectedOptionID.length == 0 ) {			
				orderIsValid = false; 			
			}
		});	
	}
	
	if ( jQuery(".vProduct-detailPageTemplate-productContainer .vProduct-productForm-container form input[name=quantity]").length ) {
		orderTotal = jQuery(".vProduct-detailPageTemplate-productContainer .vProduct-productForm-container form input[name=quantity]").val();
	}
	else {
		var itemCount = jQuery(".vProduct-detailPageTemplate-productContainer .vProduct-packageProductsForm-container form .vProduct-packageProductsForm-productControlsQuantityContainer input").length;
		jQuery(".vProduct-detailPageTemplate-productContainer .vProduct-packageProductsForm-container form .vProduct-packageProductsForm-productControlsQuantityContainer input").each(function(){
			orderTotal = orderTotal + parseInt($(this).val(),10);
		});
	}
	
	if( orderIsValid && orderTotal > 0 )
	{
		showLoading();
		return true;
	}
	else
	{
		// this is for IE not being able to resubmit the form after the first ajax submit, unless you reselect a product in the drop down menu
		alert("Please Select A Product\nPlease select a product and quantity to add it to your Shopping Cart.");
		return false;
	}
	

} 
 
// post-submit callback 
function showResponse(responseTxt, statusText)  { 
	//alert('status: ' + statusText + '\n\nresponseText:' + responseTxt);	
	
	// get cart details.
	$.ajax({
		async: false, // set to false for testing
		url: "/index.cfm/fuseaction/cart.ajaxCartSummary",
		dataType: "html",
		cache: false,
		complete: function(XMLHttpRequest, textStatus)
		{	
			//alert('status: ' + textStatus + '\n\nresponseText:' + XMLHttpRequest.responseText);
			if ( textStatus == 'success' )
			{
				// remove old items from drop down
				jQuery("#cart-container ul li.cart-item ul li.cart-message").remove();
				jQuery("#cart-container ul li.cart-item ul li.cart-prod").remove();
				
				// if there are no items in the cart, create the nested UL
				if( jQuery("#cart-container ul li.cart-item:has(ul)").length < 1 )
				{
					jQuery("#cart-container ul li.cart-item").append("<ul><li class=\"actions\"><a href=\"/index.cfm/fuseaction/cart.view\" class=\"bag\">View My Cart</a> <a href=\"/index.cfm/fuseaction/checkout.start\" class=\"checkout-link\">Checkout</a></li></ul>");
					// reinit the cart drop down now that there's a nested UL
					/*$("#cart-container ul li.cart-item:has(ul)").mouseover(function() {
						$("select").css("visibility","hidden");
						$(this).addClass("modal");
					});
					$("#cart-container ul li.cart-item:has(ul)").mouseout(function() {
						$("select").css("visibility","visible");
						$(this).removeClass("modal");
						jQuery("#cart-container ul li.cart-item ul").css("top","");
						jQuery("#cart-container ul li.cart-item ul").css("left","");
						
					});*/
					
				}

				// add newly returned items
				jQuery("#cart-container ul li.cart-item ul li.actions").before(XMLHttpRequest.responseText);
				jQuery("#cart-container ul li.cart-item ul li.cart-message").append("<h2>Your Items have been added to your Shopping Cart</h2>");
				jQuery("#cart-container ul li.cart-item ul li.cart-message").append(jQuery("#cart-container ul li.cart-item ul li.actions").html());
				//jQuery("#cart-container ul li.cart-item ul li.cart-message .scanalert").remove();
				jQuery("#modalCartCloseBtn").remove();
				
				
				// update the item count in the util nav
				jQuery("#cart-container ul li.cart-item a.cart-link").html("<span>Shopping Cart</span>"+jQuery("#cart-container ul li.cart-item ul li.cart-message input.cart-count").val()+" item");
			
				hideLoading();
				
				resetProductOptions();				
				
				// scroll to top and trigger the over state
				//jQuery(document).scrollTo("#util-navigation",500);
				
				jQuery("body").append('<div id="modalOverlay" class="overlay"/>');
				jQuery("#modalOverlay").css("height",jQuery(document).height()+"px");
				jQuery("#modalOverlay").css("width",jQuery(document).width()+"px");
				jQuery("#modalOverlay").fadeTo("fast", 0.8);
				//if(jQuery("#cart-container ul li.cart-item ul li.actions-row2").length < 1){
				//	jQuery("#cart-container ul li.cart-item ul").append('<li class="actions-row2"><a class="scanalertLogo" target="_blank" href="https://www.scanalert.com/RatingVerify?ref=www.harrietcarter.com"><img width="65" height="37" border="0" src="//images.scanalert.com/meter/www.harrietcarter.com/31.gif" alt="HACKER SAFE certified sites prevent over 99.9% of hacker crime." oncontextmenu="alert(\'Copying Prohibited by Law - HACKER SAFE is a Trademark of ScanAlert\'); return false;" /></a></li>');
				//}
				jQuery("#cart-container ul li.cart-item ul").append('<li class="actions-row2"><span id="modalCartCloseBtn">Close</span></li>');
				jQuery("#modalCartCloseBtn").click(function(){
					jQuery("select").css("visibility","visible");
					jQuery("#cart-container ul li.cart-item").removeClass("modal").removeClass("over");
					jQuery("#cart-container ul li.cart-item ul").css("top","");
					jQuery("#cart-container ul li.cart-item ul").css("left","");
					//jQuery("#modalCartCloseBtn").remove();
					jQuery("#modalOverlay").remove();
					jQuery("#cart-container ul li.cart-item ul li.cart-message h2").remove();
					jQuery("#cart-container ul li.cart-item ul li.cart-message a").remove();
				});
				
				jQuery("#cart-container ul li.cart-item").addClass("modal");
				
				var modalCartHeight = jQuery("#cart-container ul li.modal ul").height();
				var modalCartWidth = jQuery("#cart-container ul li.modal ul").width();
				jQuery("#cart-container ul li.modal ul").css("top", 50);
				jQuery("#cart-container ul li.modal ul").css("left", f_scrollLeft()+(f_clientWidth()/2) - (modalCartWidth/2));
				
				
				//var temp = setTimeout('jQuery("#cart-container ul li.cart-item").removeClass("modal").removeClass("over");jQuery("#modalOverlay").remove();', 6000);
			}
			else
			{
				hideLoading();
				alert("Error2\nWe were unable to update the Shopping Cart summary, refresh the page or visit your Shopping Cart to see your items added.");
			}
		},
		error: function()
		{
			alert("Error3\nWe were unable to update the Shopping Cart summary, refresh the page or visit your Shopping Cart to see your items added.");
		}
	});
} 

function showLoading()
{
	jQuery("body").append("<div id=\"ordersave-loading\" class=\"overlay\" style=\"display: none;\"><div class=\"loading\"><h2>Adding Items to your Shopping Cart</h2></div></div>");
	jQuery("#ordersave-loading").css("height",jQuery(document).height()+"px");
	jQuery("#ordersave-loading").css("width",jQuery(document).width()+"px");
	jQuery("#ordersave-loading").fadeTo("fast", 0.8);
	jQuery("#ordersave-loading").fadeTo("fast", 0, function() { jQuery("#ordersave-loading").css("display","block"); });
	jQuery("#ordersave-loading").fadeTo("slow", 0.9);
	jQuery(document).scrollTo("#header-container",500);
}

function hideLoading()
{
	jQuery("#ordersave-loading").remove();
}	


