/**
 * @author Sebastian Romero
 * Andres Garcia: Code refactoring... now the slider changes depending on the number of elements retrieved from the database
 * Laura Martinez: 
 * - Added selector to make "Select a product category" expand the categories list.
 * - Added condition to fix rounded corners.
 * All Functionality related with the Search Box Component
 * @ var search = new SearchBox();
 */

 function SearchBox(){
 	
	/**
	 * Public Methods 
	 */
	this.scope = this;
	var boo_animate = PartsDirect.animateComponents;
	
	/**
	 * Private Methods
	 */
	var init = function(){
		void initSelect();
		void initFields();
		void initSubmitButtons();
		if($("#searchBoxControl").val() === "display")
			$(".collapse").click();
		$(".top_search").css("cursor", "pointer");
		$(".options h4").css("cursor", "pointer");
	};
	
	/**
	 * Initialize the HTML select
	 */
	var initSelect = function(){
		var select = $(".select");
		$(select).find(".options_trail").css({height:"1px"});
		if (document.all) {
			if(!window.XMLHttpRequest)
				$(".select").find(".options").css("height", 20);
			$(select).find(".options_trail").css("position", "relative");
		}
		$(".options h4", select).click(function(){
			if($(select).find(".options_trail").css("height") == "1px"){
				
				
				$(".expand").css("background-position", "-26px 0");
				
				$(select).find(".options_trail").css("display", "block");
				if (boo_animate) {
					$(select).find(".options_trail").css("height", 192);
					$(select).find(".options_trail").show("blind", {}, 500, 
					function(){
						$(select).find(".scroll").css("display", "block");
					});
				} else {
					$(select).find(".options_trail").css({height:"192px"});
					$(select).find(".scroll").css("display", "block");
				}
			} else {
				
				$(".expand").css("background-position", "0 0");
				
				$(select).find(".scroll").css("display", "none");
				if (boo_animate) {
					$(select).find(".options_trail").hide("blind", {}, 500, function(){
						$(select).find(".options_trail").css("height", 1);
						$(select).find(".options_trail").css("display", "none");
					});
				} else {
					$(select).find(".options_trail").css({height:1});
					$(select).find(".options_trail").css("display", "none");
				}
			}
		});
	};
	
	/**
	 * Initialize the TextFields Events
	 */
	var initFields = function(){
		
		$(document).ready(function() {
			/**
			 * Enter Key Handler for search
			 * @param {Object} event
			 */
			 $(".searchbox input#fldSBModelNumber").attr("title", "model number");
			 $(".searchbox input#fldSBPartNumber").attr("title", "part number");
			 $(".searchbox input#fldSBModelNumber").removeAttr("disabled");
			 $(".searchbox input#fldSBPartNumber").removeAttr("disabled");
			$(".searchbox input").keyup(function(event){
				if(event.keyCode === 13){
					switch(this.name){
						case "modelNumber":
							$("#aSearchModel").click();
						break;
						case "partNumber":
							$("#aSearchPart").click();
						break;
					}	
				}
			});
			
			var onFocus = function(event){
				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");
				}
				$(this).css("color", "#000");
				if($(this).val().toLowerCase() == $(this).attr("title").toLowerCase())
					$(this).val("")
			};
			$("#fldSBModelNumber").css("color", "#CCC");
			$("#fldSBPartNumber").css("color", "#CCC");
			$("#fldSBModelNumber").blur(onFocus);
			$("#fldSBPartNumber").blur(onFocus);
			$("#fldSBModelNumber").focus(onFocus);
			$("#fldSBPartNumber").focus(onFocus);
		});
	};
	
	/**
	 * Init the submit buttons
	 */
	var initSubmitButtons = function(){
		var str_modelAction = PartsDirect["localPath"] + PartsDirect["getModelURL"];
		var str_partAction = PartsDirect["localPath"] + PartsDirect["getPartURL"];
		
		$("#aSearchModel").click(function(event){
			event.preventDefault();
			//if($("#fldSBModelNumber").val().toLowerCase() != $("#fldSBModelNumber").attr("title").toLowerCase()){
				$(this).parents("fieldset").validate(function(){
					$("#searchForm").attr("action", str_modelAction);
					var model_label = $("#fldSBModelNumber").attr("name");
					$("#fldSBPartNumber").removeAttr("class");
					$("#fldSBPartNumber").removeAttr("name");
                    if($("#fldSBDivision").length > 0){
                        $("#fldSBDivision").removeAttr("class");
					    $("#fldSBDivision").removeAttr("name");
                    }
					$(document.body).popup({isModal:true, isLoader:true, fixCenter:true});
					$("#searchForm").submit();
					return false;
					//$.get($("#searchForm").attr("action"), {model_label : $("#fldSBModelNumber").val()} );
				});
			//}
		});
		
		$("#aSearchPart").click(function(event){
			event.preventDefault();
			//if ($("#fldSBPartNumber").val().toLowerCase() != $("#fldSBPartNumber").attr("title").toLowerCase()) {
				$(this).parents("fieldset").validate(function(){
					$("#searchForm").attr("action", str_partAction);
					var model_label = $("#fldSBPartNumber").attr("name");
                    $("#fldSBModelNumber").removeAttr("class");
					$("#fldSBModelNumber").removeAttr("name");
					$(document.body).popup({isModal:true, isLoader:true, fixCenter:true});
					$("#searchForm").submit();
					return false;
					//$.get($("#searchForm").attr("action"), {model_label: $("#fldSBPartNumber").val()});
				});
			//}
		});
	};
	
	/**
	 * 
	 * @param {Boolean} show
	 */
	var showHideSearchBox = function(show){
		if (boo_animate) {
			if (show) {
				if(!document.all)
					$("#searchForm").show("blind", {}, 500);
				else 
					$("#searchForm").show();
			}
			else {
				$("#searchForm").hide("blind", {}, 500);
			}
		} else {
			if (show) {
				$("#searchForm").show();
			}
			else {
				$("#searchForm").hide();
			}
			
		}
	};
	
	/*
	$(".collapse").click(function(event){
		var show = ($("#searchForm").css("display") == "none");
		
		$(this).css({"background-position":(!show)?"0 -34px":"0 0"});
		$("#searchForm .error_bubble").remove();;
		showHideSearchBox(show);
	});
	*/
	$(".top_search").unbind('click');
	$(".top_search").click(function(event){
		var show = ($("#searchForm").css("display") == "none");
		// hides select in child account commercial page when search box is expand.
		$(".collapse").css({"background-position":(!show)?"0 -34px":"0 0"});
		if($("#searchForm").css("display") == "block" ){
			$("#itemPerPage1").css({"visibility":"visible"});
		}else{
			$("#itemPerPage1").css({"visibility":"hidden"});
		}		
		
		$("div.bottom_search").css({"background-position":(!show)?"0 bottom":"0 -3px"});
		$("#searchForm .error_bubble").remove();
		showHideSearchBox(show);
	});
	
	init();
	return this;
 };
  
jQuery.fn.scrollContent = function(){
	
	var scope = this;
	var scrollBar;
	var num_scrollAmount = 10;
	this.minHeight = 190;
	/**
	 * 
	 * @param {HtmlObject / JqueryObject} element
	 */
	var scrollContent = function(element){
		var scroll = scope.createScroll();
		scroll.css({
			height:($(element).height() > scope.minHeight)?$(element).height():scope.minHeight,
			/*top:(document.all)?5:24,*/
			bottom:0
		});
		$(element).parent().append(scroll);
		scrollBar = $(".scroll_rail", $(element).parent())
		$(".scroll_rail").css({height:60, "margin-top":107});
		scrollBar.slider();
		scrollBar.slider("option", "orientation", "vertical");
		scrollBar.bind("slidechange", scope.onsliderChange);
		scrollBar.slider("option", "value", 100);
		$(".scroll_top a", $(element).parent()).click(function(event){
			var percent = (($(".scroll_rail", $(element).parent()).slider("option", "value") - num_scrollAmount)<100)?($(".scroll_rail", $(element).parent()).slider("option", "value") + num_scrollAmount):100
			$(".scroll_rail", $(element).parent()).slider("option", "value", percent);
			scope.onsliderChange();
		});
		$(".scroll_bottom a", $(element).parent()).click(function(event){
			var percent = (($(".scroll_rail", $(element).parent()).slider("option", "value") - num_scrollAmount)>0)?($(".scroll_rail", $(element).parent()).slider("option", "value") - num_scrollAmount):0
			$(".scroll_rail", $(element).parent()).slider("option", "value", percent);
			scope.onsliderChange();
		});
	}
	
	//Andres Garcia: Code refactoring... now the slider changes depending on the number of elements retrieved from the database
	this.onsliderChange = function(event, element){
		
		//The height of the elements inside the visor
		var num_optionGroupHeight = $("#scroll_element").height();
		
		//Percent displaced by the slider thumb
		var num_percentDisplaced = -($(".ui-slider-handle").css("bottom").split("%").join("") - 100);
		
		//Height of the visor
		var num_containerHeight = $(".options_trail").height(); //191
		
		//Max. displacements is the height of the content - the height of the visor container + 5 of padding and margin
		var num_maxDisplacement = num_optionGroupHeight - num_containerHeight + 8;
		
		//The final position of the elements in the visor respect the percent of the displacement
		var num_finalPosition = (num_percentDisplaced * num_maxDisplacement) / 100;
		
		//Apply the negative position in order to move upside
		$("#scroll_element").css("top", -num_finalPosition + "px");
		
		//Old Code:
		//var percent =  (parseInt($("a", scrollBar).css("bottom")) - 165) * -1;
		//var percent =  (parseInt($("a", scrollBar).css("bottom")) - 50) * -1;
		
		
		
		//if(percent === 65)percent=0;
		//$("#scroll_element").css({"bottom": percent + "%"});
	};
	
	/**
	 * 
	 * This function creates the html for the scroll bar
	 * @return {JqueryObject} 
	 */
	this.createScroll = function(){
		var div_scroll = $(document.createElement("div"));
		var scroll_content = "<div class=\"scroll_button scroll_rail\">";
		div_scroll.addClass("scroll");
		scroll_content += "</div>";
		scroll_content += "<div class=\"scroll_button scroll_top\">";
		scroll_content += "<a href=\"javascript:;\"></a>"
		scroll_content += "</div>";
		scroll_content += "<div class=\"scroll_button scroll_bottom\">";
		scroll_content += "<a href=\"javascript:;\"></a>";
		scroll_content += "</div>";
		div_scroll.html(scroll_content);
		return div_scroll;					
	};
	/**
	 * Constructor Call
	 */
    this.each(function(){
        scrollContent(this);
    });
	return this;
}
