
/** DLCTRComponent Class
 * USE: Update dependent select boxes based on user selection and
        results from Ajax calls

        This is patterned after the MMYO Component
 *
 * NOTES:
 * 1. The ajax functionality is not defined as a privileged method in order to keep it loosely
 *  coupled from the rest of the functionality as there is no need for it to be exposed to private
 *  variables
 *
 */
function DLCTRComponent(){

	/**
		DLCTR Component Static Variables
	*/
	MILES_ID = 'DLR:miles';
	ZIPCODE_ID = 'DLR:zipcode';
	CITY_ID = 'DLR:city';
	STATE_ID = 'DLR:state';
	ZIPDIV_ID = 'searchByZip';
	CITYSTATEDIV_ID = 'searchByCityState';
	FINDSTORES_ID = "DLR:findLocations";
	FINDTIRESTOP_ID = "DLRLOCATION:findTiresTop";
	FINDTIRESBOTTOM_ID = "DLRLOCATION:findTiresBottom";	
	SEARCHAGAIN_ID = "DLR:searchAgain";
	CITYSTATE_SEARCH_TYPE = "CityState";
	ZIP_SEARCH_TYPE = "Zipcode";
	NA_SEARCH_VALUE = "N/A";
	NO_STATE_SELECTION = "State";
	LOCATIONSEARCHPANEL_ID = "DLR:locationSearch";
	DEALER_GROUP = "dealerGroup"
	
	//empty content for dealer search results; used to clear results when landing page
	//redisplayed via back button, bread crumb navigation, etc.
	DEFAULT_CHOOSEALOCATION_CONTENTS = '<div id="chooseALocation"></div>';
	
	//YMMO ids used to add parameters to findTires button	
	YEARS_ID = 'MMYO:years';
	MAKES_ID = 'MMYO:makes';
	MODELS_ID = 'MMYO:models';
	OPTIONS_ID = 'MMYO:options';
	

	//maintain the conversation id between remoting calls
	var conId = null;
	
	// The user selected dealer
	var selectedDealer = null;

	//Variables for the preservation of the current state of the dropdown lists and their selections
	//These are used to save the original state of the dropdowns before they are updated by the Seam
	//Remoting calls.  The onChange event handler for the findTires button restores these values
	//into the DOM before firing the search, in order for the DOM to be in the correct state if the
	//user hits the back button.
	var currentRadiusMiles = null;
	var currentZipCode = null;
	var currentCity = null;
	var currentState = null;
		
	DEBUG = false ;

	this.debug = function(debugMessage) {
	//Simple debug message function that uses alerts.  Controlled by setting DEBUG variable to
	//either true to activate debug, or false to deactive debug.
		if (DEBUG) {
			alert(debugMessage);
		}
	}

	this.init = function(pageConversationId){
		this.debug("DLCTR.init() called");
		this.conId = pageConversationId;	
	}
	
	this.reset = function() {
	     // If we have already performed a location search; reset -- click the "Start new search" link
	     var ele = document.getElementById("DLRLOCATION:newSearchLink");
	     if (ele) {
	     	ele.onclick();
	     }
	}
	
	/**
	 * This function is invoked during the page load to match the DLCTR values in 
	 * the DOM to the correct values in the Seam DealerLocaterBean and to set the
	 * dealer locater search display state properly. 
	 */
	this.synchronize = function(){
		var locationSearchPanel = document.getElementById("DLR:locationSearch");
		if (locationSearchPanel) {
			locationSearchPanel.style.display = "block";
		}
		//Note that reinitializeCityStateDropdowns() makes an
		// A4J call to reset the state of the DealerLocaterBean		
		this.reinitializeCityStateDropdowns();
		this.reinitializeZipCodeSearch();
		this.showCityStateSearch();
		this.resetLocationResultsDisplay();
	}
	
	this.reinitializeZipCodeSearch = function() {
		var defaultZipCodeMsg = document.getElementById("label.dlctrDefaultZipCodeValue");
		var defaultZipCodeValue = null;
		if (defaultZipCodeMsg) {
			defaultZipCodeValue = defaultZipCodeMsg.innerHTML;
			this.debug("got default zipCodeValue; value = " + defaultZipCodeValue);
		}
		var ele = document.getElementById(ZIPCODE_ID);
		if (ele) {
				ele.value = defaultZipCodeValue;
		}
		var ele = document.getElementById(MILES_ID);
		if (ele) {
				ele.selectedIndex = 0;
		}	
	}
	
	this.initZipCode = function(zipval) {
	
		var ele = document.getElementById(ZIPCODE_ID);
		if (ele) {
			if ((ele.value == null) || (ele.value.length == 0)) {
				ele.value = zipval;
			}
		}
	
	}
	
	this.showZipSearch = function(){
		var zipDiv = document.getElementById(ZIPDIV_ID);
		var cityStateDiv = document.getElementById(CITYSTATEDIV_ID);
		
		
		zipDiv.style.display = "block";
		cityStateDiv.style.display = "none";		
	}
	this.showCityStateSearch = function(){
		var zipDiv = document.getElementById(ZIPDIV_ID);
		var cityStateDiv = document.getElementById(CITYSTATEDIV_ID);
		
		zipDiv.style.display = "none";
		cityStateDiv.style.display = "block";		
	}
	
	this.enableFindTires = function() {
		var topButton = document.getElementById(FINDTIRESTOP_ID);
		var bottomButton = document.getElementById(FINDTIRESBOTTOM_ID);		
				
		topButton.style.display = "block";
		bottomButton.style.display = "block";
	}
	
	this.isFindTiresEnabled = function() {
		var topButton = document.getElementById(FINDTIRESTOP_ID);
		return ("block" == topButton.style.display);
	}
	
	this.getSearchType = function() {
		var elem = document.getElementById(CITYSTATEDIV_ID);
		if (elem) {
			if (elem.style.display == "none") {
				return ZIP_SEARCH_TYPE;
			}
		}
		return CITYSTATE_SEARCH_TYPE;
	}
	
	this.getZip = function() {
		if (this.getSearchType() == CITYSTATE_SEARCH_TYPE) return  NA_SEARCH_VALUE;
		var zipcode = document.getElementById(ZIPCODE_ID);		
		return zipcode.value;
	}
	this.getMiles = function() {
		if (this.getSearchType() == CITYSTATE_SEARCH_TYPE) return 0;
		var miles = document.getElementById(MILES_ID);
		return parseInt(miles.value);
	}	
	this.getCity = function() {
		if (this.getSearchType() == ZIP_SEARCH_TYPE) return NA_SEARCH_VALUE;
		var city = document.getElementById(CITY_ID);
		return city.value;
	}
	this.getState = function() {
		if (this.getSearchType() == ZIP_SEARCH_TYPE) return  NA_SEARCH_VALUE;
		var state = document.getElementById(STATE_ID);
		return state.value;
	}
	
	this.validateShowLocationsButton = function() {
	  var elem;

	  if (this.getSearchType() == CITYSTATE_SEARCH_TYPE) {


		elem = document.getElementById(STATE_ID);
		if ((elem == null) || (elem.selectedIndex == 0)) {
			var errorLabel = document.getElementById('label.dlctrNoStateErrorMessage' );
			alert(errorLabel.innerHTML) ;
			return false;
		}
		elem = document.getElementById(CITY_ID);
		if ((elem == null) || (elem.selectedIndex == 0)) {
			var errorLabel = document.getElementById('label.dlctrNoCityErrorMessage' );
			alert(errorLabel.innerHTML) ;
			return false;
		}
	  } else if (this.getSearchType() == ZIP_SEARCH_TYPE) {
	  	elem = document.getElementById(ZIPCODE_ID);
		if ((elem == null) || (elem.value == null)  || (elem.value.length == 0)) {
		 	var errorLabel = document.getElementById('label.dlctrNoZipErrorMessage' );
			alert(errorLabel.innerHTML) ;
			return false;
		}
			
		reZip = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
	    if (!reZip.test(elem.value)) {
		 	  var errorLabel = document.getElementById('label.dlctrInvalidZipErrorMessage' );
			  alert(errorLabel.innerHTML) ;
	          return false;
	    }
	  } 
	  return true;
	}

	
	this.updateCity = function(cityList) {
		this.debug("Start updateCity; remote callback, cid = " + Seam.Remoting.getContext().getConversationId());
		var selectbox = document.getElementById(CITY_ID);
		selectbox.options.length = 1;

		//Handle case where only one item has been returned
		//Set to the current value
		if (cityList.length == 1){

			selectbox.options[1] = new Option(cityList[0],cityList[0]);
			selectbox.selectedIndex = 1;

		} else {
			//More than one returned - update as normal
			for (var i = 0;i<cityList.length;i=i+1)
			{
				selectbox.options[i+1] = new Option(cityList[i],cityList[i]);
			}
		}	
		
		//enable the select lists that were disabled at the start of the remote call
		this.enableSelections();
		if (typeof ymmoComponent != "undefined" && ymmoComponent) {
			ymmoComponent.enableYMMO("option");
		}
	}
	
	this.updateSearchOptions = function(successFlag) {
		this.debug("Start updateSearchOptions, cid = " + Seam.Remoting.getContext().getConversationId() );
		
		//enable selections that were disabled prior to the remoting call
		this.enableSelections();
		if (typeof ymmoComponent != "undefined" && ymmoComponent) {
			ymmoComponent.enableYMMO("option");
		}
	}
	
	this.rewriteButtonHandler = function(button) {
		this.debug("DLCTR.updateSearchOptions; original onClick = " + button.onclick);
		//get function text and strip off function wrappings and closing brace
		var handlerScript = button.onclick.toString();
		handlerScript = handlerScript.replace(/[^{]+{/,"");
		handlerScript = handlerScript.substring(0, handlerScript.length-1);
		//find and replace the cid; add a bogus parameter (foo) to contain the old cid
		//not changing the cid here; it is just a good reference point to add the other params
		//to the URL
		var cidIndex = handlerScript.indexOf("cid=");
		var newHandlerScript = handlerScript.substring(0, cidIndex+4);
		newHandlerScript += this.conId;
		//add selected MMYO as parameters
		newHandlerScript += "&sYear=";
		newHandlerScript += encodeURIComponent(document.getElementById(YEARS_ID)[document.getElementById(YEARS_ID).selectedIndex].value);
		newHandlerScript += "&sMake=";
		newHandlerScript += encodeURIComponent(document.getElementById(MAKES_ID)[document.getElementById(MAKES_ID).selectedIndex].value);
		newHandlerScript += "&sModel=";
		newHandlerScript += encodeURIComponent(document.getElementById(MODELS_ID)[document.getElementById(MODELS_ID).selectedIndex].value);
		newHandlerScript += "&sOptions=";
		newHandlerScript += encodeURIComponent(document.getElementById(OPTIONS_ID)[document.getElementById(OPTIONS_ID).selectedIndex].value);
		newHandlerScript += "&foo=";
		newHandlerScript += handlerScript.substring(cidIndex+4);
		//construct a new function ptr with our updated code
		button.onclick = new Function(newHandlerScript);
		this.debug("DLCTR.setSelectedDealer; new handler = " + button.onclick);
	}
	
	/**
	 * Reset the HTML content for the Dealer Location Results panel; avoid A4J roundtrip
	 */
	this.resetLocationResultsDisplay = function() {
		document.getElementById("DLRLOCATION:locationResults").innerHTML = DEFAULT_CHOOSEALOCATION_CONTENTS;
	}
	
	/**
	 * reset the state of the city/state dropdowns to the original settings
	 */
	this.reinitializeCityStateDropdowns = function() {
		var lsElem = document.getElementById(CITYSTATEDIV_ID);
		if (lsElem == null) {
		     // If we have already performed a location search; reset -- emulate click of the "Start new search" link
		     var ele = document.getElementById("DLRLOCATION:newSearchLink");
		     if (ele) {
		        this.debug("DLCTR: Emulate new location search click");
				//Note that this onclick triggers an A4J call to the server that reinitializes the
				//DealerLocater backing bean.
		     	ele.onclick();
		     }
		} else {
			   var ele = document.getElementById(STATE_ID);
			   if (ele) {
					ele.selectedIndex = 0;
			   }
			   ele = document.getElementById(CITY_ID);
			   if (ele) {
			   	   	ele.options.length = 1;
					ele.selectedIndex = 0;   
			   }
		}		
	}
	
	this.disableLocationRadioButtons = function() {
		var dealerGroup = document.getElementsByName(DEALER_GROUP); 
		for (var j = 0; j < dealerGroup.length; j++) {
			dealerGroup[j].disabled = true;
		}
	}

	this.disableSelections = function() {
		document.getElementById(STATE_ID).disabled = true;
		document.getElementById(CITY_ID).disabled = true;
		document.getElementById(MILES_ID).disabled = true;
		document.getElementById(ZIPCODE_ID).disabled = true;
	}
	
	this.enableSelections = function(level) {
		if (level == "state/miles") {
			document.getElementById(STATE_ID).disabled = false;
			document.getElementById(MILES_ID).disabled = false;
			
			//determine if a value city list is presently selected, if so enable it
			var citySelect = document.getElementById(CITY_ID);
			if (citySelect.selectedIndex > 0) {
				citySelect.disabled = false;
			}
			//just enable the zip entry, as a radius is default selected
			document.getElementById(ZIPCODE_ID).disabled = false;	
			//alert("after DLR state/miles enable");	
		} else {
			//check for case where a previous function call (e.g. showLocationSearchPanel())
			//has already set the visibility of state & city; this is necessary due to the order
			//in which A4J fires the "oncomplete" callback from a component prior to firing the
			//the "onstop" callback used to remove the transparent overlay
			if (document.getElementById(STATE_ID).disabled) {
				document.getElementById(STATE_ID).disabled = false;
				document.getElementById(CITY_ID).disabled = false;
			}
			document.getElementById(MILES_ID).disabled = false;
			document.getElementById(ZIPCODE_ID).disabled = false;
		}
	}
	
} //End DLCTRComponent




/** DLCTRComponent.remoteUpdate -- AJAX Calling Method
 * Additional AJAX method on the DLCTRComponent class - Defined outside of the class constructor as it will never require access
 * to any private variables within the DLCTRComponent class.
 *
 */
DLCTRComponent.prototype.remoteUpdate = function(level, milesSelection, zipcodeSelection, citySelection, stateSelection){

	this.debug( "remoteUpdate:"+ level + " - cid = " + this.conId );
	
    if (level == "state") {
    
        // Do not perform a remote update if the user has selected the "No Selection" state value
        // Fixes JIRA issue: MNABJ-15 
        if (stateSelection.length > 2) {
            // Update city list and return..
            var selectbox = document.getElementById(CITY_ID);
			selectbox.options.length = 1;
			selectbox.selectedIndex = 0;
        	return;
        } 
		this.searchType = CITYSTATE_SEARCH_TYPE;

		//disable all the selections
		this.disableSelections();
		if (typeof ymmoComponent != "undefined" && ymmoComponent) {
			ymmoComponent.disableYMMO();
		}
		
		//Make the remote call to get data for the cities list		
		this.debug("DLCTRComponent.remoteUpdate: Before getCitiesForDealer call - stateSelection = " + stateSelection 
			+ "; conversationId = " + this.conId);
		Seam.Remoting.getContext().setConversationId(this.conId);
		 Seam.Component.getInstance("dlctrInformation").getCitiesForDealer( stateSelection, this.updateCity.bindObj(dlctrComponent));

	} else if (level == "city") {
		this.searchType = CITYSTATE_SEARCH_TYPE;
		
		//disable all the selections
		this.disableSelections();
		if (typeof ymmoComponent != "undefined" && ymmoComponent) {
			ymmoComponent.disableYMMO();
		}
		//alert("city - after disable");

		//Make the remote call to set the search selections into the backing bean		
		this.debug("DLCTRComponent.remoteUpdate: Before setSearchSelections call - milesSelection = " + milesSelection 
			+ " zipCodeSelection = " + zipcodeSelection + " citySelection = " + citySelection + "stateSelection = " + stateSelection 
			+ "; conversationId = " + this.conId);
		Seam.Remoting.getContext().setConversationId(this.conId);
	     Seam.Component.getInstance("dlctrInformation").setSearchSelections( milesSelection, zipcodeSelection, citySelection, stateSelection, this.updateSearchOptions.bindObj(dlctrComponent));

	} 
	else if (level == "zipcode") {
		this.searchType = ZIP_SEARCH_TYPE;
		
		//disable all the selections
		this.disableSelections();
		if (typeof ymmoComponent != "undefined" && ymmoComponent) {
			ymmoComponent.disableYMMO();
		}

		//Make the remote call to set the search selections into the backing bean		
		this.debug("DLCTRComponent.remoteUpdate: Before setSearchSelections call - milesSelection = " + milesSelection 
			+ " zipcodeSelection = " + zipcodeSelection + " citySelection = " + citySelection + "stateSelection = " + stateSelection 
			+ "; conversationId = " + this.conId);
		Seam.Remoting.getContext().setConversationId(this.conId);
	     Seam.Component.getInstance("dlctrInformation").setSearchSelections( milesSelection, zipcodeSelection, citySelection, stateSelection, this.updateSearchOptions.bindObj(dlctrComponent));
	} 
}

/** DLCTRComponent.setSelectedDealer -- AJAX Calling Method
 * Additional AJAX method on the DLCTRComponent class - Defined outside of the class constructor as it will never require access
 * to any private variables within the DLCTRComponent class.
 *
 */
DLCTRComponent.prototype.setSelectedDealer = function(shipTo, addressLine1, addressLine2, city, state, zip){

	this.debug("Start DLCTR.setSelectedDealer, cid = " + this.conId );

	//rewrite the onclick handler for the top findTires button, adding the
	//selected values from the select lists as parameters
	var ele = document.getElementById("DLRLOCATION:findTiresTop");
	if( ele ) {
		this.rewriteButtonHandler(ele);
	} else {
		this.debug("updateSearchOptions; top button not found in DOM");
	}	
	
	//rewrite the onclick handler for the top findTires button, adding the
	//selected values from the select lists as parameters
	ele = document.getElementById("DLRLOCATION:findTiresBottom");
	if( ele ) {
		this.rewriteButtonHandler(ele);
	} else {
		this.debug("updateSearchOptions; bottom button not found in DOM");
	}		
	
	//Set the shipTo on the remote bean; bean retrieves DealerInfo object for the specified shipTo
	//and sets it as the selectedDealer
	this.debug("DLCTRComponent.setSelectedDealer: Before remote call - shipTo = " + shipTo 
		+ "; conversationId = " + this.conId);
	Seam.Remoting.getContext().setConversationId(this.conId);
	Seam.Component.getInstance("dlctrInformation").setSelectedDealer( shipTo ); 
}

