
/**
 * Partner Search Scripts
 * @author luisat
 */
var psRefinementTimeoutValue  = 10;
var haveCities = false;
var haveStates = false;
if(!geoDisplayMaps) var geoDisplayMaps = {};
if(!geoDisplayMaps.partnerTypeMap) {
	geoDisplayMaps.partnerTypeMap = {
	
		// solution providers	
		"CSA" : "Citrix Solution Advisor",
		"ISV" : "Independent Software Vendor",
		"SI"  : "System Integrator",

		// alliance types
		"CR"  : "Citrix Ready",

		// distribution types
		"CELP"        : "CELP",
		"DISTRIBUTOR" : "Distributor",
		"VOLUME"      : "Volume"
	}
}

if(!geoDisplayMaps.partnerLevelMap) {
	geoDisplayMaps.partnerLevelMap = {
		"PLATINUM" : "Platinum",
		"GOLD"     : "Gold",
		"SILVER"   : "Silver",
		"AUTHORIZED" : "Authorized",
		"CORE"      :  "Core",
		"LEADERSHIP": "Leadership",		
		"EXHIBITOR" : "Exhibitor"
	}
}

if (!ps) var ps = {};

if (!ps.search) { 				
	ps.search = {				
		country: "",
		state:   "",
		pType: "",
		program: "", 
		method : "state"
	};
}
// if the Solution tab is selected go fetch states or cities
ps.search.handleCountrySelectChange = function() {
	
	// load partner type for first tab
	ps.search.program = jQuery(".ui-tabs-selected > a ").attr("id");
	
	ps.search.getPartnerTypesFor(ps.search.program);
	
	jQuery("#tabValue").attr("value", ps.search.program);	  // write program member to input field
	
	ps.search.country = jQuery(this).attr("value");	
	
	if(!ps.search.country) {
		ps.search.country = ps.search.getCountryDropdown().val();
	}
	
	if(ps.search.country && ps.search.country.length > 0) {
		
			
			// populate states
			DWRPSRefinementController.getStatesForCountry(ps.search.country, { 
				callback: ps.search.populateStates,
				errorHandler:function(message) { 
					ps.search.printMessage("Debug: error ocurred while refining country: " +  message);
				 },
				timeout:psRefinementTimeoutValue * 1000
			});
			
			//If country is USA don't fetch the cities - they're too many	
			if (ps.search.country=='US') {
				jQuery("#psCitySelect").empty();
				jQuery("#psCitySelect").append('<option value="" selected>' + "All" + '</option>');
			}
			else {
				// refine and add all cities for that country except for USA		
				DWRPSRefinementController.getCitiesForState("",ps.search.country,  { 
					callback :ps.search.populateCities,
					errorHandler:function(message) { 
						ps.search.printMessage("Debug: error ocurred while refining state");
					 },
					timeout:psRefinementTimeoutValue * 1000
				});
			}
	
	}			
};

// if the Dist tab is selected don't fetch states or cities
ps.search.handleCountrySelectChangeDist = function() {
	
	// load partner type for first tab
	ps.search.program = jQuery(".ui-tabs-selected > a ").attr("id");
	ps.search.getPartnerTypesFor(ps.search.program);
	jQuery("#tabValue").attr("value", ps.search.program);	  // write program member to input field
	
	ps.search.country = jQuery(this).attr("value");	
	
	if(StringUtils.isEmpty(ps.search.country)) {
		ps.search.country = ps.search.getCountryDropdown().val();
	}
};


ps.search.printMessage = function(message) {
	jQuery("#dynamicMessage").empty().append(message);	
};

ps.search.displayMethodSelector = function(showZip, showState) {
	
	if(ps.search.program != "DIST") {
		jQuery("#methodSelectorFields").show();
	}
	
	if(!showZip) {		
		jQuery("#zipRadioSection").hide();
		jQuery("#zipRadiusForm").hide();   
	}
	else {
		
		if(ps.search.program != "DIST") {
			jQuery("#zipRadioSection").show();	
		}
		
				
		if(!jQuery("#zipRadiusForm").attr("checked")) {
			jQuery("#zipRadioButton").attr("checked", true);
			if(ps.search.program != "DIST") {
				jQuery("#zipRadiusForm").show();
			}			
		}		   
	}
	
	if(!showState){
		jQuery("#stateRadioSection").hide();
		jQuery("#stateRegionForm").hide();		
		jQuery("#cityForm").hide();
	}
	else {
		
		if(ps.search.program != "DIST") {
			jQuery("#stateRadioSection").show();
		}
		if(!jQuery("#stateRadioButton").attr("checked")) {
			jQuery("#stateRadioButton").attr("checked", true);
			
			if(ps.search.program != "DIST") {
				jQuery("#stateRegionForm").show();
				jQuery("#cityForm").show();
				jQuery("#zipRadiusForm").hide();
			}			
		}		
	}
};

ps.search.handleZipButtonClick = function() {
	ps.search.method = "zip";
	jQuery("#zipRadiusForm").show();
	jQuery("#stateRegionForm").hide();
	jQuery("#psStateRegionSelect").attr("value", "");	
	jQuery("#cityForm").hide();
	jQuery("#psCitySelect").attr("value", "");
	jQuery("#psZipInput").val("");
};


ps.search.handleStateButtonClick = function() {
	ps.search.method = "state";
	jQuery("#stateRegionForm").show();
	jQuery("#cityForm").show();
	jQuery("#zipRadiusForm").hide();	
	jQuery("#psZipInput").val("");
};

//everytime you select a different state, it will fetch the all cities for that state except for USA
ps.search.handleStateSelectChange = function() {
	
	ps.search.state = jQuery(this).attr("value");
	
	if(StringUtils.isEmpty(ps.search.state)) {
		ps.search.state = "";
	}

	if (StringUtils.isEmpty(ps.search.state) && (ps.search.getCountryDropdown().val()=="US") ) {
		jQuery("#psCitySelect").empty();
		jQuery("#psCitySelect").append('<option value="" selected>' + "All" + '</option>');
	}
	else {
		DWRPSRefinementController.getCitiesForState(ps.search.state ,ps.search.country,  { 
			callback :ps.search.populateCities,
			errorHandler:function(message) { 
				ps.search.printMessage("Debug: error ocurred while refining state");
			 },
			timeout:psRefinementTimeoutValue * 1000
		});
	}
};


/**
 * private: handle state refinement
 * @param states - receives a set of <code>PSState</code>
 */
ps.search.populateStates = function(states) {	
	
	if(ps.search.country == "US" || ps.search.country == "CA") {			
		// for US and Canada show both zip and location search methods
		ps.search.displayMethodSelector(true, true);
	}
	else {
		// otherwise show just location
		ps.search.displayMethodSelector(false, true);
	}
	var options = '<option value="" selected>' + "All" + '</option>';;
	if(states) {
		
		if(ps.search.program != "DIST") {
			jQuery("#stateRegionForm").show();
		}
		if(states.length > 0) {	
			haveStates = true;
			// populate states drop down with states						
			// if US or Canada show long names
			if(ps.search.country == "US" || ps.search.country == "CA") {			
				for(var i = 0; i < states.length; i++) {					
					 options += '<option value="' + states[i].state + '">' + states[i].longState+ '</option>';
				}
			}
			else {
				for(var i = 0; i < states.length; i++) {					
					 options += '<option value="' + states[i].state + '">' + states[i].state + '</option>';
				}
			}							
		}		
		else {	
			haveStates = false;
			jQuery("#stateRegionForm").hide();
		}
		jQuery("#psStateRegionSelect").empty().append(options);		
	}	
	else {
		// display no states 
		haveStates = false;
		var options = '<option value="" selected>' + "No states available" + '</option>';
		jQuery("#psStateRegionSelect").empty().append(options);		
	}
};

/**
 * populate partner types drop down
 * @param types - a set of <code>PartnerType</code>
 */
ps.search.populatePartnerTypes = function(types) {
	
	
	
	if(types.length > 1) {				
		// populate partner types drop down
		var options = '<option value="" selected>' + "All" + '</option>';		
		for(var i = 0; i < types.length; i++) {								
			 options += '<option value="' + types[i] + '">' + geoDisplayMaps.partnerTypeMap[types[i]] + '</option>';
		}		
		jQuery("#psPartnerTypeSelect").empty().append(options);
	}	
	else if(types.length == 1) {										
		// populate single drop down item
		var options = '<option value="' + types[0] + '">' + geoDisplayMaps.partnerTypeMap[types[0]] + '</option>';				
		jQuery("#psPartnerTypeSelect").empty().append(options);
		
		// after populating with single item, populate the levels with this partner type
		ps.search.pType = types[0];
		ps.search.handlePartnerTypeSelectChange();
	}	
};

ps.search.handlePartnerTypeSelectChange = function() {
	
	// if event came from a change, record new value
	if(!StringUtils.isEmpty(jQuery(this).attr("value")))
		ps.search.pType = jQuery(this).attr("value");
	
	if(!StringUtils.isEmpty(ps.search.pType)) {
		
		DWRPSRefinementController.getLevelsFor(ps.search.pType, ps.search.program,  { 
			callback: ps.search.populateLevels,
			errorHandler:function(message) { 
				ps.search.printMessage("Debug: error ocurred while refining state");
			 },
			timeout:psRefinementTimeoutValue * 1000
		});
	}				
};

/**
 * populate levels drop down
 */
ps.search.populateLevels = function(levels) {
		
	if(levels.length > 1) {				
		// partner level drop down
		var options = '<option value="" selected>' + "All" + '</option>';		
		for(var i = 0; i < levels.length; i++) {								
			 options += '<option value="' + levels[i] + '">' + geoDisplayMaps.partnerLevelMap[levels[i]] + '</option>';
		}		
		jQuery("#psLevelSelect").empty().append(options);
	}	
	else if(levels.length == 1) {
		 // partner level single item
		 var options = '<option value="' + levels[0] + '">' + geoDisplayMaps.partnerLevelMap[levels[0]] + '</option>';
		 jQuery("#psLevelSelect").empty().append(options);		 
	}		
};

/**
 * private: handle city refinement
 */
ps.search.populateCities = function(cities) {	
	
	var options = '<option value="" selected>' + "All" + '</option>';
	if(cities && cities.length > 0) {	
		jQuery("#cityForm").show();
		haveCities = true;
		// populate cities drop down with country's states							
		for(var i = 0; i < cities.length; i++) {		
			 options += '<option value="' + cities[i] + '">' + cities[i] + '</option>';	
		}
		jQuery("#psCitySelect").empty().append(options);		
	}	
	else {
		haveCities = false;
		// none
		jQuery("#cityForm").hide();
	}
};

/**
 * Fetch partner types for a specific program
 */
ps.search.getPartnerTypesFor = function(program) {
	
	if(program && program.length > 0) {
				
		DWRPSRefinementController.getPartnerTypesFor(program, { 
			callback: ps.search.populatePartnerTypes,
			errorHandler:function(message) { 
				ps.search.printMessage("<span class='countryhighlight padding10'>* An error occurred while loading the page. Please refresh the browser.</span>");
			 },
			timeout:psRefinementTimeoutValue * 1000
		});	
	}	
};

ps.search.getCountryDropdown = function ()
{
	if(ps.search.program == "DIST") 
	{
		return jQuery("#psCountrySelectDist");
	}else
	{
		return jQuery("#psCountrySelect");
	}
};
	
ps.search.validateForm = function() {
	
	if(ps.search.program == "DIST") {
		jQuery("#psCountrySelect").val(jQuery("#psCountrySelectDist").val());	
	}
			
	country = ps.search.getCountryDropdown().val();
	if(StringUtils.isEmpty(country)){	
		return false;
	}
	
	var zipInput = jQuery("#psZipInput").val();	
	if(ps.search.method == "zip") {				
		return zipInput != undefined && zipInput.length > 0 && typeof zipInput == "string";		
	}
	else {
		return true;
	}	
};


jQuery(document).ready( function() {
	
	// DISABLE ALL FIELDS BELOW COUNTRY UNTIL IT HAS BEEN SELECTED 
	jQuery("#zipRadioButton").attr({disabled: "disabled"});
	jQuery("#stateRadioButton").attr({disabled: "disabled"});
	jQuery("#psStateRegionSelect").attr({disabled: "disabled"});
	jQuery("#psCitySelect").attr({disabled: "disabled"});
	jQuery("#psProductSelect").attr({disabled: "disabled"});
	jQuery("#psPartnerTypeSelect").attr({disabled: "disabled"});
	jQuery("#psLevelSelect").attr({disabled: "disabled"});
	jQuery("#searchButton").attr({disabled: "disabled"});
	jQuery("#zipRadioSection").hide();
	jQuery("#psCountrySelectDist").hide();
	jQuery("#psCountrySelect").show();
	
	
	if (ps.search.getCountryDropdown().val() !== "" ){
		jQuery("#zipRadioButton").removeAttr("disabled");
		jQuery("#stateRadioButton").removeAttr("disabled");
		jQuery("#psStateRegionSelect").removeAttr("disabled");
		jQuery("#psCitySelect").removeAttr("disabled");
		jQuery("#psProductSelect").removeAttr("disabled");
		jQuery("#psPartnerTypeSelect").removeAttr("disabled");
		jQuery("#psLevelSelect").removeAttr("disabled");
		jQuery("#searchButton").removeAttr("disabled");
		jQuery("#countryRow").removeClass("countryhighlight");
	}

	jQuery("#psCountrySelectDist").change(			//everytime you select an option from dropdown behavior changes
		function(){
			if (ps.search.getCountryDropdown().val() == "" ){
				jQuery("#countryRow").addClass("countryhighlight");
				jQuery("#zipRadioButton").attr({disabled: "disabled"});
				jQuery("#stateRadioButton").attr({disabled: "disabled"});
				jQuery("#psStateRegionSelect").attr({disabled: "disabled"});
				jQuery("#psCitySelect").attr({disabled: "disabled"});
				jQuery("#psProductSelect").attr({disabled: "disabled"});
				jQuery("#psPartnerTypeSelect").attr({disabled: "disabled"});
				jQuery("#psLevelSelect").attr({disabled: "disabled"});
				jQuery("#searchButton").attr({disabled: "disabled"});
				
				return false;
			}
		
			jQuery("#zipRadioButton").removeAttr("disabled");
			jQuery("#stateRadioButton").removeAttr("disabled");
			jQuery("#psStateRegionSelect").removeAttr("disabled");
			jQuery("#psCitySelect").removeAttr("disabled");
			jQuery("#psProductSelect").removeAttr("disabled");
			jQuery("#psPartnerTypeSelect").removeAttr("disabled");			
			jQuery("#searchButton").removeAttr("disabled");
			jQuery("#psLevelSelect").removeAttr("disabled");
			jQuery("#countryRow").removeClass("countryhighlight");	
			
			
		});
		
		
		jQuery("#psCountrySelect").change(			//everytime you select an option from dropdown behavior changes
		function(){
			if (ps.search.getCountryDropdown().val() == "" ){
				jQuery("#countryRow").addClass("countryhighlight");
				jQuery("#zipRadioButton").attr({disabled: "disabled"});
				jQuery("#stateRadioButton").attr({disabled: "disabled"});
				jQuery("#psStateRegionSelect").attr({disabled: "disabled"});
				jQuery("#psCitySelect").attr({disabled: "disabled"});
				jQuery("#psProductSelect").attr({disabled: "disabled"});
				jQuery("#psPartnerTypeSelect").attr({disabled: "disabled"});
				jQuery("#psLevelSelect").attr({disabled: "disabled"});
				jQuery("#searchButton").attr({disabled: "disabled"});
				
				return false;
			}
		
			jQuery("#zipRadioButton").removeAttr("disabled");
			jQuery("#stateRadioButton").removeAttr("disabled");
			jQuery("#psStateRegionSelect").removeAttr("disabled");
			jQuery("#psCitySelect").removeAttr("disabled");
			jQuery("#psProductSelect").removeAttr("disabled");
			jQuery("#psPartnerTypeSelect").removeAttr("disabled");			
			jQuery("#searchButton").removeAttr("disabled");
			jQuery("#psLevelSelect").removeAttr("disabled");
			jQuery("#countryRow").removeClass("countryhighlight");	
			
			
		});		
	
	// display tabs	and populate partner type according to tab
	var $tabs = jQuery("#pstabs > ul").tabs({			 
		
		// on tab show, populate levels
	    show: function(ui) {			    		    		
			
			// when clicking on a tab, populate partner types for that tab
			ps.search.program = jQuery(".ui-tabs-selected > a ").attr("id");			
			ps.search.getPartnerTypesFor(ps.search.program);
			jQuery("#tabValue").attr("value", ps.search.program);
			
			// change levels back to 'All'
			var options = '<option value="">' + "All" + '</option>';
			jQuery("#psLevelSelect").empty().append(options);
			
			// dynamically change link on help page
			if(ps.search.program == "SOLUTION_PROVIDER") {

				// remember tab
				CookieUtils.eraseCookie("psTab2Remember");
				
				jQuery("#partnerTypeLink").attr("href", serverURL + "/res/html/ps/solution-partners.html");
				
				// bring back hidden options
				jQuery("#noshow").show();
				jQuery("#cityForm").show();
								
				jQuery("#methodSelectorFields").show();				
				
				if(ps.search.method == "zip") {
					jQuery("#zipRadiusForm").show();	
				}
				else {
					if(haveStates)
						jQuery("#stateRegionForm").show();
					
					if(haveCities)
						jQuery("#cityForm").show();	
				}
				
				if(ps.search.country == "US" || ps.search.country == "CA") { 
					jQuery("#zipRadioSection").show();
				}
				
				
				jQuery("#psCountrySelectDist").hide();
				jQuery("#psCountrySelect").show();
				jQuery("#psCountrySelect").val(jQuery("#psCountrySelectDist").val());	
				
				if (jQuery("#psCountrySelectDist").val() != "") {
					jQuery("#psCountrySelect").trigger('change');
				}
				
							
			}			
			if(ps.search.program == "DIST") {

				// remember tab
				CookieUtils.createCookie("psTab2Remember",true,0);
				
				jQuery("#partnerTypeLink").attr("href", serverURL + "/res/html/ps/distribution-partners.html");

				// RDY-299 hide functionality
				jQuery("#methodSelectorFields").hide();
				jQuery("#zipRadiusForm").hide();
				jQuery("#stateRegionForm").hide();
				jQuery("#cityForm").hide();
				jQuery("#noshow").hide();
				
				jQuery("#psCountrySelectDist").show();
				jQuery("#psCountrySelect").hide();
				jQuery("#psCountrySelectDist").val(jQuery("#psCountrySelect").val());
				
				if (jQuery("#psCountrySelectDist").val() != "") {
					jQuery("#psCountrySelectDist").trigger('change');
				}
			}							
	    }
	});
	
	// attach event handler to country drop down depending on which tab is selected
	jQuery("#psCountrySelectDist").change(ps.search.handleCountrySelectChangeDist);
	jQuery("#psCountrySelect").change(ps.search.handleCountrySelectChange);	

	// attach event handler to zip radio button
	jQuery("#zipRadioButton").click(ps.search.handleZipButtonClick);
	
	// attach event handler to state radio button
	jQuery("#stateRadioButton").click(ps.search.handleStateButtonClick);
	
	// attach event handler to state/region drop down
	jQuery("#psStateRegionSelect").change(ps.search.handleStateSelectChange);
	
	// attach event handler on partner type drop down
	jQuery("#psPartnerTypeSelect").change(ps.search.handlePartnerTypeSelectChange);	
		
	// attach validator 
	jQuery("#psSearchForm").submit(ps.search.validateForm);
	
	// attach window open pop up for help link
	jQuery("#partnerTypeLink").click(function() {
		var url = jQuery(this).attr("href");
    	var name= "PartnerType";  		        		
   		window.open(url,name,'width=740,height=580,alwaysRaised=yes,resizable=no,scrollbars=yes,toolbar=no,location=no,directories=no,status=no,menubar=no');
   		return false;		
	});
	
	// adjust right tab
	if(CookieUtils.readCookie("psTab2Remember")) {		
		$tabs.tabs('select', 1);		
	}
		
	// on browser back button, refresh country refinements
	var oldCountry = jQuery("#psCountrySelect").val();	
	
	if(!StringUtils.isEmpty(oldCountry)) {
		ps.search.method = "state";
		ps.search.handleCountrySelectChange();
	}	
});