// JavaScript Document

if (typeof SophioAjaxCatalog === "undefined") {
SophioAjaxCatalog = {};
}

window.onbeforeunload=confirmBrowseAway;

function confirmBrowseAway()
{
  if (typeof SophioAjaxCatalog.preventPageLeave !== "undefined" && SophioAjaxCatalog.preventPageLeave) {
    return "At this point you are about to leave our catalog page.\n" +
	"Select Cancel if you would like to continue shopping!"
  }
}


if (typeof SophioAjaxCatalog.drillManager === "undefined") {
SophioAjaxCatalog.drillManager= function() {
	return {
			drills:new Array(),
			currentCallId:'',
			addonVars:{ajax:"true",isajax:true}, // vars to be added with every call
			ohighlightMgr:new Object(),
			addDrill:function(oDrill){
				var nLastDrill=this.drills.length;
				this.drills.push(oDrill);
				if (nLastDrill > 0){this.setNextDrill(this.drills[nLastDrill-1],oDrill)} // set next drill
				},
		   setCurrentCallId:function(cId){this.currentCallId=cId;},	
		   getCurrentCallId:function(){return this.currentCallId;},	
		   setNextDrill:function(oCurrentDrill,oNextDrill) {oCurrentDrill.nextDrill=oNextDrill;},
		   setaddonVars:function(ovars){
			   jQuery.extend(this.addonVars,ovars);
			   },
		    getaddonVars:function(){return this.addonVars},
		   disableNextDrills:function(vCurrentDrill) {
			try {
				if (typeof vCurrentDrill ==="number")
				{
					var inArr=vCurrentDrill
				} else {				
				var inArr=jQuery.inArray(vCurrentDrill,this.drills);
				}
				if (inArr>-1) {	
				jQuery.each(this.drills,function(n,drill){
											 if (n>inArr) { drill.disableDrill();}
											 })	;
							}		
			} catch (cerr) {}
			},
			reloadDrill:function(nIndex) {
				if (typeof nIndex==="number")
					try {
						// load drill
						this.drills[nIndex].loadData();
						} catch (cerr){}
				},
			getDrill:function(cDrillMode){
				
				jQuery.each(this.drills,function(n,drill){
											 if (drill.cDrillMode==cDrillMode) { return drill;}
											 })	;
				return false;				
				},
			setupDrills:function(cSelSize){var self=this; jQuery.each(this.drills,function(){this.setup(cSelSize,self)});},	
			setProperty:function(cProperty,cValue){   // sets a property on all drills				
				jQuery.each(this.drills,function(n,drill){												 
											 drill[cProperty]=cValue;
											 })	;				
				},	
			getDrillsValues: function(vCurrentDrill) {		
				try {
					if (typeof vCurrentDrill ==="number")
					{
					  var inArr=vCurrentDrill
					} else {				
					  var inArr=jQuery.inArray(vCurrentDrill,this.drills);
					}						
					var oDrillValues={};
					if (inArr>-1) {	
					jQuery.each(this.drills,function(n,val){
												 if (n<inArr) { jQuery.extend(oDrillValues,eval('({'+val.getValueNamePair()+'})')) }
												 })	;
					}
					// exted current object with addonVars
					return jQuery.extend(oDrillValues,this.addonVars);
			
					} catch (cerr) {}
			}	
		}
	}
}

if (typeof SophioAjaxCatalog.drillDefinitions === "undefined") {
SophioAjaxCatalog.drillDefinitions={};
}

if (typeof SophioAjaxCatalog.drillDefinitions.drillMaster === "undefined") {
SophioAjaxCatalog.drillDefinitions.drillMaster = function() {
	var drillMaster={
		cDrillMode:"MK",  // method of the drill
		isEnabled:false,  
		parentDIV:"",  // where do we creat this drill
		cSelectID:"",  // the id of the select without #
		nextDrill:"",  // next drill object, populated by drill manager object
		parentDIVprefix:"" , // prefix added to enable to have more then one drill on the same page
		cSelectIDprefix:"" , // prefix added to enable to have more then one drill on the same page
		cSelectErrorMessage:"Please select a value first!", // message to display when we attempt to load next drill without selecting a value
		cHoverClass:'ui-state-hover',  // class used for highlighting /focus:add , blur:remove
		cRestoreCaption:'',  // holds the caption before ajax load
		cLoadingMessage:'Loading',  // ajax loading message displayed
		cBusyClass:'busy',  // class when ajax call is undergoing
		cMarkup:'',  // holds the markup of the select to be created, when empty it will be auto created
		cWebVarName:'', // web var to be passed in the ajax call
		cValue:"",  // holds the current value
		cText:"", // holds the current text
		cSize:'1', // size of the select / when 1 its a select menu, when >1 its a list
		lCheckValue:true, // flag to enable/disable value check
		cURL:"ShopForOEParts.epc",  // the url servicing the drills
		cDrillType:"", // drill type Vehicle/Product/Part
		drillManager:{},
		lDisableOnChange:true, //flag to disable the current drill on change / when data is loaded it will be reinabled
		currentCallId:"",
		timeOut:50000, // ajax timeout value / should be increased when getting parts
		oSelectBox:"", // holds the jQueryfiy select box
		getValueNamePair:function(){
			return this.cWebVarName+":'"+this.cValue+"'";
		},
		// sets a unique call id to prevent several calls in the background
		setCurrentCallId:function(cVal){			
			if (typeof this.drillManager.setCurrentCallId==='undefined') {return false;}
			this.currentCallId= this.cDrillMode+":"+String((new Date()).getTime()).replace(/\D/gi,'')
			this.drillManager.setCurrentCallId(this.currentCallId);
		},
		// tests current callid against the the callid stored in the drill manager class
		isCurrentCallValid:function(){
			if (typeof this.drillManager.getCurrentCallId==='undefined') {return true;}			
			return this.drillManager.getCurrentCallId()===this.currentCallId;			
			},
	// call before loading data / used in subclass
		beforeloadData:function(){return true;},
	// disable current drill
		disableDrill:function() {
			// clear the stored values
			this.setValue("");		
			this.setText("");
			// clear and disable the select box
			var oDrill=this.oSelectBox
			.attr("disabled", true)
			.removeOption(/./).blur()
			.find('option:selected')
			// if the first option was selected , remove the selection attribute
			if (oDrill.length>0){
			oDrill.removeAttr("selected");
			}			
		},
	// load ajax data on select
	loadData:function(oCaller) {
			//process any before load options
			this.beforeloadData();
			var self=this;
			// accumulate a json object of query strigns to be sent to server
			var oWebVars={ajax: 'true',isajax: 'true',nooutput:'true'};
			jQuery.extend(oWebVars,eval("({mode:'"+this.cDrillMode+"'})"),this.drillManager.getDrillsValues(this));
			// remove any current data, disable and add a loading message
			this.oSelectBox.removeOption(/./).addClass(this.cBusyClass).addOption("", this.cLoadingMessage);
			// set current call id
			this.setCurrentCallId();
			// get data from server
			jQuery.ajax({
				url: this.cURL,
				data:oWebVars ,
				dataType: "json",
				timeout: this.timeOut,
				success: function(data, status){
							// remove any stored data
							self.oSelectBox.removeOption(/./)
							// test for valid call, and if so add the received data to teh select box							
							if (self.isCurrentCallValid()){
							self.oSelectBox.addOption(data,false);
							}
							// if a caller was passed ( always passed except for drill 1), enable the caller
							if(typeof oCaller!=='undefined'){oCaller.attr("disabled", false).removeClass(self.cHoverClass);};
							// successfull post process call
							self.enableMe(self.oSelectBox);
				},
				error: function(XHR, textStatus, errorThrown){
					// if a caller was passed ( always passed except for drill 1), enable the caller
							if(typeof oCaller!=='undefined'){oCaller.attr("disabled", false).removeClass(self.cHoverClass);};
					// show the error
					self.showError('There was an error getting data from our server.Please try again!');
					self.oSelectBox.removeClass('busy').addOption("",self.cRestoreCaption);
					//alert("ERREUR: " + textStatus);
					//alert("ERREUR: " + errorThrown);
					
				}
			});
			
			//ajaxAddOption(this.cURL,oWebVars,false,function(){self.enableMe(this);});		
		},
		highlight:function(cType,obj) {
			//obj=obj || "#"+this.cSelectID;
			if (cType=='add'){		
			this.oSelectBox.addClass(this.cHoverClass); 		
			if (typeof this.drillManager.ohighlightMgr !=='undefined')  {jQuery(this.drillManager.ohighlightMgr).trigger('highlight',[this.cDrillType]);}
			} else {this.oSelectBox.removeClass(this.cHoverClass)}
		},
	// setup this drill	
		setup:function(cSelSize,drillManager){
				// check if this drill can be html created
				var self=this;
				// dynamic size ( 1 for select box , >1 for listbox)
				this.cSize=(cSelSize?cSelSize:'1');
				// store the drill manager
				this.drillManager=drillManager
				// autogenerate markup if one is not present
				if (this.cMarkup==''){
				this.cMarkup='<select name="'+this.cWebVarName+'" id="'+this.cSelectIDprefix+this.cSelectID+'" class="selectlookup" size="'+
				this.cSize+'"><option value="">'+this.cRestoreCaption+'</option></select>';
				}
				// create your select object
				this.oSelectBox=jQuery(this.cMarkup)
				.attr("disabled", true)
				.appendTo("#"+self.parentDIVprefix+self.parentDIV)
				.bind('focus',function(){self.highlight('add',this);})
				.bind('blur',function(){self.highlight('remove',this);})
				.change(function(){
					// disable current drill
					if (self.lDisableOnChange){
					self.oSelectBox.attr("disabled",true);}
					// set current value and text
					self.setValue(this.value);
					self.setText(this.options[this.selectedIndex].text);	
					// disable and clear subsequent drills
					self.drillManager.disableNextDrills(self);
					// if this value is missign just stop;
					if (self.lCheckValue && this.value=='') {
					self.showError(self.cSelectErrorMessage);
					// enable this drill
					self.oSelectBox.attr("disabled",false);
					this.focus();
					return true;
					}
					if (typeof self.nextDrill ==="object" && typeof self.nextDrill.loadData==="function") {
					self.nextDrill.loadData(self.oSelectBox);
					}
					// call blur on this object to remove highlight
					this.blur();
				  });
		},
		
	// manages the error we get back when no data is available for a drill / could be overritten in subclass	
		showError:function(cErrorMsg){			
				// if this is first time, create the error dialog	
				if (jQuery('#SophioErrorDialog').length==0){	
				jQuery('<div id="SophioErrorDialog" title="Sorry...">\
					   <div style="padding:0.7em; font-size:14px;" class="ui-state-error ui-corner-all">\
					   <span><span style="float: left; margin-right: 0.3em;" class="ui-icon ui-icon-alert"/>\
					   <span class="errorMessage">Currently we do not have parts for the vehicle/product selected!</span></span></div></div>')
						.dialog({
							bgiframe: true,
							modal: true,
							autoOpen: false,
							draggable: false,
							resizable: false ,
							buttons: {
								Ok: function() {
									jQuery(this).dialog('close');
								}
								
							}
						});
				}
				if (typeof cErrorMsg !=='undefined' && cErrorMsg!=='')
				{jQuery('#SophioErrorDialog span.errorMessage').html(cErrorMsg);}
				// show error dialog
				jQuery('#SophioErrorDialog').dialog('open');
				return false;
		},
		
		// called by the drill after a succefull ajax load	
		enableMe:function(oSelect){
			try 
			{				
				
				if (!this.isCurrentCallValid()){
				oSelect.attr("disabled", true).removeClass('busy')
				.addOption("",this.cRestoreCaption);
				return false;
				}
				
				oSelect.attr("disabled", false).removeClass('busy')
				.addOption("",this.cRestoreCaption).focus();

				if (oSelect.find("option").length==1){
				this.showError('Currently we do not have parts for the vehicle/product selected!');
				return false;
				}		
				// if only one item is returned , auto load it and go next
				if (oSelect.find("option").length==2){
				oSelect.val(oSelect.find("option:last").val()).change();
				}
			} catch (cerr){}	
		},
		selectOption:function(cValue) {
			this.oSelectBox.selectOptions(cValue,true);
			},
		addOptionFromValue:function() {
			this.oSelectBox.addOption(this.getValue(),this.getText());
			},				
		// setter, getter functions
		setText:function(cVal){this.cText=cVal;},
		getText:function(){return this.cText;},
		setValue:function(cVal){this.cValue=cVal;},
		getValue:function(){return this.cValue;}
	  };
	  return drillMaster;
	};
};




if (typeof SophioAjaxCatalog.drillDefinitions.drillMake === "undefined") {
SophioAjaxCatalog.drillDefinitions.drillMake=function(){
	var drillMake=new SophioAjaxCatalog.drillDefinitions.drillMaster();
	drillMake.cDrillMode="MK";
	drillMake.isEnabled=false;
	drillMake.parentDIV="make_lookup";
	drillMake.cSelectID="selMakeLookup";
	drillMake.cSelectErrorMessage="Please select a Make First!";
	drillMake.cRestoreCaption='Make(s)';
	drillMake.cLoadingMessage='Loading Makes';
	drillMake.cWebVarName='makeid';
	drillMake.lCheckValue=false; // first drill, do not check value on change
	drillMake.cDrillType="Vehicle";
		return drillMake;
	}
}

if (typeof SophioAjaxCatalog.drillDefinitions.drillYear === "undefined") {
SophioAjaxCatalog.drillDefinitions.drillYear=function(){
	var drillYear=new SophioAjaxCatalog.drillDefinitions.drillMaster();
	drillYear.cDrillMode="YR";
	drillYear.isEnabled=false;
	drillYear.parentDIV="year_lookup";
	drillYear.cSelectID="selYearLookup";
	drillYear.cSelectErrorMessage="Please select a Year First!";
	drillYear.cRestoreCaption='Year(s)';
	drillYear.cLoadingMessage='Loading Years';
	drillYear.cWebVarName='yearid';
	drillYear.cDrillType="Vehicle";
	return drillYear;
	
}}


if (typeof SophioAjaxCatalog.drillDefinitions.drillModel === "undefined") {
SophioAjaxCatalog.drillDefinitions.drillModel=function(){
	var drillModel=new SophioAjaxCatalog.drillDefinitions.drillMaster();
	drillModel.cDrillMode="MD";
	drillModel.isEnabled=false;
	drillModel.parentDIV="model_lookup";
	drillModel.cSelectID="selModelLookup";
	drillModel.cSelectErrorMessage="Please select a Model First!";
	drillModel.cRestoreCaption='Model(s)';
	drillModel.cLoadingMessage='Loading Models';
	drillModel.cWebVarName='modelid';
	drillModel.cDrillType="Vehicle";
	return drillModel;	
}}

if (typeof SophioAjaxCatalog.drillDefinitions.drillTrim === "undefined") {
SophioAjaxCatalog.drillDefinitions.drillTrim=function(){
	var drillTrim=new SophioAjaxCatalog.drillDefinitions.drillMaster();
	drillTrim.cDrillMode="TL";
	drillTrim.isEnabled=false;
	drillTrim.parentDIV="submodel_lookup";
	drillTrim.cSelectID="selSubmodelLookup";
	drillTrim.cSelectErrorMessage="Please select a Trim First!";
	drillTrim.cRestoreCaption='Trim(s)';
	drillTrim.cLoadingMessage='Loading Trims';
	drillTrim.cWebVarName='submodelid';
	drillTrim.cDrillType="Vehicle";
	return drillTrim;	
}}

if (typeof SophioAjaxCatalog.drillDefinitions.drillEngine === "undefined") {
SophioAjaxCatalog.drillDefinitions.drillEngine =function(){
	var drillEngine=new SophioAjaxCatalog.drillDefinitions.drillMaster();
	drillEngine.cDrillMode="EG";
	drillEngine.isEnabled=false;
	drillEngine.parentDIV="engine_lookup";
	drillEngine.cSelectID="selEngineLookup";
	drillEngine.cSelectErrorMessage="Please select an Engine First!";
	drillEngine.cRestoreCaption='Engine(s)';
	drillEngine.cLoadingMessage='Loading Engines';
	drillEngine.cWebVarName='engineid';
	drillEngine.cDrillType="Vehicle";
	return drillEngine;	
}}

if (typeof SophioAjaxCatalog.drillDefinitions.drillSection === "undefined") {
SophioAjaxCatalog.drillDefinitions.drillSection=function(){
	var drillSection=new SophioAjaxCatalog.drillDefinitions.drillMaster();
	drillSection.cDrillMode="SC";
	drillSection.isEnabled=false;
	drillSection.parentDIV="section_lookup";
	drillSection.cSelectID="selSectionLookup";
	drillSection.cSelectErrorMessage="Please select a Vehicle First!";
	drillSection.cRestoreCaption='Section(s)';
	drillSection.cLoadingMessage='Loading Sections';
	drillSection.cWebVarName='sectionid';
	drillSection.cDrillType="Product";
	return drillSection;	
}}


if (typeof SophioAjaxCatalog.drillDefinitions.drillGroup === "undefined") {
SophioAjaxCatalog.drillDefinitions.drillGroup=function(){
	var drillGroup=new SophioAjaxCatalog.drillDefinitions.drillMaster();
	drillGroup.cDrillMode="PG";
	drillGroup.isEnabled=false;
	drillGroup.parentDIV="group_lookup";
	drillGroup.cSelectID="selGroupLookup";
	drillGroup.cSelectErrorMessage="Please select a Section First!";
	drillGroup.cRestoreCaption='Group(s)';
	drillGroup.cLoadingMessage='Loading Groups';
	drillGroup.cWebVarName='catid';
	drillGroup.cDrillType="Product";
	return drillGroup;	
}}

if (typeof SophioAjaxCatalog.drillDefinitions.drillSubgroup === "undefined") {
SophioAjaxCatalog.drillDefinitions.drillSubgroup=function(){
	var drillSubgroup=new SophioAjaxCatalog.drillDefinitions.drillMaster();
	drillSubgroup.cDrillMode="PS";
	drillSubgroup.isEnabled=false;
	drillSubgroup.parentDIV="subgroup_lookup";
	drillSubgroup.cSelectID="selSubgroupLookup";
	drillSubgroup.cSelectErrorMessage="Please select a Product Group First!";
	drillSubgroup.cRestoreCaption='Subgroup(s)';
	drillSubgroup.cLoadingMessage='Loading Subroups';
	drillSubgroup.cWebVarName='subcatid';
	drillSubgroup.cDrillType="Product";
	return drillSubgroup;	
}}

if (typeof SophioAjaxCatalog.drillDefinitions.drillComponent === "undefined") {
SophioAjaxCatalog.drillDefinitions.drillComponent=function(){
	var drillComponent=new SophioAjaxCatalog.drillDefinitions.drillMaster();
	drillComponent.cDrillMode="CP";
	drillComponent.isEnabled=false;
	drillComponent.parentDIV="component_lookup";
	drillComponent.cSelectID="selComponentLookup";
	drillComponent.cSelectErrorMessage="Please select a Product Subgroup First!";
	drillComponent.cRestoreCaption='Component(s)';
	drillComponent.cLoadingMessage='Loading Components';
	drillComponent.cWebVarName='compid';
	drillComponent.cDrillType="Product";
	return drillComponent;	
}}

if (typeof SophioAjaxCatalog.drillDefinitions.drillQualifier === "undefined") {
SophioAjaxCatalog.drillDefinitions.drillQualifier=function(){
	var drillQualifier=new SophioAjaxCatalog.drillDefinitions.drillMaster();
	drillQualifier.cDrillMode="VI";
	drillQualifier.isEnabled=false;
	drillQualifier.parentDIV="qualifier_lookup";
	drillQualifier.cSelectID="selQualifierLookup";
	drillQualifier.cSelectErrorMessage="Please select a Product Component First!";
	drillQualifier.cRestoreCaption='Qualifier(s)';
	drillQualifier.cLoadingMessage='Loading Qualifiers';
	drillQualifier.cWebVarName='qualifierid';
	drillQualifier.cDrillType="Product";
	return drillQualifier;	
}}

if (typeof SophioAjaxCatalog.drillDefinitions.drillPart === "undefined") {
	SophioAjaxCatalog.drillDefinitions.drillPart=function(){
	var drillPart=new SophioAjaxCatalog.drillDefinitions.drillMaster();
	drillPart.cDrillMode="PA";
	drillPart.isEnabled=false;
	drillPart.lCheckValue=false; // first drill, do not check value on change
	drillPart.cDrillType="Part";
	return drillPart;	
}}

if (typeof SophioAjaxCatalog.drillDefinitions.drillCatSelector === "undefined") {
SophioAjaxCatalog.drillDefinitions.drillCatSelector=function(){
	var drillCatSelector=new SophioAjaxCatalog.drillDefinitions.drillMaster();
	drillCatSelector.cDrillMode="CA";
	drillCatSelector.isEnabled=false;
	drillCatSelector.parentDIV="catalog_lookup";
	drillCatSelector.cSelectID="selCatalogSelector";
	drillCatSelector.cSelectErrorMessage="Please select a Catalog First!";
	drillCatSelector.cRestoreCaption='Catalog(s)';
	drillCatSelector.cLoadingMessage='Loading Catalog Types';
	drillCatSelector.cWebVarName='catalog';
	drillCatSelector.cDrillType="Catalog";
	drillCatSelector.lDisableOnChange=false
	
	// setup this drill	
    drillCatSelector.setup=function(cSelSize,drillManager){
				var self=this;
				// dynamic size ( 1 for select box , >1 for listbox)
				this.cSize=(cSelSize?cSelSize:'1');
				// store the drill manager
				this.drillManager=drillManager
				// autogenerate markup if one is not present
				if (this.cMarkup==''){
				this.cMarkup='<select name="'+this.cWebVarName+'" id="'+this.cSelectID+'" class="selectlookup" size="'+
				this.cSize+'"></select>';
				}
				// create your select object
				this.oSelectBox=jQuery(this.cMarkup)
				.appendTo("#"+self.parentDIV)
				.addOption({"OEL":"OE Catalog (Mechanical & Collision)","OEM":"OE Mechanical"})
				.val("OEL")
				.selectmenu({width:300})				
				.change(function(){
					// disable current drill
					if (self.lDisableOnChange){
					self.oSelectBox.attr("disabled",true);}
					// set current value and text
					self.setValue(this.value);
					self.setText(this.options[this.selectedIndex].text);	
					// if this value is missign just stop;
					if (self.lCheckValue && this.value=='') {
					alert(self.cSelectErrorMessage);					
					// enable this drill
					self.oSelectBox.attr("disabled",false);
					this.focus();
					return;
					}								
					jQuery(self).trigger('catalogchanged',[eval('({'+self.getValueNamePair()+'})')]);
					// call blur on this object to remove highlight
					this.blur();
					return true;
				  });
				// trigger catalog load
				this.oSelectBox.change();
				//jQuery(self).trigger('catalogchanged',[eval('({'+self.getValueNamePair()+'})')]);
				
		}
	
	return drillCatSelector;	
}}


				
