/**
 * Parts Direct Configuration
 * 
 * @example PartsDirect["localPath"] + PartsDirect["getModelURL"]
 */
var PartsDirect = {
	animateComponents : false,
	isCommercial : false,
	localPath : "/partsdirect/",
	getModelURL : "getModel!retrieve.pd",
	getPartURL : "getPart!search.pd"
};

/**
 * this function adds all the events related with the max chars on a textarea
 * created by : Sebastian Romero
 */
function initMaxOnTextArea() {
	var textarea = $("textarea");
	var textareaChanged = function(event) {
		if (this.className.indexOf("max_") != -1) {
			var string_message = "Characters left";
			var max_chars = parseInt(this.className.split("max_")[1]);
			var chars_left = Math.abs(max_chars - ($(this).val().length));
			if (chars_left > 0) {
			} else
				$(this).val($(this).val().substr(0, $(this).val().length - 1));
			$($(this).parent().find("small").get(0)).text(
					chars_left + " " + string_message);
		}
	}
	textarea.each( function() {
		if ($(this).parent().find("small").length > 0)
			$(this).addClass(
					"max_"
							+ parseInt($($(this).parent().find("small").get(0))
									.text()));
		$(this).keydown(textareaChanged).keyup(textareaChanged);
		$(this).keydown();
	});

}
/**
 * max Width and Min adjustments for Internet Explorer 6
 * created by : Sebastian Romero
 */
function minMaxinternetExplorer() {
	var num_minWidth = 990;
	var num_maxWidth = 1500;
	if (document.all && !window.XMLHttpRequest) {
		if ($("#HeaderTabs").width() <= num_minWidth)
			$("#page").css( {
				"width" : num_minWidth + "px"
			});
		else if ($("#HeaderTabs").width() >= num_maxWidth + "px")
			$("#page").css( {
				"width" : num_maxWidth + "px"
			});
		else
			$("#page").css( {
				"width" : "100%"
			});
	}
};

/**
 * Inits the login on the Page
 */
function initLogin() {
	$("#a_login")
			.click(
					function(event) {
						var login = '<iframe class="login_iframe" src="login.html" border="0"></iframe>'
						$(document.body).popup( {
							isModal : true,
							html : login,
							fixCenter : true,
							width : 350
						});
					});
}

function liquidCarousel(){
	var liquid = function(){
		var carousels = $("div.wrapper_accordion");
		var num_containerWidth, num_padding, num_itemsCount, num_itemsToDisplay, num_eachMargin;
		carousels.each(function(index, element){
			num_containerWidth = $(element).parent().parent().width();
			num_itemsToDisplay = Math.floor(num_containerWidth / parseInt($(".cont_item", element).css("width")));
			num_padding = (num_containerWidth - (num_itemsToDisplay * parseInt($(".cont_item", element).css("width"))))/2;
			$(".cont_item", element).css("padding", "0px " + num_padding + "px");
		});
	};
	void liquid();
	$(window).resize(liquid); 
}

/**
 * Andres Garcia: Flows the items in the carousel as the page resizes
 * @param {Number} The index of the accordion container
 * @return Void
 */
 
function resizeCarousel(index, element){ 
	
	//The width visible area of a visible item
	var num_containerWidth = $("div.accordion div.ui-accordion-content:visible").width();
	
	//The width of each item
	var num_itemWidth = 187;
	
	//The number of elements in the accordion
	var num_itemsCount = $(element).find("div.cont_item").length;
	
	//The number of elements that actually fits in the space
	var num_itemsToDisplay = Math.floor(num_containerWidth / num_itemWidth);
	
	if(num_itemsToDisplay > num_itemsCount)
		num_itemsToDisplay = num_itemsCount;
	
	var num_finalMargin = num_containerWidth - (num_itemWidth * num_itemsToDisplay);
	
	var num_marginsCount = num_itemsToDisplay * 2;
	var num_eachMargin = num_finalMargin / num_marginsCount;
	
	//Change paddings just if are positive number
	if(num_eachMargin > 0)
		$(element).find("div.cont_item").css("padding", "0px " + num_eachMargin + "px");
	
	//Finally, Remove lines on last items
	setupLastElementInAccordion($(element), num_itemsToDisplay);
}

/**
 * Andres Garcia: Applies a correct behavior for the rollover in the search results
 * @return Void
 */
function applyHoverList(){
	
	var str_hoverColor = "#f3f3f3";
	
	var createHoverList = function(trClassName, siblingType){
		$("table.table_270 tbody tr" + trClassName).hover(
				function(event){
					$(this).css("background-color", str_hoverColor);
					var element = $(this)[siblingType]();
					
					
					try {
						while(element.get(0).className.indexOf("alert") != -1){
							element.css("background-color", str_hoverColor);
							element = element[siblingType]();
						}
					} catch(e){
					}
					
					if(siblingType === "prev")
						element.css("background-color", str_hoverColor);
					
				},
				function(event){
					$(this).css("background-color", "");
					var element = $(this)[siblingType]();
					
					
					try {
						while(element.get(0).className.indexOf("alert") != -1){
							element.css("background-color", "");
							element = element[siblingType]();
							//$(this)[siblingType]().css("background-color", "");
						}
					} catch(e){
					}
					
					if(siblingType === "prev")
						element.css("background-color", "");
					
				}
		);
	}
	
	
	
	
	createHoverList("", "next");
	createHoverList(".alert", "prev");
}
 
/**
 * Gets Query String 
 * @param param String 
 * @return
 */
function getQueryString(param){
	return window.location.href.split(param + "=")[window.location.href.split(param + "=").length - 1].replace(/&.+$/, "")
}
/** 
 * 
 * http://localhost:8080/partsdirect/?userType=loggedUser&siteType=commercial
 * http://localhost:8080/partsdirect/?userType=loggedUser&siteType=consumer
 * http://localhost:8080/partsdirect/?userType=loggedOutUser&siteType=consumer
 * http://localhost:8080/partsdirect/?userType=superAdmin&siteType=commercial
 * http://localhost:8080/partsdirect/?userType=admin&siteType=parts
* register!setup.pd		 
 */
/*function headerStates (){
	var str_userType = (getQueryString("userType").indexOf("http") == -1)?getQueryString("userType"):"loggedUser";
	var str_siteType = (getQueryString("siteType").indexOf("http") == -1)?getQueryString("siteType"):"consumer";
	$("." + str_userType + "." + str_siteType).removeClass("hidden");	
}*/
 
 function displayActionErrorsLiquid() {
	if(typeof(ErrorHandler) != "undefined"){
		ErrorHandler.displayActionErrors = function(){
			ErrorHandler.removeActionErrors();
			MessageHandler.page.removeMessages();
			var str_errorDiv = '<div id="errorWrapper" class="error_message"><div id="actionErrorContainer" class="moduleActionError alert">' + '<div class="actionErrors"></div>' + '</div></div>';
			if($('#subContent').length > 0){
				$('#subContent').prepend(str_errorDiv);
			}else{
				if($(".errorWrapper").size() === 0){
					if($('#content h2').length > 0){
						if($('#storeAvailabilityForm').length == 0){
								$('#content h2:first').after(str_errorDiv);
							}
						else
							$('#storeAvailabilityForm').prepend(str_errorDiv);
					}else{
						if($('#overlayLogin').length > 0){
							$('.loginPopupTitle').after(str_errorDiv);
							$('#errorWrapper').css("margin-left", "10px");
						}	
					}
				}
			}
			for(var i = 0; i < ErrorHandler.actionErrors.length; i++) {
				$('div.actionErrors').append('<p>' + ErrorHandler.actionErrors[i] + '</p>');
			}
			ErrorHandler.actionErrors = [];
		};
		ErrorHandler.displayFieldErrors =  function() {
			ErrorHandler.removeFieldErrors();
			var i = 0;
			var zipCodeId = '_zipCode'; 
			var errorFlagRightStyle = 'errorFlagRight';
			// First create the flag for each fieldset that contains a field error
			for(i = 0; i < ErrorHandler.fieldErrors.length; i++) {
			 	if(!ErrorHandler.fieldErrors[i].fieldset.hasClass('ERROR')) {
					if(ErrorHandler.fieldErrors[i].fieldset.hasClass('errorFlagOnLeft')) {
						ErrorHandler.fieldErrors[i].fieldset.addClass('ERROR').prepend('<div class="errorFlagLeft errorFlag png_fix"><p></p></div>');
					} else {
						if(ErrorHandler.fieldErrors[i].field[0]){
							
						if(zipCodeId == ErrorHandler.fieldErrors[i].field[0].id)
							errorFlagRightStyle = 'errorFlagRightZipCode';
						//Prevent blank messages
						if(ErrorHandler.fieldErrors[i].errorMessage.split(" ").join("") != "")
							ErrorHandler.fieldErrors[i].fieldset.addClass('ERROR').append('<div class=" ' + errorFlagRightStyle + ' errorFlag png_fix"><p></p></div>');
						if(ErrorHandler.fieldErrors[i].field[0].tagName.toLowerCase().indexOf("select") != -1){
							if($("#fldOtherIndustry", $(ErrorHandler.fieldErrors[i].field[0]).parent()).length == 0)
								ErrorHandler.fieldErrors[i].fieldset.find("." + errorFlagRightStyle).css("right", "-165px");
							else 
								ErrorHandler.fieldErrors[i].fieldset.find("." + errorFlagRightStyle).css("right", "-140px");
							$(ErrorHandler.fieldErrors[i].field[0]).change(function(event){
								var field = $(this).parent().find("." + errorFlagRightStyle);
								var shapeIE6 = $(this).parent().find("shape");
								if(this.selectedIndex == 0){
									if(field.length > 0){
										field.css("display", "block");
										$(this).addClass("error");
									}
								} else{
									field.remove();					
									if (navigator.userAgent.toLowerCase().indexOf('msie 6') != -1)
									{
										shapeIE6.remove();		
									}
									
									$(this).removeClass("error");
								}
							});
						}
						
						
					}
					}
				}
			}
			
			// Populate each flag with its messages, highlight the field
			for(i = 0; i < ErrorHandler.fieldErrors.length; i++) {
				// Determine if the flag is on the right or left (default right)
				var errorFlagClass = (ErrorHandler.fieldErrors[i].fieldset.hasClass('errorFlagOnLeft')) ? 'errorFlagLeft' : 'errorFlagRight';
				if(errorFlagRightStyle == 'errorFlagRightZipCode'){
					errorFlagClass = errorFlagRightStyle;
				}

				
				// Add errors messages to the flag
				//if(ErrorHandler.fieldErrors[i].errorMessage != "")
				// Prevent blank messages
				if(ErrorHandler.fieldErrors[i].errorMessage.split(" ").join("") != "")
					ErrorHandler.fieldErrors[i].fieldset.find('div.' + errorFlagClass + ' p').append('<span class="errorMessage">' + ErrorHandler.fieldErrors[i].errorMessage + '</span>');
				// Highlight the field
				if(ErrorHandler.fieldErrors[i].errorMessage.split(" ").join("") != "")
					ErrorHandler.fieldErrors[i].field.addClass('error');

				// Re-position the flag because the height has changed
				var flagHeight = ErrorHandler.fieldErrors[i].fieldset.find('div.' + errorFlagClass).height() + 10;
				if((ErrorHandler.fieldErrors[i].fieldset.height() != 0)){
					ErrorHandler.fieldErrors[i].fieldset.find('div.' + errorFlagClass).css('bottom', ErrorHandler.fieldErrors[i].fieldset.height()/2 - flagHeight/2);
				}else{
					if(!isNaN(ErrorHandler.fieldErrors[i].fieldset.css("height").replace("px", "")))
						ErrorHandler.fieldErrors[i].fieldset.find('div.' + errorFlagClass).css('bottom', Number(ErrorHandler.fieldErrors[i].fieldset.css("height").replace("px", ""))/2 - flagHeight/2);
				}	
				ErrorHandler.posFieldError(ErrorHandler.fieldErrors[i].fieldset);
			}
			//ErrorHandler.overlapCheck();
			
			// Clear the field errors array for next submission
			ErrorHandler.fieldErrors = [];
		};
	}
}

 
/* 
 function displayActionSuccessMessagesLiquid() {
	 if(typeof(MessageHandler) != "undefined"){
		 MessageHandler.page.displayMessageTemplate = function(heading, type){
			//ErrorHandler.removeActionErrors();
			//MessageHandler.page.removeMessages();
			var str_messageDiv = '<div id="messageWrapper"><div id="messageContainer">' + '<p class="confirmation_message"><strong>'+heading+'</strong></p>' + '</div></div>';
			if($('.col_right').length > 0){
				$('.col_right').prepend(str_messageDiv);
			}else{
				$('#content h2').after(str_messageDiv);
			}
			for(i = 0; i < MessageHandler.messages[type].length; i++) {
				$('p.confirmation_message').append('<p>' + MessageHandler.messages[type][i] + '</p>');
			}
			 //ErrorHandler.actionErrors = [];
		}
	}
 } 
*/ 
 
 function errorFieldPosition() {
	 if(typeof(ErrorHandler) != "undefined"){
		 ErrorHandler.posFieldError = function(fieldSet){
			if(fieldSet.find(".errorFlag").hasClass("errorFlagRight") || fieldSet.find(".errorFlag").hasClass("errorFlagRightZipCode") || fieldSet.find(".errorFlag").hasClass("errorFlagLeft")){
				var left = 0;
				fieldSet.find("input, select, textarea").each(function(index, item){
					if(!$(item).prev().hasClass("line_break"))
						left += $(item).width() + 20;
					else {
						if(left == 0)
							left = $(item).width() + 20;
					}
					if(($(item).parent().next().css("float") === "left") && ($(item).parent().css("float") === "left")){
						left = $(item).parent().width() + $(item).width() + 20;
						
					}
					if($(item).parents(".narrowSuggestedModel,.modelSelectSearch").size() > 0)
						left += 85;
					
					if($(item).parents(".end_field").size() > 0){
						if($(item).parents(".end_field:first").width() !== 0)
							left = $(item).parents(".end_field:first").width();
						else
							left = parseInt($(item).parents(".end_field").css("width"));
					}
					
					if($(item).parents(".end_fieldComments").size() > 0){
						if($(item).parents(".end_fieldComments:first").width() !== 0)
							left = $(item).parents(".end_fieldComments:first").width();
						else
							left = parseInt($(item).parents(".end_fieldComments").css("width"));
					}
					
					if(($(item).parents(".stateFld").size() > 0)){
						if((navigator.userAgent.toLowerCase().indexOf('msie') != -1) || (navigator.userAgent.toLowerCase().indexOf('safari') != -1)){
							left += 129;
						}
					}
					
					if(($(item).parents(".passReg").size() > 0) && (navigator.userAgent.toLowerCase().indexOf('msie 6') != -1)){
						left = 520;
					}
					
					if(($(item).parents(".orderConf").size() > 0)){
						left = -232;
					}
					
					if(($(item).parents(".couponFieldset").size() > 0)){
						left = 400;
					}
					
					if(($(item).parents(".verification_popup").size() > 0)){
						$(".verification_popup").find("div.errorFlagRight").css("display", "none");
					}
					
					if($(item).parents(".largeFlagFix").size() > 0){
						$(".largeFlagFix").find("p").css("width", "220px");
						$(".largeFlagFix").find("span").css("width", "220px");						
						$(".largeFlagFix").find(".errorFlag").css("top", "-15px");
						$(".largeFlagFix").find(".errorFlag").css("height", "45px");
						left = 300;
					}
					
					if($(item).parents(".largeFlagFixPass").size() > 0){
						if ($(".largeFlagFixPass span").text().length > 100){
							$(".largeFlagFixPass").find("p").css("width", "250px");
							$(".largeFlagFixPass").find("span").css("width", "250px");						
							$(".largeFlagFixPass").find(".errorFlag").css("top", "-30px");
							$(".largeFlagFixPass").find(".errorFlag").css("height", "59px");
						}
					}

					if(($("div.errorFlag").length > 0) && ($("body.checkoutPayment").length > 0) )
					{
						$(window).scrollTop(0);
					}
					
					($("form.standard fieldset.flagUpdate div.errorFlag").length > 0)
				});

				if(fieldSet.hasClass("errorFlagOnLeft")){
					//fieldSet.find(".errorFlag").css("left", "-245px");
					fieldSet.find(".errorFlag").css("bottom", fieldSet.height()/2+"px");
				}else if(fieldSet.hasClass("errorUploadFile")){
					// special case for input Type File in uploadForm.jsp
					fieldSet.find(".errorFlag").css({
						"left": $(".errorFlag").parent().width()+"px"
					});
				}else{
					fieldSet.find(".errorFlag").css("right", "0px");
					fieldSet.find(".errorFlag").css("left", left + "px");
				}
				
				/*
				 * 
				 */
				if(document.all && !window.XMLHttpRequest){
					fieldSet.find(".errorFlag:last").parent().next().css("display", "none");
					fieldSet.find(".errorFlag:last").parent().next().css("display", "block");
				}
				
				//for purchaser edit in commercial account.
				if($(".purchaserForm").length > 0){
					fieldSet.find(".errorFlag").css("left", "520px");
				}
				
			}
		 }; 
	 }
 }

/**
 * Main Load Function
 */
$( function() {	
	 $(document).ready(function() {
		if(PartsDirect.animateComponents == "false"){
			jQuery.fx.off = false;
		}
		//var searchBox = new SearchBox();
		void displayActionErrorsLiquid();
		//void displayActionSuccessMessagesLiquid();
		void errorFieldPosition();
		void minMaxinternetExplorer();
		void initMaxOnTextArea();
		void initLogin();
		void displayFeaturesPopUp();
		if($(".select ul").length != 0) {
			$(".select ul").scrollContent();
		}
		$("#partSearchForm").validate();
	
		$(".accordion").accordion( {
			autoHeight : false,
			collapsible : true,
			active : 1
		});
		if(!PartsDirect.animateComponents)
			$('.accordion').accordion('option', 'animated', PartsDirect.animateComponents);
		
		if (typeof (ShoppingCart) != "undefined")
			ShoppingCart.init();
		
		//Fix the hover in the lists
		applyHoverList();
		
		$("div.accordion div.ui-accordion-content div.wrapper_accordion").each(resizeCarousel);
		//setAccordeonCategoryShowLink();
		
		
		/**
		 * Temporary Fix For headers 
		 */
		//void headerStates();
		
		if(typeof(RR) != "undefined"){
			RR.jsonCallback = function(recs){
				//alert("some JSON data: " + recs.placements.length);
				
				if(typeof(initCarousels) != "undefined"){
					void initCarousels(recs);
				}
			};
		}
		
		/* HEADER POP UPS */
		var copy="";
		
		setTimeout(function(){	
				$("div.links div#lpvoicebutton").children("a").addClass("headerPhone");
				$("div.links div#lpvoicebutton").children("a").hover(hOver, hOut);
				
				$("div#lpvoicebutton2").children("a").addClass("rightRailPhone");
				$("div#lpvoicebutton2").children("a").hover(hOver, hOut);
				
				$("div.links div#lpchatbutton").children("a").addClass("headerChat");
				$("div.links div#lpchatbutton").children("a").hover(hOver, hOut);
				
				$("div#lpchatbutton2").children("a").addClass("rightRailChat");
				$("div#lpchatbutton2").children("a").hover(hOver, hOut);
		}, 2000);

		/* SEARCH BOX FIELDS INITIAL STATE */
		
		if(($("#fldSBModelNumber").val() == "")){
			$("#fldSBModelNumber").val($("#fldSBModelNumber").attr("title").toLowerCase());
			$("#fldSBModelNumber").css("color", "#CCC");
		}
		if($("#fldSBPartNumber").val() == ""){
			$("#fldSBPartNumber").val($("#fldSBPartNumber").attr("title").toLowerCase());
			$("#fldSBPartNumber").css("color", "#CCC");
		}
		
	 });
});
 
//Andres Garcia: This function removes the right line on the last item [Jira 3190]
 
function setupLastElementInAccordion(container, latestItem){
	$(container).find("div.cont_item").each(
		function(index, element){
			$(element).css("background-repeat", "no-repeat");
			$(element).addClass("lastAccordeonBorder");
			if(index == latestItem - 1)
				$(element).css("background-image", "none");
		}
	);	
}
 
function displayFeaturesPopUp (){
	if($("#new_feutures").size() > 0){
		if(document.cookie.indexOf("newfeatures") == -1)
			$(document.body).popup({fixCenter:"true", isModal:true, isNewFeature:true });
	}
}


 
$(window).resize( function() {
	minMaxinternetExplorer();
	
	$("div.accordion div.ui-accordion-content div.wrapper_accordion").each(resizeCarousel);
});

/* ROLL OVER LINK HEADER */

function hOver(){
	var btn_over = $(this).attr("id");
	var btn_overPos = $(this).offset();
	
		// creates message container
		if ($(".cntr_message").length == 0){
			$("body").append("<div id='box_message'><div class='cntr_message'></div></div>");
		};
		
		// applies copy
		copy = "<p>" + $(this).attr("name") + "</p>";
				
		//Sets Positions
		//Live Person Phone in Header
		if($(this).attr("class") == "headerPhone"){
			$("#box_message").addClass("box_messageTop");
			$("#box_message").css({
				"top": parseInt(btn_overPos.top) + 54 ,
				"left": parseInt(btn_overPos.left) - 50
			});
			var image = $(this).children("img").attr("src");
			if(image.indexOf("voice_reponline.gif") != -1){
				copy ="<p>Call us at " + phoneNumber + ", or click for a representative to call you.</p>";
			}
			else if (image.indexOf("voice_repoffline.gif") != -1)
			{
				copy ="<p>We're sorry - no agents available. Call " + phoneNumber + " for immediate assistance.</p>";
			}
		}
		//Live Person Chat in Header	
		if($(this).attr("class") == "headerChat"){
			$("#box_message").addClass("box_messageTop");
			$("#box_message").css({
				"top": parseInt(btn_overPos.top) + 54 ,
				"left": parseInt(btn_overPos.left) - 50
			});
			var image = $(this).children("img").attr("src");
			if(image.indexOf("chat_reponline.gif") != -1){
				copy ="<p>Need help? Click to chat with a parts representative.</p>";
			}
			else if (image.indexOf("chat_repoffline.gif") != -1)
			{
				copy ="<p>We're sorry - no agents available. Call " + phoneNumber + " for immediate assistance.</p>";
			}
		}
		//Live Person Phone in Right Rail
		if($(this).attr("class") == "rightRailPhone"){
			$("#box_message").addClass("box_messageTop");
			$("#box_message").css({
				"top": parseInt(btn_overPos.top) + 48 ,
				"left": parseInt(btn_overPos.left) - 5
			});
			var image = $(this).children("img").attr("src");
			if(image.indexOf("voice_reponline2.gif") != -1){
				copy ="<p>Call us at " + phoneNumber + ", or click for a representative to call you.</p>";
			}
			else if (image.indexOf("voice_repoffline2.gif") != -1)
			{
				copy ="<p>We're sorry - no agents available. Call " + phoneNumber + " for immediate assistance.</p>";
			}
		}
		//Live Person Chat in Right Rail		
		if($(this).attr("class") == "rightRailChat"){
			$("#box_message").addClass("box_messageTop");
			$("#box_message").css({
				"top": parseInt(btn_overPos.top) + 48 ,
				"left": parseInt(btn_overPos.left) - 5
			});
			var image = $(this).children("img").attr("src");
			if(image.indexOf("chat_reponline2.gif") != -1){
				copy ="<p>Need help? Click to chat with a parts representative.</p>";
			}
			else if (image.indexOf("chat_repoffline2.gif") != -1)
			{
				copy ="<p>We're sorry - no agents available. Call " + phoneNumber + " for immediate assistance.</p>";
			}
		}
		
		if($(this).attr("class") == "topRight"){
			$("#box_message").addClass("box_messageTopRight");
			$("#box_message").css({
				"top": parseInt(btn_overPos.top) + 54 ,
				"left": parseInt(btn_overPos.left) - 120
			});
		}
		
		if($(this).hasClass("estara")){
			$("#box_message").addClass("box_messageTop");
			$("#box_message").css({
				"top": parseInt(btn_overPos.top) + 59 ,
				"left": parseInt(btn_overPos.left) - 2
			});
		}
				
		$(".cntr_message").html(copy);
		$("#box_message").show(80);
};

function hOut(){
	$("#box_message").hide(200);
	$("#box_message").removeClass();
};

function preparePrint() {
	$('#diagramBox').height($('#diagram').height());
	$('#diagramBox').width($('#diagram').width());								
};

/* /ROLL OVER LINK HEADER */

