/*
Given a group of element ids, this function hides all the
elements represented by those ids and shows only the element
that is represented by the toShowId.

Parameters:
 - toHideIds: Array with the ids of the elements to hide.
 - toShowId: The id of the element to show.

This function changes the style.display attribute of the
elements represented by the parameter ids.
*/
function switchVisibleGroup(toHideIds, toShowId){
	var toHide;
	for (var i = 0; i < toHideIds.length; ++i){
		toHide = $(toHideIds[i]);
		if(toHide != null) toHide.style.display = "none";
	}
	var toShow = $(toShowId);
	if(toShow != null) toShow.style.display = "";
}

/*
This function prints the pagination links for a set of pages given the
current page number and the total of pages.

Parameters:
 - pageNumber: The current page number.
 - pageCount: Total of pages.
 - pagesElementId: Element whose inner HTML will be rewritten to show the pagination.

This function modifies the inner HTML of the element represented by the pagesElementId.
This function assumes all pages are contained in an element whose id has the
following format: page#; where # represents the page number, starting from 0.

*/
var pageGroupIds = null;
function updatePages(pageNumber, pageCount){
	if(pageGroupIds == null){
		pageGroupIds = new Array();
		for(var i = 0; i < pageCount; ++i){
			pageGroupIds[i] = "page"+i;
		}
	}
	var pagesElement = $('pagination');
	var html = "Page: ";
	if (pageNumber > 0) {
		html += '<a id="pagPrevious" href="javascript:updatePages(' + (pageNumber-1) + ',' + pageCount + ');" onclick=\"trackingPageNumber('+(pageNumber)+')\">&lt;Previous</a>';
	}
	for(var i = 0; i < pageCount; ++i){
		if (pageNumber == i) {
			html += ' '+(i+1);
		}
		else {
			html += ' <a href="javascript:updatePages(' + i + ',' + pageCount + ');" onclick=\"trackingPageNumber('+(i+1)+')\">' + (i+1) + '</a>';
		}
	}
	if ((pageNumber+1) < pageCount) {
		html += ' <a id="pagNext" href="javascript:updatePages(' + (pageNumber+1) + ',' + pageCount + ');" onclick=\"trackingPageNumber('+(pageNumber+2)+')\">Next&gt;</a>';
	}
	pagesElement.innerHTML = html;
	switchVisibleGroup(pageGroupIds, "page"+pageNumber);
}

function showModifySearchByPostalCode(proximity) {
	var divModify = prepareModifySearchPopUpWindow();
	var txtZip = createText('zipCodeP','Your zip code: '+$('ipZip').get('value'));
	
	var changeZipLink = createLink('changeZipLink','#','Change',function changeZipCode(){
		document.getElementById('zipCodeP').style.display = "none";
		document.getElementById('countyP').style.display = "none";
		document.getElementById('cmbCounties').style.display = "none";
		document.getElementById('submitModifySearch').style.display = "none";	
		
		var newZipText = createText('newZipText','In order to provide you with the best vehicle price and relevant results we will need to know your location,');
		divModify.appendChild(newZipText);		
		/*var txtNewZip = createInput('txtNewZip','text','Enter ZIP Code','');
		
		divModify.appendChild(txtNewZip);*/
		//divModify.appendChild(createInput('submitNewZip','button','Go >',"getNextDialog('modifySearch','zipcode')"));		
	});
	txtZip.appendChild(changeZipLink);	
	divModify.appendChild(txtZip);
	
	/*var txtRange = createText('rangeP','Range ');
	txtRange.appendChild(createSelectMile());
	divModify.appendChild(txtRange);*/

	var txtCounty = createText('countyP','There were multiple in the zip code you entered, help us to narrow it down. Please select your county: ');
	
	divModify.appendChild(txtCounty);
	divModify.appendChild(createSelectCounty($('ipZip').get('value')));
	
	executeModifySearchPopUpWindow(divModify);
	//selectProximityRangeCombo(proximity);
}

function showConfigureDealerLocator(){
	validateCookie(this,'locateDealer()','cd',false,$('ipZip').get('value'));
}

function showModifySearchByCity(proximity, state) {
	var divModify = prepareModifySearchPopUpWindow();

	var txtCity = createText('cityP','City/State ');
	txtCity.appendChild(createInput('city','text',$('CityStateCityName').get('value'),''));
	divModify.appendChild(txtCity);

	var txtState = createText('stateP','State ');
	txtState.appendChild(createSelectState('cmbState','cmbState',state));
	divModify.appendChild(txtState);

	var txtRange = createText('rangeP','Range ');
	txtRange.appendChild(createSelectMile());
	divModify.appendChild(txtRange);

	executeModifySearchPopUpWindow(divModify);
	selectProximityRangeCombo(proximity);
}

function showModifySearchByVendorName(state){

	var divModify = prepareModifySearchPopUpWindow();

	var txtDealer = createText('dealerName','Dealer Name ');
	txtDealer.appendChild(createInput('dealer','text',$('VendorName').get('value'),''));
	divModify.appendChild(txtDealer);

	var txtCity = createText('cityName','City Name ');
	txtCity.appendChild(createInput('city','text',$('VendorCityName').get('value'),''));
	divModify.appendChild(txtCity);

	var txtState = createText('stateP','State ');
	txtState.appendChild(createSelectState('cmbState','cmbState',state));
	divModify.appendChild(txtState);

	executeModifySearchPopUpWindow(divModify);

}

function selectProximityRangeCombo(proximity) {
	// Select the Proximity Range.
	var proximityRangeCombo = $('cmbRange');
	for (var i=0; i < proximityRangeCombo.options.length; i++) {
		if (proximityRangeCombo.options[i].value == proximity) {
			proximityRangeCombo.options[i].selected = true;
		}
	}
}

function prepareModifySearchPopUpWindow() {
	var divModify = document.createElement("DIV");
	divModify.id = "configureRegion";

	divModify.appendChild(createLink('close','#','[X]',closeModifySearch));
	divModify.appendChild(createText('modifySearchTitle','Please enter your zip code'));
	return divModify;
}

function executeModifySearchPopUpWindow(divModify) {
	divModify.appendChild(createInput('submitModifySearch','button','Go >',submitModifySearch));
	//divModify.appendChild(createLink('searchNew',BASE_CONTEXT+'/tools/dealerlocator/search.do','Start A New Search',''));
	document.body.appendChild(divModify);

	if($('zipcodepopup') != null){
		$('zipcodepopup').addEvent('click', function(evt) {
			$('zipcodepopup').set('value','');
		});

		$('zipcodepopup').addEvent('keypress', function(evt) {
			var charCode = (evt.which) ? evt.which : evt.key;
			var src = $('zipcodepopup').get('value');			
			if (((charCode >= 48 && charCode <= 57)) ||  (charCode<31)){
				if ($('zipcodepopup').get('value').length > 4) {
					return false;
				}else {
					return true;
				}
			}else if(evt.key == 'backspace'){
				return true;
			}else{
				return false;
			}
		});
	}
}

function closeModifySearch(){
	var modifyWin = $('modifySearch');	
	if (modifyWin) document.body.removeChild(modifyWin);
	return false;
}


function createLink(id,href,text,method){
	var link = document.createElement("A");
	link.id = id;
	link.href = href;
	link.onclick = method;
	link = $(link);
	link.addEvent('mouseenter',function(){link.addClass(id+"On");});
	link.addEvent('mouseleave',function(){link.removeClass(id+"On");});
	link.appendChild(document.createTextNode(text));
	return link;
}

function createText(id, text){
	var txt = document.createElement("P");
	txt.id = id;
	txt.appendChild(document.createTextNode(text));
	return txt;
}

function createInput(id,type,value,method){
	var input = document.createElement("INPUT");
	input.id = id;
	input.type = type;
	input.value = value;
	input.onclick = method;
	if (type == 'button'){
		input = $(input);
		input.addEvent('mouseenter',function(){input.addClass(id+"On");});
		input.addEvent('mouseleave',function(){input.removeClass(id+"On");});
	}
	return input;
}

function createOption(text,value, selected){
	var option = document.createElement("OPTION");
	option.appendChild(document.createTextNode(text));
	option.value = value;
	if(selected==true){
		option.selected = "true";
	}
	return option;
}

function createSelectState(id,name, value){
	var selectState = document.createElement("SELECT");
	selectState.id = id;
	selectState.name = name;
	var myRequest = new Request({url: BASE_CONTEXT+'/mds/tiles/global/states.xml',
		onSuccess: function(text,xml) {
			var object = xml.getElementsByTagName("data")[0];
			for (var i=0; i < object.getElementsByTagName("state").length; i++) {
				var optiontext = object.getElementsByTagName("state")[i].childNodes[0].nodeValue;
				var optionvalue = object.getElementsByTagName("state")[i].getAttribute("value");
				if(optionvalue==value){
					selectState.appendChild(createOption(optiontext,optionvalue,true));
				} else {
					selectState.appendChild(createOption(optiontext,optionvalue,false));
				}
			};
		}
	}).send();
	return selectState;
}

function createSelectCounty(zip){
	var selectCounty = document.createElement("SELECT");
	
	selectCounty.id = "cmbCounties";
	var vZipInfo = new zipcodeUtil(zip);
	var counties = vZipInfo.getCounties();
		selectCounty.appendChild(createOption('Select County','0'));
		for (var i=0; i < counties.length; i++){
			selectCounty.appendChild(createOption(counties[i].description),i);
		} 	
		
	return selectCounty;
}

function createSelectMile(){
	var selectRange = document.createElement("SELECT"); 
	selectRange.id = "cmbRange";
	selectRange.appendChild(createOption('25 mi.','25'));
	selectRange.appendChild(createOption('50 mi.','50'));
	selectRange.appendChild(createOption('100 mi.','100'));
	selectRange.appendChild(createOption('150 mi.','150'));
	return selectRange;	
}

/*
Set the zipcode on the cookie.
If the cookie exists, update it
If the cookie don’ts exist create now one.
*/
function handlerCookie(zip){
	try{
		var loc = mrm.cmp.zc.getLocation();
		if(loc!=null)
			if(loc.zipcode != zip)
				saveDefaultLocation(zip,null,null);
	}catch(e){}
}





function submitModifySearch(){

	if ($('searchType').get('value') == "ByPostalCode") {

		$('ipZip').set('value', $('zipcodepopup').get('value'));
		$('PostalCodeProximity').set('value', $('cmbRange').get('value'));

	}else if ($('searchType').get('value') == "ByCityState") {
		$('CityStateCityName').set('value', $('city').get('value'));
		$('CityStateName').set('value', $('cmbState').get('value'));
		$('CityStateProximity').set('value', $('cmbRange').get('value'));
		$('PostalCodeProximity').set('value', $('cmbRange').get('value'));

	}else if ($('searchType').get('value') == "ByVendor") {

		$('VendorName').set('value', $('dealer').get('value'));
		$('VendorCityName').set('value', $('city').get('value'));
		$('VendorStateName').set('value', $('cmbState').get('value'));
	}

	//For Modify Your Search Criteria uses 'zipcodepopup' id instead
    //of 'zipcode', so both ids must be contemplated
    if( ($('zipcode')==null)  ||  ($('zipcode').value==undefined) ){
    	if( ($('zipcodepopup')!=null)  ||  ($('zipcodepopup')!=undefined) ){
     		if(validateZip($('zipcodepopup').value))
     			var zipcode = new zipcodeUtil($('zipcodepopup').value);
     			if(zipcode.isValid){
     				handlerCookie($('zipcodepopup').value);
     				$('sortForm').submit();
     			}
    	 }else{
    		 $('sortForm').submit(); 
    	 }
     }else {
     		if(validateZip($('zipcode').value))
		       $('sortForm').submit();
	} 



}

function trackingDealerWebsite(name){
	var obj = {
		prop18: BRAND,
		prop23: 'en',
		prop27: 'contentarea',
		prop32: BRAND+': us: locate-a-dealer-results: view '+name
	};
	clickTrack(obj);
}

function trackingPageNumber(name){
	var divisionObj=BRAND.toUpperCase();
	var nameObj = name;
	var obj = {
		prop18: BRAND,
		prop23: 'en',
		prop27: 'contentarea',
		prop32: BRAND+': us: locate-a-dealer-results: list '+name
	};
	clickTrack(obj);
}

function validateAddress(){
	var objZip = document.getElementById("ipZip");
	var objStreet = document.getElementById("startAddressStreetId");
	var objCity = document.getElementById("startAddressCityId");
	var objState = document.getElementById("startAddressStateId");
	var zipErrorMsg = "Please enter either zip code or street, city and state.";
	var zipValid = false;
	var addressValid = false;
	if(objZip.value.search(/^\d{5}$/) == -1){
		zipValid = true;
	}
	if(emptyStr(objStreet.value)||emptyStr(objCity.value)){
		addressValid = true;
	}else{
		if("Street Address"==objStreet.value||"City"==objCity.value||"State"==objState.value){//default value
			addressValid = true;
		}
	}
	if(zipValid&&addressValid){
		alert(zipErrorMsg)
		return false;
	}
	return true;
}


/* Set the user's zipcode to that of the 
   dealer inventory that was selected in LAD results
*/

function setLocationToDealer(zip) {
   var loc = getDefaultLocation();
      
   if(loc == null || loc.zipcode != zip) {
   	var zipInfo = new zipcodeUtil(zip);
    var counties = zipInfo.getCounties();
    var regions = zipInfo.getRegions(counties[0].code);
                                    
    saveDefaultLocation(zip, 
     new Region(regions[0].code,regions[0].description,zipInfo.getDmaByRegion(regions[0].code)),
     new County(counties[0].code,counties[0].description),
     zipInfo.isMultiCounty, 
     zipInfo.isMultiRegion);
   }
}

function emptyStr(value){
	if(value ==null||value.length==0){
		return true;
	}
	return false;
}


