
function updateCartTotals(){
	// if the cart info div is there, we want to get the item count and dollar amount
	if ($('#cart-info').length > 0) {
  		$.getJSON('/index.cfm/do/ajax.QuickCartInfo', function(data) {
				$('#order-itemcount').html(data.itemCount);
				$('#order-cart-subtotal').html(data.cartSubtotal);
			});
  }	
}

$(document).ready(function() {

	/* Start the save lists */
		$(".save-list-btn").colorbox({
			transition : "none",
			overlayClose : false,
			//Width : 500,
			//maxWidth : 500,
			//Height : 300,
			//maxHeight : 300,		
			href : "index.cfm/do/site.savelist",
			//onOpen:function(){ alert('onOpen: colorbox is about to open'); },
			//onLoad:function(){ alert('onLoad: colorbox has started to load the targeted content'); },
			onComplete:function(){
				$("#save-list-login-form").find('input[name="returnTo"]').val($(".save-list-btn").attr('ref'));
			}
			//onCleanup:function(){ alert('onCleanup: colorbox has begun the close process'); },
			//onClosed:function(){ alert('onClosed: colorbox has completely closed'); }
		});
		// this will handle automatically loading the save list dialog...
		if($('.load-save-list').length > 0){
			$(".save-list-btn").click();
		}
			
		$('#save-list-close').live("click", function(e){
			e.preventDefault();
			$.colorbox.close();
		});
		
		$('#save-lists-dialog-save').live("click", function(e){
			e.preventDefault();
			var $form = $('.add-to-cart');
			var $addType = $form.find("input[name='addType']");
			var $orderTitle = $form.find("input[name='orderTitle']");
			var $orderID = $form.find("input[name='orderID']");
			
			var $newListName = $('input[name="CreateNewSaveList"]').val();
			var $attachToSaveList = $('select[name="AttachToSaveList"]').val();
			
			if($newListName.length > 0){

				$addType.val('savelist');
				$orderTitle.val($newListName);
				$orderID.val(0);
			}else if ($attachToSaveList.length > 0){
				$addType.val('savelist');
				$orderTitle.val('');
				$orderID.val($attachToSaveList);
			} else{
				console.log('error!')
			}
			
			// flip the action of the add-to-cart form to the add to savelist.
			var formPostLocation = $('.add-to-cart').attr('action');
			
			
			$('.add-to-cart').attr('action', "index.cfm/do/cart.addToSaveList");
			$('.add-to-cart').submit();
			
			// now that the form was submitted, flip the action back.
			$('.add-to-cart').attr('action', formPostLocation);
			$orderTitle.val('');
			$orderID.val(0);		
		});
	/*End the save lists*/
	
	$('#quick-cart-close').live("click", function(e){
		e.preventDefault();
		$("#quick-cart-container").css('z-index', '-9999');
		$("#quick-cart-container").animate({"left": "-=200px"}, "fast");
	});
	
	/* START: THE ADD TO CART FUNCTION */
	// bind form using 'ajaxForm' 
	// make sure add to cart is a valid object on the page...	
	if($('.add-to-cart').length > 0){
		$('.add-to-cart').ajaxForm({dataType: 'json',
									resetForm: true,
									beforeSubmit: validateCartAdd,
									success: function(json, statusText, xhr, $form){
										$('.add-button').show();
										$('.add-button-processing').hide();
										
										if(json.resultBehavor == 'show-preview'){
											
											$('#order-itemcount').html(json.itemCount);
											$('#order-cart-subtotal').html(json.subTotal);										
										
											
											if($('#cart-preview-container').length == 0){
												$('#bgwrap').prepend('<div id="cart-added-container">'  + json.addedHtml + '</div>');
												
												$.blockUI({message:null, overlayCSS:{opacity:0.7, cursor:'arrow'}, css:{cursor:'arrow'}});
													$("#cart-added-container").animate({"top": "+=690px"}, "medium");
													$('.cart-added-close').click(function(e){
														e.preventDefault();	
														$("#cart-added-container").animate({"top": "-=690px"}, "fast");
														$.unblockUI(); 
													});
											}
											
										}else if(json.resultBehavor == 'show-cart'){
											window.location = '/cart/'
										}else if(json.resultBehavor == 'update-save-list-dialog'){
											$("#cboxLoadedContent").html(json.addedHtml);
										}
											
										$('#cart-box').unblock(); 	
									}
		}); 
	}
	/* END: THE ADD TO CART FUNCTION */
	
	//Initialize the variations
	initVariations();
	
		
	// init colorbox for all modal links
	$('a[rel="modal-set"], a[rel="image-zoom"]').colorbox();
	$('a[rel="modal"]').colorbox({ rel: 'nofollow' });
	$('a[rel="modal-frame"]').colorbox({ iframe: true });
	
	
	
	/************* ATTACH THE IMAGE ZOOM TO ALL THE CORRECT CLASSES *****************/
	//	$('.image-zoom').fancyZoom({scaleImg: true, closeOnClick: true, directory: '/skins/default/assets/images/fancyzoom'});
	
	// make sure the product-img-wrap is on the page
	if($("#prod-img-wrap").length > 0)
		$("#prod-img-wrap dl a, #prod-img-wrap li a").lightBox({
			imageBtnClose: "/skins/default/assets/images/lightbox-btn-close.gif",
			imageBtnPrev: "/skins/default/assets/images/lightbox-btn-prev.gif",
			imageBtnNext: "/skins/default/assets/images/lightbox-btn-next.gif",
			imageBlank: "/skins/default/assets/images/lightbox-blank.gif"
		});
	
	// when the page first loads, we need to update the shipping data...
	updateShippingData();

	// now listen for changes...
	$('#shipping_City').blur(function(){
		updateShippingData();
	});
	$('#shipping_State').blur(function(){
		updateShippingData();
	});
	$('#shipping_PostalCode').blur(function(){
		updateShippingData();
	});

	$('#shipping_Country').change(function(){
		updateShippingData();
	});



	$('.customer-shipping-address').click(function(e){
		e.preventDefault();
	 $('#shipping_Company').val($(this).find('.address_Company').html());
	 $('#shipping_FirstName').val($(this).find('.address_FirstName').html());
	 $('#shipping_LastName').val($(this).find('.address_LastName').html());
	 $('#shipping_Address1').val($(this).find('.address_Address1').html());
	 $('#shipping_Address2').val($(this).find('.address_Address2').html());
	 $('#shipping_City').val($(this).find('.address_City').html());
	 $('#shipping_State').val($(this).find('.address_State').html());
	 $('#shipping_PostalCode').val($(this).find('.address_PostalCode').html());
	 $('#shipping_Country').val($(this).find('.address_Country').html());
	 $('#shipping_Phone').val($(this).find('.address_Phone').html());
	 $("#shipping_AddressCopied").show().animate({opacity: 1.0}, 3000).fadeOut(1000);
	 $('html, body').animate({scrollTop:0}, 'fast');
	 // run the shipping update to make sure the up-to-date rates are loaded...
	 updateShippingData();
	});
	
	$('.customer-account-address').click(function(e){
	 e.preventDefault();
	 $('#account_Company').val($(this).find('.address_Company').html());
	 $('#account_FirstName').val($(this).find('.address_FirstName').html());
	 $('#account_LastName').val($(this).find('.address_LastName').html());
	 $('#account_Address1').val($(this).find('.address_Address1').html());
	 $('#account_Address2').val($(this).find('.address_Address2').html());
	 $('#account_City').val($(this).find('.address_City').html());
	 $('#account_State').val($(this).find('.address_State').html());
	 $('#account_PostalCode').val($(this).find('.address_PostalCode').html());
	 $('#account_Country').val($(this).find('.address_Country').html());
	 $('#account_Phone').val($(this).find('.address_Phone').html());
	 $("#account_AddressCopied").show().animate({opacity: 1.0}, 3000).fadeOut(1000);
	 $('html, body').animate({scrollTop:0}, 'fast');
	});	
	
	$('#copy-payment-address-to-cc').click(function(e){
	 e.preventDefault();
	 $('#payment_cc_Name').val($('#account_FirstName').val() + ' ' + $('#account_LastName').val());
	 $('#payment_cc_Company').val($('#account_Company').val());
	 $('#payment_cc_Address').val($('#account_Address1').val() + ' ' + $('#account_Address2').val());
	 $('#payment_cc_City').val($('#account_City').val());
	 $('#payment_cc_State').val($('#account_State').val());
	 $('#payment_cc_PostalCode').val($('#account_PostalCode').val());
	 $('#payment_cc_Country').val($('#account_Country').val());
	});	
	
	$('#copy-payment-info-to-ccp').click(function(e){
	 e.preventDefault();
	 $('#payment_ccp_Name').val($('#account_FirstName').val() + ' ' + $('#account_LastName').val());
	 $('#payment_ccp_ContactPhone').val($('#account_Phone').val());
	});	
	$('#copy-payment-info-to-po').click(function(e){
	 e.preventDefault();
	 $('#payment_po_Name').val($('#account_FirstName').val() + ' ' + $('#account_LastName').val());
	 $('#payment_po_ContactPhone').val($('#account_Phone').val());
	});

	
	
	
	
	$('input[name="payment_PaymentMethodID"]').change(function(){
		// find the new active fieldset...
		var activeFieldset = $(this).closest('li').next('li').find('fieldset');
		// find the fieldsets that are curretly active so they can be slid up...
		$(this).closest('ul').find('fieldset').hide();
		// now slide down the new fieldset...		
		$(activeFieldset).slideDown();
	});
	
	$('#get-shipping-rates').click(function(e){
			// prevent the link from submitting
			e.preventDefault();
			// show the getting rates message.
			$('#shipping-rates-container').html('Getting shipping rates');			
			// get the rates
			$.get($(this).attr('href'), function(data) {
			  $('#shipping-rates-container').html(data);
			});
	});
	
	
	$('#nav li ul').hide();
	$('#nav > li').hoverIntent({
		over: function(){
			$(this).children('ul').fadeIn('fast');		
		},
		timeout: 1000,
		out: function(){
			$(this).children('ul').fadeOut('fast');
		}
	});
	
});
/*End the Document.Ready*/

function initVariations(){
	var $variations = $('.variations');
	
	// if the object has variations as indicated by the variations class being present...then we need to store the default values for some of the content areas that will swap...
	if($('body').find(".related-select,.related-radio").length > 0){
		
		jQuery.data(document.body, 'longDescription', jQuery.trim($('#longDescription').html()));
		jQuery.data(document.body, 'title', jQuery.trim($('#title').html()));
		jQuery.data(document.body, 'sku', jQuery.trim($('#sku').html()));
		jQuery.data(document.body, 'priceLabel', jQuery.trim($('#priceLabel').html()));
		jQuery.data(document.body, 'price', jQuery.trim($('#price').html()));
		jQuery.data(document.body, 'imageSrc', $('#objectImage').attr("src"));
		jQuery.data(document.body, 'tieredPricing', jQuery.trim($('#tiered-pricing-container').html()));
		
		$('#sku-container').hide();
		
		jQuery.data(document.body, 'displayingDefault', true);
	}
	
	// setup the variations for each fieldset...
	$variations.each(function(i, x){
		$relationshipGroup = $(x);
		currentRelatedId = $(this).attr('id');
		relatedFields = $(this).find(".related-select,.related-radio").find("select,input[type='radio']");
		relatedContainers = $(this).find(".related-select,.related-radio");
		onChangeUrl = $('.onChangeUrl').val();
		populateField = $(this).find('.populateField').val();
		onLoadUrl = $(this).find('.onLoadUrl').val();
		relatedItemList = $(this).find("input[name='relatedItemList']").val();
		
		// get all the select and input(radio) controls and add then to the related fields array
		$(relatedContainers).each(function(i, x){
			var fieldType = 'select';
			var $fieldContainer = $(this);
			var defaultText = '';
			if($(x).attr("class") == 'related-select'){
				var fieldType = 'select';
				var $field = $(this).find("select");
			}else if($(x).attr("class") == 'related-radio'){
				fieldType = 'radio';
				var $field = $(this).find("input[type='radio']");
			}
			
			// if each field has no value, set it to disabled...			
			if(fieldType == 'select'){
				if(i > '0'){
					$field.attr('disabled', 'true');
				}
				defaultText = $(this).find('option').filter(':first').attr('text');
			}else if(fieldType == 'radio'){
				previousLabel = $(relatedContainers[i-1]).attr('title');
				currentLabel = $(relatedContainers[i]).attr('title');					
				defaultText = "Please select a " + previousLabel + " before selecting " + currentLabel + ".";
				if(i > '0'){
					$fieldContainer.html(defaultText);
				}
			}
			// add the default text to the proper key in the container element.
			$fieldContainer.data('defaultText', defaultText);
			
			// Loop each field now adding the change event.
			$field.each(function(i, fld){
				bindField(fld);
			});
			// make sure the fields are all set to null when first loading the page...But do not set it as null if the first related group is a radio button bank...
			if(i == 0 && fieldType == 'radio'){
				// do nothing b/c the first related set of fields are radio buttons...
			}else{
				$field.val("");	
			}
			
		});
		
		// lastly, make sure one load, any select fields that are disabled... are reset as well
		relatedContainers.find('select[disabled="true"]').val("");
	
	});
}

function bindField(fld){
	
	// now bind the click handler to each field
	$(fld).change(function(e){
		e.preventDefault();
		// first lets block the field so the user knows a changes is in the works...
		$('#cart-box').block({ 
			message: '<h1>Updating</h1>', 
			css: { border: '3px solid #a00' } 
		});
		
		$changeField = $(this);
		$changeFieldContainer = $(this).parent('span');
		// make sure the change field actually has a value...
		if($changeField.val()){		
			// post the new filtered data to get the other options...
			postFields = $(this).parents('.variations').find(".related-select,.related-radio").find("select,input[type='radio']").serialize();						
			postFields = postFields + '&relatedItemList=' + relatedItemList + '&changeField=' + $changeField.attr('name');
			
			$.post(onChangeUrl + '?rand=' + Math.floor(Math.random()*100), postFields, function(json){
				// if not ID was returned, that means the user has not drilled down to the product yet...
				if(!json.object.objectID){
					// loop the options...
					$(json.options).each(function(i, o){
						var fieldId = 'variation_' + o.ItemIndex + '_' + o.VariationID + '_VariationItemID';
						if(fieldId != $changeField.attr("id")){
							// if a select box...
							if(o.FieldType == 'selectbox'){
								var select = $('#' + fieldId);	
								var $thisFieldContainer = select.parent('span');
								var options = select.attr('options');							
								$('option', select).remove();
								options[options.length] = new Option($thisFieldContainer.data("defaultText"), "");
								$.each(o.Options, function(val, opt) {
									options[options.length] = new Option(opt.VariationItemName, opt.VariationItemID);
								});
								select.removeAttr('disabled');
								select.val("");								
							}else if(o.FieldType == 'radio'){
								var fieldName = 'variation_' + o.ItemIndex + '_' + o.VariationID + '_VariationItemID';
								var radioContainer = $('#variation_' + o.ItemIndex + '_' + o.VariationID + '_VariationItemID_Container');
								var newHtml = '';
								var fieldId = 'variation_' + o.ItemIndex + '_' + o.VariationID + '_VariationItemID';
								$.each(o.Options, function(val, opt) {
									thisId = fieldId + '_' + opt.VariationItemID;
									newHtml = newHtml + '<label for="' + thisId + '"><input id="' + thisId + '" name="'+  fieldName +'" type="radio" class="required combinable" value="' + opt.VariationItemID + '" />' + opt.VariationItemName + '</label></cfoutput>' ;
								});
								$(radioContainer).html(newHtml);
								
								// we need to bind the new fields
								$("input[name='"+ fieldName +"']").each(function(i, fld){
									bindField(fld);
								});
								
							}
						resetContainers($changeField);	
						}
					});	
				}else{
					updateVariationDetails(json);
				}
				// now unblock...
				$('#cart-box').unblock(); 
			}, 'json');
			
		}else{
			resetContainers($changeField);
			// now unblock...
			$('#cart-box').unblock(); 
		}
	});
	
}


function resetContainers($changeField){
	// ok the value was changed back to null, so we need to reset all the of the related fields after this one to the default state...
	setToDefault = false;
	var $nextContainer = '';
	var nextFieldName = '';
	
	resetObjectDetails();
	
	$(relatedContainers).each(function(i, x){							
		var fieldName = '';
		
		if($(x).attr("class") == 'related-select'){
			fieldName = $(x).find('select').attr('name');
		}else if($(x).attr("class") == 'related-radio'){	
			fieldName = $(x).find('input[type="radio"]').attr('name');
		}
		
		if(setToDefault && nextFieldName != fieldName){
			if($(x).attr("class") == 'related-select'){
				$(x).find('select').attr('disabled', 'true');
				$(x).find('select').val("")
			}else if($(x).attr("class") == 'related-radio'){		
				$(x).html($(x).data('defaultText'));
			}
		}	
		
		if($changeField.parents("span").attr('id') == fieldName + '_Container'){
			setToDefault = true;
			
			if($changeField.val()){
				$nextContainer = $(relatedContainers[i + 1])
				
				if($nextContainer.attr("class") == 'related-select'){
					nextFieldName = $nextContainer.find('select').attr('name');
				}else if($nextContainer.attr("class") == 'related-radio'){	
					nextFieldName = $nextContainer.find('input[type="radio"]').attr('name');
				}
			}
			
		}
		
		
	});

}

function resetObjectDetails(){
	
	if(!jQuery.data(document.body, 'displayingDefault'))	{
		//$('#objectID_' + json.ItemIndex).val("");
		$('#longDescription').html(jQuery.data(document.body, 'longDescription'));
		$('#title').html(jQuery.data(document.body, 'title'));
		$('span.sku').html(jQuery.data(document.body, 'sku'));
		$('span.skuLabel').html(jQuery.data(document.body, 'skuLabel'));
		$('#priceLabel').html(jQuery.data(document.body, 'priceLabel'));
		$('#price').html(jQuery.data(document.body, 'price'));
		$('#objectImage').attr('src', jQuery.data(document.body, 'imageSrc'));
		console.log(jQuery.data(document.body, 'tieredPricing'))
		$('#tiered-pricing-container').html(jQuery.data(document.body, 'tieredPricing'));
		
		// how show a few fields that were hidden in the default display...
		$('#sku-container').hide();
		
		jQuery.data(document.body, 'displayingDefault', true);
	}
		
}

function updateVariationDetails(json){
	var data = json.object;
	var $tierContainer = $('body').find('#tiered-pricing-container_' + json.ItemIndex)
	$('#objectID_' + json.ItemIndex).val(data.objectID);
	if(data.longDescription.length){
		$('#longDescription').html(data.longDescription);
	}
	$('#title').html(data.title);
	$('#sku').html(data.sku);
	$('#priceLabel').html(data.priceLabel);
	$('#price').html(data.price);
	if(data.image.src.length) // only replace the image if there is one for this object
		$('#objectImage').attr('src', data.image.src);
	
	$('#sku-container').show();
	
	jQuery.data(document.body, 'displayingDefault', false);
	
	// Start: update the image
		// only update the image if a new image was returned...
		if (data.image.src.length) {
		$('.default-image').attr('src', data.image.src);
			$('.enlarge-default-image-link').attr('href', data.image.enlargeUrl);
			if(data.image.width > 0){
				$('.default-image').attr('width', data.image.width);	
			}else{
				$('.default-image').removeAttr('width');
			}
		if(data.image.height > 0){
				$('.default-image').attr('height', data.image.height);	
			}else{
				$('.default-image').removeAttr('height');
			}
		
	  }						
	// End: update the image
	
	// START: updating the tiered pricing table...
		tiersTable = '<table class="tiered-pricing"><thead><tr><th>Buy Qty</th><th class="price">Quantity Price</th></tr></thead><tbody>';
		$.each(data.tieredPricing, function(i, obj) {
		// we need to add 1 to i b/c it is on a 0 - index whereas the .length is not.		
		if(i + 1 < data.tieredPricing.length ){
			tiersTable = tiersTable + '<tr><td>'+ obj.qty + ' - ' + (parseInt(data.tieredPricing[i + 1].qty) - 1) + ' </td><td class="price">' + obj.price + '</td></tr>';	
		}else{
			tiersTable = tiersTable + '<tr><td>'+ obj.qty + ' or more</td><td class="price">' + obj.price + '</td></tr>';	
		}
			
		});
		tiersTable = tiersTable + '</tbody></table>';
		
		if (data.tieredPricing.length > 1) {
			$tierContainer.html(tiersTable);
			$tierContainer.show();
	  }else{
			$tierContainer.hide();
			$tierContainer.html("");
		}
	// END: updating the tiered pricing table...	
		
		
	
}

function validateCartAdd(formData, jqForm, options){
	var allowSubmit = true;
	//form-error
	var requiredFields = $('input[class~=required],select[class~=required],textarea[class~=required],input[class~=combinable],select[class~=combinable]');
	var valueChecked = false;
	// loop each field to ensure a value is selected.
	$.each(requiredFields, function(i, f) {
		$field = $(f);			
		valueChecked = false;
		$container = $field.parents('span');
		if($field.attr('type') == 'radio'){
						
			if(!$("input[@name='" + $field.attr('name') + "']:checked").val()){
				if(!$container.hasClass('form-error')){	
					$container.addClass('form-error');
					$container.next('p.form-error').show();
					allowSubmit = false;
				}
			}else{
				$container.removeClass('form-error');			
				$container.next('p.form-error').hide();
			}			
		}else{
			//$container = $field.nextAll('p.form-error');
			if(!$field.val()){
				// if the field does not already have the error class, add it
				if(!$field.hasClass('form-error')){				
					$field.addClass('form-error');
					// add the error message...
					$container.next('p.form-error').show();
				}
				allowSubmit = false;
			}else if($field.val() && $field.hasClass('form-error')){
					// remove the class...
					$field.removeClass('form-error');
					$container.next('p.form-error').hide();
			}
		}
	});
		
	
	if(allowSubmit){
		$('#cart-box').block({ 
			message: '<h1>Adding Item</h1>', 
			css: { border: '2px solid #a00' }		 
		}); 
	}
	
	return allowSubmit;
}







function updateShippingData(){
	
	// if the data structure exists, this means the user has changed the values, so lets update the shipping...
	if (jQuery.data(document.body, "shippingAddress")) {
		// we need to make sure the City, State, Postal Code and Country is complete before fetching the rates...
		var city =  $('#shipping_City').val();
		var state =  $('#shipping_State').val();
		var postalCode =  $('#shipping_PostalCode').val();
		var country =  $('#shipping_Country').val();
		if(city.length > 0 && state.length > 0 && postalCode.length > 0 && country.length > 0){
			// now, we only want to check the new rates if one of the fields has changed...
			var dataStore = jQuery.data(document.body, "shippingAddress");
			if (city != dataStore.city || state != dataStore.state || postalCode != dataStore.postalCode || country != dataStore.country) {
	  		// before we start swapping stuff around, store the currently selected shipping method.  If the same method is found in the new options we will preselect it...
				jQuery.data(document.body, "shippingAddress_selectedMethodID", $("input[name='shipping_ShipMethodID']:checked").val());
				// show the getting rates message.
				$('#shipping-rates-container').hide();
				$('#shipping-rates-loading-message').show();
				// fetch the rates...
				$.post($("#shippingRatesUrl").val(), {
					shipping_City: city,
					shipping_State: state,
					shipping_PostalCode: postalCode,
					shipping_Country: country
				}, function(data){
					$('#shipping-rates-container').html(data);
					$('#shipping-rates-loading-message').hide();
					// now check to see if the value of shippingAddress_selectedMethodID is present in the new options...
					if (jQuery.data(document.body, "shippingAddress_selectedMethodID")) {
						var currentVal = jQuery.data(document.body, 'shippingAddress_selectedMethodID');
						$('input[value=' + currentVal + ']').attr("checked", "checked");
		  		}					
					$('#shipping-rates-container').show();
				});
			}
		}
	}
	
	// load the data into the body...
  jQuery.data(document.body, "shippingAddress", {city: $('#shipping_City').val(), 
					 																			 state: $('#shipping_State').val(),
																								 postalCode : $('#shipping_PostalCode').val(),
																								 country : $('#shipping_Country').val()});
}



function clearMe(formfield) 	{
	if (formfield.defaultValue==formfield.value)
	formfield.value = ""	}



