// Blink an item
function blinkClass (inputid,inputclass) {
	$(inputid).addClass(inputclass);
	timeoutstr = "$(\"" + inputid + "\").removeClass(\"" + inputclass + "\")";
	setTimeout(timeoutstr,500);
};

// Remove dollar sign and comma
function filterNum(str) {
	re = /^\$|,/g;
	return str.replace(re, "");
}

// Add commas to a number
function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function recommendProducts() {
		$.ajax({
   			type: "GET",
			cache: false,
   			url: "/ecom/ajax_calculate_shipping_savings.php",
			data: "servicecode=03",
   			success: function(resulthtml){
				if (resulthtml != "") {
					$("#ShippingSavingsContainer").html(resulthtml).slideDown(300,function(){
																		
																		
						/*$(".ProductCategoryThumb").hover(function(){
		thisimage = $(this).attr("src");
		newimage = thisimage.replace(/thumb/i,"sized");
		
		$("#CategoryImageHover").image(newimage,function(){
		
		$("#CategoryImageHover").fadeIn(300);
		
						
		});

		
		
	}, function(){
		
		$("#CategoryImageHover").html("").hide();	
	});						*/
																		
																		
																						   
						$("#RecommendMoreProducts").click(function(event){
							event.preventDefault();
							$("#RecommendMoreProducts").unbind();
							
							recommendProducts();
							
						});
					});
				}
				
   			}
 		});
}

// Calculate the cart total
function calculateCartTotal(blinkresult) {
		
		// Selected UPS text value
		thisval = $("#UPSShippingOption option:selected").text();
		
		// Calculat shipping savings
		if ($("#UPSShippingOption option:selected").val() == "03") {
			//$("#ShippingSavingsContainer").html("<div class=\"CalculatingSavings\">Calculating shipping savings...</div>").slideDown(300);
			
			recommendProducts();
			
			
		} else {
			$("#ShippingSavingsContainer").slideUp(300);	
		}
		
		if (thisval != "") {
			
			// Selected UPS option value
			thisselection = $("#UPSShippingOption option:selected").val();
			
			// Set cookie so we know what option they selected later on
			$.cookie('RetailShippingOption', thisselection, { expires: 7 });
			
			// Calculate total and blink the results
			
			// Get rid of the excess junk
			x = thisval.split('-');
			thisnum = x[0].replace(/^\s+|\s+$/g, '') ;
			thisnum = filterNum(thisnum);
			
			productsubtotal = filterNum($("#ProductSubTotal").val());
			newtotal = (parseFloat(thisnum) + parseFloat(productsubtotal));
			newtotal = addCommas(newtotal.toFixed(2));
	
			if (newtotal == "NaN") {
				$("#GrandTotal").html("An error occured");
			} else {
				$("#GrandTotal").html("$" + newtotal);
			}
		
			if (blinkresult == "Y") {
				blinkClass("#GrandTotal","TempHilight");	
			}
						
		} else {
			// No UPS option present, display product subtotal only
			productsubtotal = filterNum($("#ProductSubTotal").val());	
			$("#GrandTotal").html("$" + productsubtotal);
		}
			
		

}

function setCartUPSRates(resulthtml,blinkresult) {
	
	// Set the rates in the DOM
	$("#CartShippingOptions").html(resulthtml).removeClass("Loader");
	
	// Recalculate the cost
	calculateCartTotal(blinkresult);
	
	// Blink results
	if (blinkresult == "Y") {
		blinkClass("#CartShippingOptionsContainer","TempHilight");
		blinkClass("#GrandTotal","TempHilight");
		blinkClass("#CartShippingOptions","TempHilight");		
	}
	
	// Set change event to monitor the users selection
	$("#CartShippingOptions select").change(function() {
		calculateCartTotal("Y");
	});
}

$.fn.image = function(src, f){ 
   return this.each(function(){ 
     var i = new Image(); 
     i.src = src; 
     i.onload = f; 
     this.appendChild(i);
   }); 
} 

$(document).ready(function(){
						   
		/* The new sort by function. When user selects an option, automatically submit */
		$("#sortbyform select").change(function(){
			$("#sortby").submit();									
		});
						   
		$.ajax({
   			type: "GET",
			cache: false,
   			url: "/ecom/ajax_cart_quantity.php",
   			success: function(resulthtml){
				$("#shopping_cart_link").html(resulthtml);
   			}
 		});

		window_height = $(document).height();
		window_width = $(window).width();
		
		viewable_height = $(window).height();
		
		$(window).resize(function(){
			window_height = $(document).height();
			window_width = $(window).width();
		});

		$().mousemove(function(e){
						   
			element_height = $("#CategoryImageHover").height();
			element_width = $("#CategoryImageHover").width();
			
			if ((e.pageY + element_height + 10) > window_height) {
				top_px = e.pageY - element_height - 10 + "px";
			} else {
				top_px = e.pageY + 10 + "px";
			}
			
			if ((e.pageX + element_width + 10) > window_width) {
				left_px =  e.pageX - element_width - 10 + "px";
			} else {
				left_px =  e.pageX + 10 + "px";
			}
					var cssObj = {
        	'top' : top_px,
        	'left' : left_px
      		}	   
      		//$('#status').html(e.pageX +', '+ e.pageY);
			
			
			$("#CategoryImageHover").css(cssObj);
   		});

	$(".ProductCategoryThumb").hover(function(){
		thisimage = $(this).attr("src");
		newimage = thisimage.replace(/thumb/i,"sized_hover");
		
		$("#CategoryImageHover").image(newimage,function(){
		
		$("#CategoryImageHover").fadeIn(300);
		
						
		});

		
		
	}, function(){
		
		$("#CategoryImageHover").html("").hide();	
	});
		   
  $("#processOrderButton").click(function(){
		alert("Please be patient as your order processes. Click OK to continue.");
		
	});

  // If they are on the cart page
  if ($("#CartSetZip").length) {
	  
	  $("#CartSetZip #ShipToZip").focus();
	  
	  	// Update with previous selection
		$.ajax({
   			type: "GET",
			cache: false,
   			url: "/ecom/ajax_get_cart_ups.php",
   			//data: "ShipToZip=" + thiszip,
   			success: function(resulthtml){
				
				setCartUPSRates(resulthtml,"N");
   			}
 		});
		
	// When the user enters/changes their zip, catch it and do some AJAX calculations
  	$("#CartSetZip").submit(function(event) {
		event.preventDefault();
		thiszip = $("#ShipToZip").val();
		
		// Let them know somethings happening
		//$("#CartShippingOptions").html("Getting rates for " + thiszip);
		$("#CartShippingOptions").html("").addClass("Loader");
		$("#ShippingSavingsContainer").slideUp(300);
		// Get rates
		$.ajax({
   			type: "GET",
			cache: false,
   			url: "/ecom/ajax_get_cart_ups.php",
   			data: "ShipToZip=" + thiszip,
   			success: function(resulthtml){
				setCartUPSRates(resulthtml,"Y");
   			}
 		});
	});
	
	
  }
  
  // User is on checkout page
  if ($("#ShippingOption").length) {
	  ($("#createAccount").is(":checked") ? $("#CreateAccountForm").slideDown() : $("#CreateAccountForm").slideUp());
	  $("#createAccount").click(function() {
			($(this).is(":checked") ? $("#CreateAccountForm").slideDown() : $("#CreateAccountForm").slideUp());
		});
	  
	  checkoutBillShipSame();
	  checkoutCalculateUPS();
	  
	  $("#ShippingOption").html("Enter your shipping information above");
	  
	  $("#shippingZip").change(function () {
			checkoutCalculateUPS();
		});
	  $("#billingZip").change(function () {
			checkoutCalculateUPS();
		});
	  
	  $("#BillShipSame").click(function () {
			checkoutBillShipSame();
			checkoutCalculateUPS();
		});
	  
	  // Checkout form validation
	  
	  

	var validator = $("#CheckoutForm").validate({
		rules: {
			billingFirstName: "required",
			billingLastName: "required",
			billingAddress: "required",
			billingCity: "required",
			billingState: "required",
			billingZip: {
				required: true,
				minlength: 5
			},
			billingPhone: {
				required: true,
				minlength: 10
			},
			email: {
				required: true,
				email: true
			},
			emailConfirm: {
				required: true,
				equalTo: "#email"
			},
			password: {
				required: "#createAccount:checked",
				minlength: 5
			},
			confirmPassword: {
				required: "#createAccount:checked",
				equalTo: "#password"	
			},
			
			shippingFirstName: {
				required: "#BillShipSame:unchecked"
			},
			shippingLastName: {
				required: "#BillShipSame:unchecked"
			},
			shippingAddress: {
				required: "#BillShipSame:unchecked"
			},
			shippingCity: {
				required: "#BillShipSame:unchecked"
			},
			shippingState: {
				required: "#BillShipSame:unchecked"
			},
			shippingZip: {
				required: "#BillShipSame:unchecked",
				minlength: 5
			},
			shippingPhone: {
				required: "#BillShipSame:unchecked",
				minlength: 10
			},
			
			cc: {
				required: true,
				minlength: 15
			},
			ccExpirationMonth: {
				required: true	
			},
			ccExpirationYear: {
				required: true	
			}
			
		},
		messages: {
			billingFirstName: "Please enter your first name",
			billingLastName: "Please enter your last name",
			billingAddress: "Please enter your address",
			billingCity: "Please enter your city",
			billingState: "Please enter your state",
			billingZip: {
				required: "Please enter your 5 digits zip code",
				minlength: "Please enter your 5 digits zip code"
			}, 
			billingPhone: {
				required: "Please enter your phone, including area code",
				minlength: "Please enter your phone, including area code"
			},
			email: {
				email: "Enter a valid email address",
				required: "Enter a valid email address"
			},
			emailConfirm: {
				required: "Please re-enter your email address",
				equalTo: "Your email address does not match"
			},
			password: {
				required: "Please choose an account password",
				minlength: "Password is too short. Must be atleast 5 characters"
			},
			confirmPassword: {
				required: "Please retype your password",
				equalTo: "Passwords do not match"	
			},
			
			shippingFirstName: "Please enter your first name",
			shippingLastName: "Please enter your last name",
			shippingAddress: "Please enter your address",
			shippingCity: "Please enter your city",
			shippingState: "Please enter your state",
			shippingZip: {
				required: "Please enter your 5 digits zip code",
				minlength: "Please enter your 5 digits zip code"
			},
			shippingPhone: {
				required: "Please enter your phone, including area code",
				minlength: "Please enter your phone, including area code"
			},
			cc: "Please enter a valid 15-16 digit CC #",
			ccExpirationMonth: "Please select your credit card expiration month",
			ccExpirationYear: "Please select your credit card expiration year"
			
			
		},
		errorPlacement: function(error, element) {
			if ( element.is(":radio") )
				error.appendTo( element.parent().next() );
				
			else if ( element.is(":checkbox") )
				error.appendTo ( element.parent().next() );
			else
				error.appendTo( element.parent().add() );
		},
		errorElement: "div"

	});
	  
	  
	  
	  
	  
  }
  
  
  $(".additional_images a").click(function(event){
	event.preventDefault();									   
	});
  $(".additional_images img").click(function(){
											 
		thisimg = $(this).attr("src");
		result = thisimg.match(/\/ecom\/img-u\/thumb\/(.*?.jpg)/);
		
		$("#main_product_image").attr("src",result[0]);
	});
  
  
  
  
});

function checkoutCalculateUPS() {
	// Determine if we are using the billing or shipping zip code
	thiszip = ($("#BillShipSame").is(":checked") ? $("#billingZip").val() : $("#shippingZip").val());
	
	// Selected UPS option value
	thisselection = $("#UPSShippingOption option:selected").val();
	
	if (thisselection != "") {
		// Set cookie so we know what option they selected later on
		$.cookie('RetailShippingOption', thisselection, { expires: 7 });
	}
	
	$("#ShippingOption").html("").addClass("Loader");
	
	$.ajax({
   			type: "GET",
			cache: false,
   			url: "/ecom/ajax_get_checkout_ups.php",
   			data: "ShipToZip=" + thiszip,
   			success: function(resulthtml){
				
				$("#ShippingOption").html(resulthtml).removeClass("Loader");
   			}
 		});
	
	
	
	
}
function checkoutBillShipSame() {
	($("#BillShipSame").is(":checked") ? $("#shipping_input").slideUp() : $("#shipping_input").slideDown());
}
