//get url variables
$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

function autoComplete(){
	
	searchField = $("#search");
	fauxAutoSuggest = "";
	autoSuggestEndString = fauxAutoSuggest.split("");
	
	searchField.focus(function(){
		
		searchField.keyup(function(event){
			
			if (searchField.val().length >= 1){
				
				//Gets the suggested search term based on the user's current input. Splits the string into an array for comparison.
				if ( event.keyCode == 40 || event.keyCode == 38 ){
				
				}
				else{
					getAutoSuggestTerm();
				}
				//Intercept if the user clicks on the down arrow.
				
					
				//Get the auto suggest results.
				//getAutoSuggest();
				
				autoSuggestEndString = fauxAutoSuggest.split("");
				
				var remainingCharPosition = $(this).val().length;
				var autoCompleteString = "";
				
				for (i=remainingCharPosition; i < fauxAutoSuggest.length; i++){
					
					/*
						Double check the the string being typed matches the autocomplete string. 
						Make them both lowecase, because we don't care about case sensitivity.
					*/
					
					matchStr = fauxAutoSuggest.slice(0,searchField.val().length);
					
					if (searchField.val().toLowerCase() == matchStr.toLowerCase()){
					
						autoCompleteString = autoCompleteString + autoSuggestEndString[i];
					
					}
				
				}
				
				$("#gray").val(searchField.val()+autoCompleteString);
				
				if (event.keyCode == '39'){
					
					searchField.val(searchField.val()+autoCompleteString);
					
				}
				else if ( event.keyCode == 40 || event.keyCode == 38 ){
					var currentLI = $('.SuggestUL li:eq(' + scrollPostion + ')');
					var currentWord = currentLI.children("a").children("b").text();
					$("#gray").val(currentWord);
					$("#search").val(currentWord);
				}
				
			}
			else if (searchField.val().length < 1){
				$("#gray").val("");	
			}
			
		});
		
	});
	
}

function getAutoSuggestTerm(){
	
	ajaxTransaction = $.ajax({
					    type: 'post',
					    url: "/inc/autoComplete.cfm",
					    data: $("#search-form").serialize(),
					    success: function(response) {
					    	fauxAutoSuggest = response;
					    },
					    error: function(xhr, type, errorThrown) {
					    	alert("Error:" + " " + errorThrown);
					    },
					    complete: function(jqXHR, textStatus){
					    	ajaxTransaction = null;
					    }
				    });			    
	return fauxAutoSuggest;	    
}

var scrollPostion = null;

function getAutoSuggest(){
		
	ajaxRequest = $.ajax({
					type:'post',
					url: "/inc/autoSuggest.cfm",
					data: $("#search-form").serialize(),
					success: function(response){
						$("#auto-suggest").slideDown("fast",function(){
							
							$(this).html(response);
							
						});
					}
					});
	
}

//Search Autosuggest
var objHttpFileDataRequest = null;
var scrollPostion = null;




function searchSuggest(e, inputString) {
	
	if( e.keyCode == 40 ) {		// down
									
		if(scrollPostion == null) {
			//Take away the focus.
			$('.SuggestUL li').removeClass('suggest-box-selected');
			$('.SuggestUL li:first').addClass('suggest-box-selected');
			//$('#search').val( $('.SuggestUL li:first a').attr('title') );
			scrollPostion = 0;
		} else {
			if( scrollPostion < $('.SuggestUL li').size() - 1 ) {
				scrollPostion++;
				$('.SuggestUL li').removeClass('suggest-box-selected');
				
				var thisLI = $('.SuggestUL li:eq(' + scrollPostion + ')');											
				thisLI.addClass('suggest-box-selected');
				//$('#search').val( thisLI.find('a').attr('title') );											
			}	
		}
	} else if( e.keyCode == 38 ) { // up
		if(scrollPostion != null) {
			if( scrollPostion != 0 ) {
				scrollPostion--;
				$('.SuggestUL li').removeClass('suggest-box-selected');
				var thisLI = $('.SuggestUL li:eq(' + scrollPostion + ')');											
				thisLI.addClass('suggest-box-selected');
				//$('#search').val( thisLI.find('a').attr('title') );
			}
		}									
		
	} else if (e.keyCode == 13) {
		if ($(".suggest-box-selected").length) {
			prodLoc = $("li.suggest-box-selected > a").attr("href");
			window.location = prodLoc;
		}	
	} else { // if it is not "Enter"
	
		scrollPostion = null; //reset
	
		// Check to see if there is an AJAX request already in progress that needs to be stopped.
		if (objHttpFileDataRequest){							 
			// Abort the AJAX request.
			objHttpFileDataRequest.abort();							 
		}
		
		if(inputString.length == 0) {
	        // Hide the suggestion box.
	        $("#auto-sug").hide();
	    } else {
			objHttpFileDataRequest = $.post("/site/search_products.cfm?r=" + Math.random(), {queryString: ""+inputString+""}, function(data){
				if(data.length > 0) {
					$('#moreResults').html('"' + inputString + '"');
					$('#moreResultsLink').attr('href', '/site/search.cfm?search=' + inputString );
					
					//$("#suggest-box,#suggest-box-bottom").show();
					$("#auto-sug").show();					
					
					
					$("#suggestResults").html(data);
					
					$("#suggest-box li a b").highlight(inputString);
	            } else {
					$("#auto-sug").hide();
				}
	        });
	    }							
	}						
	
} // lookup


function ajaxErrorHandler(){
	
	$(document).ajaxError(function(event, request, settings, exception){
		
		ajaxTransaction = $.ajax({
			type: 'post',
			url: "/inc/ajaxErrorHandler.cfm",
			data: {error:exception,data:settings.data,url:settings.url},
			complete: function(jqXHR, textStatus){
				ajaxTransaction = null;
			}
		});
		
		//Unbind element to prevent further errors, if the exception was not a request abort.
		if (exception != "abort"){
			var currentActiveElement = $("#"+event.target.activeElement.id);
			currentActiveElement.unbind();
		}
	});
}

function search(){
	
	var search = $("#search");
	var elementName = "search";
	
	if (search.val().length > 0){
		$("label[for='"+elementName+"']").hide();
	}
	else{
		$("gray").val("");
	}
	
	search.click(function(){
		
		//IE puts the brands scroller on top of the search, so let's fix it.
		var jLogoContainer = $( "#brands-rotator" );
		
		jLogoContainer.css( "z-index", "-10");
		
		$("label[for='"+elementName+"']").hide();
		$("#searchBox").addClass("searchBox-selected");
		$("#gray").addClass("gray-selected");
		$("#searchSubmit").addClass("active");
		search.addClass("active");
		
	}).focus(function(){
		
		$(this).trigger("click");
		
	}).blur(function(){
		
		if (search.val() == ""){
			$("label[for='"+elementName+"']").show().css("color","#999");
			$("#searchBox").removeClass("searchBox-selected");
			$("#gray").removeClass("gray-selected");
			$("#searchSubmit").removeClass("active");
			search.removeClass("active");
		}
		var jLogoContainer = $( "#brands-rotator" );
		jLogoContainer.css( "z-index", "0");
		
	});
	
	
	// Don't allow empty searches.
	$("#search-form").submit(function(){
		
		if (search.val().length > 0){
			
			return true;
			
		}
		else{
			$("label[for='"+elementName+"']").css("color","red");
		}
		return false;
		
	})
	
}

function brandScroller(){
	
		var jLogoContainer = $( "#brands-rotator" );
		var jLogos = jLogoContainer.find( "ul" );
		var blnUpdate = true;
		var intPause = 70;
		var intIncrement = 3;
		
		jLogoContainer.hide();
		
		jLogoContainer
			.css( "position", "relative" )
			.css( "width", "960px" )
			.css( "z-index", "0")
			.show();
		;
		
		jLogos
			.css( "margin", "0px 0px 0px 0px " )
			.css( "width", "3000px" )
			.css( "left", "0px" )
			.css( "position", "relative" )
			.css( "top", "0px" )
			.css( "left", "0px" )
		;
		
		jLogos.find( "li" )
			.css( "margin", "0px 0px 15px 0px " )
			.css( "padding-right", "7px" )
			.css( "height", "30px" )
		;
		
		// If the image errors out (to load), then remove the list item.
		jLogos.find( "img" )
			.error(function(){
					$( this ).parents( "li:first" ).remove();
				})
			.each(function(){
					// Check to see if the image has a width.
					if (
						this.complete && 
						(isNaN( this.width ) || this.width < 1)
						){
						// Remove the image - it did not load well.
						$( this ).parents( "li:first" ).remove();
					}
				});
		
		// Define the method that will perform the animation.
		var updatePosition = function(){
		var jFirstLogo = jLogos.children( ":first" );
		var intNewLeft = (parseInt( jLogos.css( "left" ) ) - intIncrement);
				
		// If we are not animating, then exit.
		if (!blnUpdate){
			return;
		}
				
		// Set the new offest of the logos.
		jLogos.css( "left", intNewLeft );
					
		// Check to see if we have moved left enough to hide the last element.
		// That is, if the left-offset of the list has moved the first logo
		// completely off the screen. If so, we just want to move it back to the 
		// end of the list.
			if (jFirstLogo.outerWidth() < Math.abs( intNewLeft )){
				
				// Move the logo to the end of the list (this will pop it from the
				// front and append it to the end).
				jLogos.append( jFirstLogo );
				
				// Readjust the offset of the list to not "jump" because we
				// just remove the first logo.
				jLogos.css( 
					"left", 
					(intNewLeft + jFirstLogo.width() + parseInt( jFirstLogo.css( "padding-right" ) ))
					);
					
				// Check to see if the first element has a width.
				if (jFirstLogo.width() < 1){
					// Remove it - something went wrong.
					jFirstLogo.remove();
				}					
			}
		}
			
			
		// Start the animation interval.
		var updateInterval = setInterval( updatePosition, intPause );
			
			
		jLogoContainer.click( function(){ clearInterval( updateInterval ); } );
		jLogoContainer.dblclick( function(){ updateInterval = setInterval( updatePosition, intPause ); } );
			
		// When someone mouses over the logo container, let's turn off
		// the flag for animation.
		jLogoContainer.mouseover(
			function(){
				blnUpdate = false;
				return( false );
			}
			);
			
		// When someone mouses out of the logo container, let's turn 
		// the flag for animation back on.
		jLogoContainer.mouseout(
			function(){
				blnUpdate = true;
				return( false );
			}
			);
	
	
}

function categoriesHover(){
	
	/*function makeTall(){
	
		$("#categories-menu").fadeIn("fast",function(){
		
			$("#categories-menu").mouseleave(function(){
				$("#categories-menu").hide();	
			});
		
		});
	
	};
	
	function makeShort(){
		$("#categories-menu").hide();
	};
	
	var config = {    
	    over:makeTall, // function = onMouseOver callback (REQUIRED)    
	    timeout: 0, // number = milliseconds delay before onMouseOut    
	    out: makeShort // function = onMouseOut callback (REQUIRED)    
	};
	
	$("#categories-drop-down").hoverIntent(config);
	*/
	
	$("#categories-drop-down").hoverIntent(function(){
		
		$("#categories-drop-down").addClass("categories-drop-down-hover");
		$("#categories-menu").fadeIn("fast");
		$(".categories").addClass("cat-drop");
		
	},function(){
		$("#categories-drop-down").removeClass("categories-drop-down-hover");
		$("#categories-menu").hide();
		$(".categories").removeClass("cat-drop");
		
	});
	
}

function brandsHover(){
	
	$("#brands-drop-down").hoverIntent(function(){
		
		$("#brands-drop-down").addClass("brands-drop-down-hover");
		$("#brands-menu").fadeIn("fast");
		$(".brands").addClass("brands-drop");
		
	},function(){
		
		$("#brands-drop-down").removeClass("brands-drop-down-hover");
		$("#brands-menu").hide();
		$(".brands").removeClass("brands-drop");
		
	});
}

function referenceDocs(){
	
	rd = $("#reference-docs");
	rdr = $("#reference-docs-replacement");
	
	//Find all the optgroup tags.
	rd.find("optgroup").each(function(j){
		
		var headingString = "<li class='"+$(this).attr("class")+"'><span id='no-close'>"+$(this).attr("label")+"</span></li>";
		rdr.append(headingString);
	
		//Get the current item's reference documents.
		$(this).find("option").each(function(i){
			var crrVal = $(this).val();
			var crrText = $(this).text();
			
			var liString = "<li class='"+$(this).attr('class')+"' rel='"+crrVal+"'><a href='"+crrVal+"' target='_blank'>"+crrText+"</a></li>";
			//Append to the new list.
			rdr.append(liString);
		
		});	
			
	});
	
	
	rd.hide();
	rdr.show();
	
	//Click Event.
	$("#ul-title").click(function(e){
		
		e.preventDefault();
		
		if (rdr.css("overflow") == "hidden"){
			rdr.css("overflow","visible");
		}
		else{
			rdr.css("overflow","hidden");
		}
		
	});
	
	//Close reference docs if clicked outside the ul.
	$("body").click(function(e){
		if (e.target.id == "ul-title" || e.target.id == "no-close"){
			
		}
		else{
			if (rdr.css("overflow") == "visible"){
				rdr.css("overflow","hidden");
			}
		}
	});
	
}

function detailsMenu(){
	
	$(".li-details-menu").hover(function(){
		
		$(this).find(".details").attr("class","").addClass("details-active");
		$(this).find(".details-menu").fadeIn("fast",function(){
			
		});
		
	},function(){
		
		$(this).find(".details-active").attr("class","details");
		$(this).find(".details-menu").hide();
		
	});
	
	$(".details").click(function(e){
		e.preventDefault();
	});
	
	$(".details-menu").find("a").each(function(){
				
		$(this).click(function(e){
			
			e.preventDefault();
			
			//Add the Current Class.
			$(".current").removeClass("current");
			$(this).parent("li").addClass("current");
			
			var toShow = $(this).attr("rel");
			
			//Hide all except the box to show.
			$("#"+toShow).parent("#item-info").find(".kit-info").each(function(){
				
				$(this).hide();
				
			});
			
			$("#"+toShow).fadeIn("fast");
			
			//Close the Menu.
			/*$(".details-active").attr("class","details");
			$(".details-menu").fadeOut("fast");*/
			
			
		});
		
	});
	
}

function productQTY(){

	$("#increment").click(function(e){
		
		e.preventDefault();
		var productQtyField = $("#product-qty");
		productQtyField.val(parseInt(productQtyField.val())+1);
		
	});
	
	$("#decrease").click(function(e){
		
		e.preventDefault();
		var productQtyField = $("#product-qty");
		if (parseInt(productQtyField.val()) > 1){
			productQtyField.val(parseInt(productQtyField.val())-1);
		}
		
	});

}

function productTabs(){
	
	$("#fragment-1").show();
	
	$("#product-tabs").find("li").click(function(e){
		
		e.preventDefault();
		
		//Add Selected Class.
		$(".selected").removeClass("selected");
		$(this).addClass("selected");
		
		var tabUnhide = $(this).find("a").attr("href");
		$(".tab-container").hide();
		$(tabUnhide).show();
	});;
	
}

/* Product Kit Page Price Scan */
function productKitPrice(){
	
	//Do only in the kit page.
	if ($("#kit-items-form").length){
	
		var jSelectedComponents = $( "#kit-components input:checked" );
		
		var flTotal = 0;
		
		// Loop over each component.
		jSelectedComponents.each(
			function( intI ){
				var jThis = $( this );
				var strID = jThis.attr( "id" );
				var jPrice = jThis.next( "input[ name = '" + strID + "_price' ]" );
				
				// Add the price to the total.
				flTotal += parseFloat( jPrice.val() );
				//console.log(flTotal);
			}
		);
		
		$("#product-price").text("$" + flTotal.toFixed(2));
		//Store in hidden field.
		$("#kit_total").val(flTotal.toFixed(2));
		//console.log(flTotal.toFixed(2));
		//updateQtyDiscPrices(flTotal);
		productKitTotalPrice();
	
	}
	
}

function kitComponentInputs(){
	
	//Bind to changes in the inputs.
	var componentsInput = $("#kit-components input");
	
	componentsInput.click(function(){
		
		productKitPrice();
		
	});
	
}

function updateQtyDiscPrices(flTotal) {
	//var jPriceSpan2 = $( "#product-price span span, #product-bottom-price span span" ).text();
	var qtyPrices = $('.qtyPrice');
	var theDiscPrice;
	
	qtyPrices.each( function( intI ) {
		theDiscPrice = flTotal - Math.round( ( flTotal * (  $(this).attr('rel') / 100 ) ) );
		$(this).html( theDiscPrice.toFixed( 2 )  );									
	});				
}

function productPrice(){
	
	var runningTotal = 0;
	var oldPrice = parseInt($("#product-price").text().replace("$", ""));
	
	$("select.required-option").each(function(){
		
		var optionPrice = parseInt($("#optionPrice_"+$(this).val()).val());
		runningTotal = runningTotal + optionPrice;
	});
	
	var newPrice = parseInt($("#running-price").val()) + parseInt(runningTotal);
	
	//Update the price displayed.
	$("#product-price").text("$"+newPrice.toFixed(2))
	
	if (oldPrice != newPrice) {
		$("#product-price").highlightFade({color:'yellow',speed:1000,iterator:'exponential'});
	}
	
	updateQtyDiscPrices(newPrice);
	
}

function helpMeDecideModalFunc(ahelp){
	
	optionID = ahelp.parent("li").parent("ul").parent(".jqTransformSelectWrapper").find("select").attr("rel");
	
	//Get the position of the help me link.
	var rePosition = ahelp.parent("li").parent("ul").parent(".jqTransformSelectWrapper").position();
	
	//Change the background color.
	//ahelp.parent("li").css("background-color","#DBE7F3");
	
	//console.log(rePosition);
	//console.log(optionID);
	
	//First reset everything back.
	//$("#help-me-decide-box").css("margin-left","322px");
	
	//Re-position the arrow.
	$("#help-me-arrow").css({
		"top": rePosition.top+64 + "px",
		"left": rePosition.left + "px"}).show();
	
	//Display the new box.
	$("#help-me-decide-box").fadeIn("fast",function(){
		
		$(this).find("#help-me-content").load("/help/help_me_decide.cfm",
			{
				product_id: $("#productIDField").val(),
				option_id: optionID
			},function(){
				
				//Place the title.
				var helpTitle = $("#help-me-option-name").text();
				//console.log(helpTitle);
				$("#help-me-decide-title-top").text(helpTitle);
				$("#help-me-option-name").hide();
				
				/*console.log($(this).width());
				var diffIncreased = $(this).width() - 400;
				console.log(diffIncreased);
				var newMarginLeft = parseInt($(this).css("margin-left")) - diffIncreased;
				$(this).css("margin-left",newMarginLeft);
				console.log(newMarginLeft);*/
				
			}
		);
		
		return;
		
	});
	
	/*var jLink = ahelp;
	var jModal = $( "#help-me-decide-modal" );
	var jModalLoader = jModal.find( "#modal-loader" );
	var jModalContent = jModal.find( "#modal-content" );
	
	window.jModalSelect = ahelp.parent("li").parent("ul").parent(".jqTransformSelectWrapper").find("select");
	
	// Toggle the content and loader.
	jModalLoader.show();
	jModalContent.hide();
	
	// Show the modal window.
	jModal.modal();
	
	// Load the help me decide url.
	jModalContent.load(
		"/help/help_me_decide.cfm", 
		{
			product_id: $( "#productIDField" ).val(),
			option_id: optionID
		},
		function(){
			jModalLoader.fadeOut( 500 );
			jModalContent.fadeIn( 250 );
		}
		);*/
	
	//Ends here
	
	/*$( "a.help-me-decide-pd" )
				.attr( "href", "javascript:void( 0 )" )
				.css( "display", "inline" )
				.click(
					function( objEvent ){
						var jLink = $( this );
						var jModal = $( "#help-me-decide-modal" );
						var jModalLoader = jModal.find( "#modal-loader" );
						var jModalContent = jModal.find( "#modal-content" );
						
						// Globally create the modal select box.
						window.jModalSelect = jLink.parent().prev().find("select");
								
						// Toggle the content and loader.
						jModalLoader.show();
						jModalContent.hide();
						
						// Show the modal window.
						jModal.modal();
						
						// Load the help me decide url.
						jModalContent.load(
							"/help/help_me_decide.cfm", 
							{
								product_id: $( "#productIDField" ).val(),
								option_id: jLink.attr( "rel" )
							},
							function(){
								jModalLoader.fadeOut( 500 );
								jModalContent.fadeIn( 250 );
							}
							);
						
						// Prevent default.
						objEvent.preventDefault();
						return false;
					}
				);		
			}
		);*/
}

function detectChangeOption(){
	
	$(".product-option-link").click(function(e){
			
			if ( $(this).attr("rel") == "help-me"){
				e.preventDefault();
			}
			else{
				//Check all the prices again.
				if ($("#kit-items-form").length){
					productKitTotalPrice();
				}
				else{
					productPrice();
				}
			}
	});
	
}

function detectChangeIE6(){
	
	if ( $.browser.msie ) {
			if ($.browser.version == 6){
				$(".hide-ie-6").remove();
			}
	}
	
	$(".required-option").change(function(){
		
		//Check all the prices again.
		if ($("#kit-items-form").length){
			productKitTotalPrice();
		}
		else{
			productPrice();
		}
		
	});
	
}

function productKitTotalPrice(){
	var kitTotal = parseFloat($("#kit_total").val());
	var runningTotal = 0;
	var oldPrice = parseInt($("#product-price").text().replace("$", ""));
	
	$("select.required-option").each(function(){
		
		var optionPrice = parseInt($("#optionPrice_"+$(this).val()).val());
		runningTotal = runningTotal + optionPrice;
		//console.log(runningTotal);
		
	});
	
	var newPrice = parseInt(kitTotal) + parseInt(runningTotal);
	
	//Update the price displayed.
	$("#product-price").text("$"+newPrice.toFixed(2));
	
	if (oldPrice != newPrice) {
		$("#product-price").highlightFade({color:'yellow',speed:1000,iterator:'exponential'});
	}
	
	updateQtyDiscPrices(newPrice);
}

function optionsValidation(){
	
	//Get the unselected options.
	var selectElements = $("select.required-option");
	var containsError = false;
	
	//See what the selected value is.
	selectElements.each(function(){
		
		var relSelection = $(this).attr("rel");
		var selectName = $(this).attr("name");
		var selectionMade = $(this).find("option");
		
		selectionMade.each(function(){
			
			//Check to see if this is the selection made.
			if($(this).attr("selected") == "selected"){
			
				var selectionValue = $(this).val();
				
				//Make sure it's a valid selection.
				var unselectedOptions = $(".unselectedOptions");
				unselectedOptions.each(function(){
					
					if ( selectionValue == $(this).val() ){
					
						//Grab the error div.
						$(".option-alert[rel='"+selectName+"']").show();
						containsError = true;
					
					}
					else{
												
						//$(".option-alert[rel='"+selectName+"']").hide();
						
					}
					
					
				});
				
			}
			
		});
		
	});
	
	//Submit Only if there are no errors.
	if (containsError == false){
	
		if ($("#kit-items-form").length){
			var form2 = $("#kit-items-form");
			var form1 = $("#product-options-form");
			form2.trigger("submit");
		}
		else{
			$("#product-options-form").trigger("submit");
		}
	
	}
	else{
		
		//Re-check validation.
		$(".product-option-link").click(function(){
			//See what the selected value is.
			var relValue = $(this).attr("rel");
			var selEl = $(this).parent("li").parent("ul").parent(".jqTransformSelectWrapper");
			var newSelectionMade = selEl.find("option[value='"+relValue+"']");
			var newSelectionValue = newSelectionMade.val();
			var selectName = $(this).parent("li").parent("ul").parent(".jqTransformSelectWrapper").find("select").attr("name");
			//Check to see if this is the selection made.
			//Make sure it's a valid selection.
			var unselectedOptions = $(".unselectedOptions");	
				
			unselectedOptions.each(function(){
				
				if ( newSelectionValue == $(this).val() ){
				
					//Grab the error div.
					$(".option-alert[rel='"+selectName+"']").show();
					containsError = true;
				
				}
				else{
					
					$(".option-alert[rel='"+selectName+"']").hide();
					
				}
				
				
			});
			
		});
		
		//IE6 re-check validation.
		var requiredSelect = $(".required-option");
		
		requiredSelect.change(function(){
			var currentSelectName = $(this).attr("name");
			var newSelectionValue = $(this).val();
			var unselectedOptions = $(".unselectedOptions");
			
			unselectedOptions.each(function(){
				
				if ( newSelectionValue == $(this).val() ){
					
					$(".option-alert[rel='"+currentSelectName+"']").show();
					containsError = true;
						
				}
				else{
					$(".option-alert[rel='"+currentSelectName+"']").hide();
				}
				
			});
			
		});
		
	}
	
}


/* Add to Cart */
function addToCart(){
	
	//Mortise Lock page submit.
	$("#mortise-add-to-cart").click(function(e){
		
		e.preventDefault();
		var productQTY = $("#product-qty").val();
		//Clone out the qty to the actual form.
		$("#qtyInput").val(productQTY);
		
		$("#orderForm").trigger("submit");
		
	});
	
	//Other pages.
	$("#add-to-cart").click(function(e){
		
		e.preventDefault();
		
		var productQTY = $("#product-qty").val();
		
		//Clone out the qty to the form.
		$("#qtyInput").val(productQTY);
		
		//Merge the kit items form with the main submission form.
		if ($("#kit-items-form").length){
			//Merge the two forms.
			var form2 = $("#kit-items-form");
			var form1 = $("#product-options-form");
			
			$("#qtyInputDup").val($("#qtyInput").val());
			optionsValidation();
			//form2.trigger("submit");
			
			
		}
		else{
			optionsValidation();
			//$("#product-options-form").trigger("submit");
		}		
	});
}


/*Display helpers */
function addLastLiClass(){
	
	//$(".jqTransformSelectWrapper").show();
	
}

function scrollToDept() {
	var links = $("a.scroll-to-dept");
	
	links.click(
		function(e) {
			e.preventDefault();
			$(document).scrollTo( $(this).attr("href"), 800 );	
		}
	);

}

// I will attempt to preselect options if an item is passed in through the url
function preSelectOptions() {
	var optionItem = $.getUrlVar("optionItemID");
	
	setTimeout(function() {
		$("a[rel=" + optionItem + "]").click();
	}, 500);
}

/* ================
   Document Ready 
================== */


$(document).ready(function(){

	$("document").ajaxStart(function(){
		
		ajaxTransaction = null;
		
		if (ajaxTransaction){
			return;
		}
		
	});
	
	//Search form helper for IE6.
	$("#search-form").submit(function(event){
		if ($(".suggest-box-selected").length) {
			event.preventDefault();
			prodLoc = $("li.suggest-box-selected > a").attr("href");
			window.location = prodLoc;
		}
	});
	
	// when user removes focus close the autosuggest
	$(document).click(function(e) {
		var target = e.target;
		
		if ($(target).attr("id") == "search"){
		}
		else if( !$(target).closest('.search-form').size() && !$(target).closest('#suggest-box').size() ) {
			
			$('#auto-sug').hide();
			
			var search = $("#search");
			var elementName = "search";
			
			if (search.val() == ""){
				$("label[for='"+elementName+"']").show();
				$("#searchBox").removeClass("searchBox-selected");
				$("#gray").removeClass("gray-selected");
				$("#searchSubmit").removeClass("active");
				search.removeClass("active");
			}
			else{
				$("#searchBox").removeClass("searchBox-selected");
				$("#gray").removeClass("gray-selected");
				$("#searchSubmit").removeClass("active");
				search.removeClass("active");
			}
		}
	});
	
	//Clear out the help text.
	$("#gray").val("");
	
	brandScroller();
	search();
	//autoComplete();
	//ajaxErrorHandler();
	brandsHover();
	categoriesHover();
	referenceDocs();
	detailsMenu();
	productQTY();
	productTabs();
	productKitPrice();
	//productPrice();
	//optionsValidation();
	addLastLiClass();
	kitComponentInputs();
	addToCart();
	//closeShip();
	detectChangeIE6();
	scrollToDept();
	preSelectOptions();
});
