$(document).ready(function() {

	/** Generic behaviors **/

	/*$("#menu > li").hover(
			function() {
				$(this).addClass("sfhover");
			},
			function() {
				$(this).removeClass("sfhover");
		});
	*/

	$(".navMenu > li").hoverIntent({
		over: function() {
			$(this).addClass("sfhover");
		},
		out: function() {
			$(this).removeClass("sfhover");
		},
		sensitivity:12,
		interval:75
	});

   $(".newWindow").click(function() {
	   openWindow(this.href);
	   return false;
   });

   $(".autoSubmit").bind('change', function() {
 		$(this).parents("form").submit();
 	});

  $("a.submitForm").bind('click', function() {
	  if(this.target == null) {
		  $(this).parents("form").submit();
	  } else {
		  $(this.target).click();
	  }
	  return false;
   });

  $(".orderItemChkBox").click(function() {
  	  $(this).next().trigger('click');
  });

  $(".initFocus").focus();

  $(".tab").click(function() {
	   $(".tab").addClass("inactive").removeClass("active")
	   $(this).addClass("active").removeClass("inactive");
	   $(this).find("a").get(0).blur();
	   $(".tabContent").each(function() {
		   $(this).hide();
	   });
	   $("#" + this.id + "Content").show();
  });

   //Limits the amount of text in a textarea to number of characters specified by the textarea's maxlength attribute
  var countdown = {
	    init: function() {
	        countdown.remaining = countdown.max - $(countdown.obj).val().length;
	        if (countdown.remaining < 0) {
	            $(countdown.obj).val($(countdown.obj).val().substring(0,countdown.max));
	        }
	        $(countdown.obj).next().find(".remaining").html(countdown.remaining);
	    },
	    max: null,
	    remaining: null,
	    obj: null
	};
    $(".countdown").each(function() {
        $(this).focus(function() {
            var c = $(this).attr("class");
            countdown.max = parseInt(c.match(/limit_[0-9]{1,}_/)[0].match(/[0-9]{1,}/)[0]);
            countdown.obj = this;
            iCount = setInterval(countdown.init,1000);
        }).blur(function() {
            countdown.init();
            clearInterval(iCount);
        });
    });

  $("textarea :not(.countdown)").bind("keyup blur", function() {
	  var maxLength = $(this).attr("maxlength");
	  if (maxLength != null) {
	      currentLength = this.value.length;
	      remainingCharacters = (maxLength - currentLength);
	      if ( currentLength >= maxLength ) {
	    	  this.value = this.value.substr(0, maxLength);
	      }
	  }
  });

  maxLength = 60;
  function checkTextLength( textField ) {
      currentLength = textField.value.length;
      remainingCharacters = (maxLength - currentLength);
      if ( currentLength >= maxLength ) {
        textField.value = textField.value.substr(0, maxLength);
      }
  }

  /** Product detail page behaviors **/

  $(".itemQty").submitFromEnter("input#addToCartButton");

  $(".sellableItems td input:text").click(function() {
	   $(this).select();
  });

   $(".skuBubble").hover(
		function(event) {
			showToolTip(event,$('.salesText', $(this).parents('.description')).html(),true,-6,-2);
		},
		function() {
			hideToolTip();
	});

   $("#addToCartButton").click(function() {
	   var params = $(this.form).serializeArray();
	   params.push({name:"ajax", value:true},{name:this.name, value:this.value});
	   $("#addToCartButton").hide();
	   $("#addToCartProcessing").show();
	   $.post(this.form.action, params, function(data) {
		   if( validateResponse(data)) {
			   $("#addToCartModalContentContainer").html(data);
			   $("#totalQuantity").html($("#newTotalQuantity").html());
			   $("#addToCartModal").jqmShow();
			   $("#theTitle").html($("#newModalTitle").html());
			   resetQuantityInputs();
			   $("#addToCartButton").show();
			   $("#addToCartProcessing").hide();
		   }
	   });

	   // Set order id to null
	   $("#orderId").val(null);
	   return false;
   });

   ajaxGetHandler(ajaxGetHandler);

   /** Cart summary page behaviors **/
   $(".quantityInput").submitFromEnter("input#updateQuantity")

   $("#registerFromCheckoutButton").click(function() {
	   $.get('/checkout/register/registerAnonymous.htm', null, function(data) {
		   if( validateResponse(data)) {
			   $("#checkoutRegistrationModalContainer").html(data);
			   $("#checkoutRegistrationModal").jqmShow();
		   }
	   });

	   return false;
   });

   $("input[name='isStorePickup']").click(function() {
	   if ($(this).val() == 'true') {
		   $("#hiddenMethodInput").val("pickup");
		   $("#changeMethod").submit();
	   } else {
		   $("#hiddenMethodInput").attr('disabled', 'disabled');
		   $("#changeMethod").submit();
	   }
   });

   /** Shipping Address page behaviors **/

   $(".tab").click(function() {
	   if (this.id == "singleTab") {
		   $(".currentTab").val("1");
		   $(".shipEntireOrderCheckbox").removeAttr("disabled");
		   $(".defaultShipEntireOrderCheckbox").attr("checked", "checked");
		   $(".shipEntireOrder").removeClass("disabled")
	   }

	   if (this.id == "multipleTab") {
		   $(".currentTab").val("2");
		   $(".shipEntireOrderCheckbox").attr("disabled", true).removeAttr("checked");
		   $(".defaultShipEntireOrderCheckbox").removeAttr("checked");
		   $(".shipEntireOrder").addClass("disabled")
	   }
   });

	$(".tab").filter(".active").click();

   /** Shipping method page behaviors **/
   $(".methodsContainer input:radio").click(function() {
	   displayDeliveryInstructions(this);
   });

   $(".methodsContainer input:radio:checked").each(function() {
	   $(this).click();
   });


   $(".methodsContainer select.daySelect").bind("change blur keyup", function() {
	   var parentContainer = $(this).parents(".methodsContainer");
	   var selectedIndex = $("option:selected", $(this))[0].index;

	   //also disabling so that hidden elements are not submitted with the form
	   $(".timeOptions select", parentContainer).attr("disabled", "disabled").hide().removeClass("currentTimeSelect");
   	   $($(".timeOptions select", parentContainer)[selectedIndex]).show().addClass("currentTimeSelect").attr("disabled", null).show();
   });

   $(".addNewNumber").click(function() {
	   if ($(this).parent().parent().find(".addingNewPhone").val() == "true") {
		   $(this).parent().parent().find(".addingNewPhone").val("false");
	   } else {
		   $(this).parent().parent().find(".addingNewPhone").val("true");
	   }

	   $(this).parent().parent().children(".existingPhoneSelect").find('select option:first').attr('selected', 'selected').parent('select');
	   $(this).parent().parent().children(".newPhoneInput").toggle();
	   $(this).parent().parent().children(".existingPhoneSelect").toggle();
	   return false;
   });

   $(".preventDoubleSubmit").preventDoubleSubmit();

   $(".hover-menu").hoverIntent({
      sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)
      interval: 50,   // number = milliseconds for onMouseOver polling interval
      over: function() { $(".hover-items", this).fadeIn(200); },     // function = onMouseOver callback (required)
      timeout: 1000,   // number = milliseconds delay before onMouseOut
      out: function() { $(".hover-items", this).fadeOut(200); }      // function = onMouseOut callback (required)
    });

   $(".wishlist .addToCartLink").one("click", function(){
	   this.href = this.href + '&quantity=' + $(this).closest("tr.item").find(".quantityInput").val();
	});

});

$.fn.preventDoubleSubmit = function() {
  $(this).submit(function() {
    if (this.beenSubmitted)
      return false;
    else
      this.beenSubmitted = true;
  });
};

$.fn.submitFromEnter = function(targetSelector) {
   $(this).keypress(function(e){
	   //if enter key is pressed...
	   if (e.keyCode == 13) {
		   $(targetSelector).click();
		   return false;
	   }
   });
}

function displayDeliveryInstructions(clickedElem) {
	var parentContainer = $(clickedElem).parents(".methodsContainer");
	if ($(clickedElem).val() == "delivery") {
		   $(".dayTimeContainer", parentContainer).show();
		   $(".dayTimeContainer textarea, .dayTimeContainer select").removeAttr("disabled");
	} else {
		   $(".dayTimeContainer", parentContainer).hide();
		   $(".dayTimeContainer textarea, .dayTimeContainer select").attr("disabled", true);
	}
}

function openWindow(winUrl) {
	var winAttr = 'resizable=true,toolbar=yes,location=yes,scrollbars=yes';
	window.open( winUrl, 'text', winAttr );
}

function positionModal(h){
	h.w.css('top',$(window).scrollTop()+10).prependTo('body>.bodyContent').show();
}
function removeModal(h){
	h.w.hide();
	if (h.o) h.o.remove();
}

function ajaxGetHandler(callback) {
   $("a.ajaxGet").click(function() {
	   $(this.target).load(this.href);
	   return false;
   });
}

function printCart(){
	urchinTracker('/links/shoppingcart/print');
	self.print();
}

function validateResponse(data) {
	var ajaxErrorRedirect = $("#ajaxErrorRedirect", $(data));
	if (ajaxErrorRedirect.length > 0) {
		window.location = ajaxErrorRedirect.html();
		return false;
	}
	return true;
}

function resetQuantityInputs() {
	var inputs = $(".sellableItems input.itemQty, .sellableItems input.accessoryQty");
	var itemInputs = $(".sellableItems input.itemQty");
	if (itemInputs.length == 1) {
		inputs.val("0");
		itemInputs.val("1");
	} else {
		inputs.val("0");
	}

	$(".giftWrapCheckbox").removeAttr("checked");
}

function resetTimeslots() {
	//resetting the timeslot select boxes in case the user hits the back button
	$(".methodsContainer select.daySelect option[selected]").removeAttr("selected");
	$(".methodsContainer select.daySelect :first-child").attr("selected", "selected");

	$(".methodsContainer .timeOptions select").attr("disabled", "disabled")
	$(".methodsContainer .timeOptions").each(function() {
		$("select:first", this).attr("disabled", null).show();
	});
	$(".methodsContainer .timeOptions select option").removeAttr("selected");
	$(".methodsContainer .timeOptions select :first-child").attr("selected", "selected");
}

function addItemToWishList( pWishListId ) {

	// New Wish List
	if ( pWishListId == null ) {
		$("#wishListSubmitButton").click();
		return false;
	}

	$("#orderId").val(pWishListId);
	$("#addToCartButton").click();
	return false;
}