﻿<!-- 
//send Email to your friend jquery
function sendEmailFriend(asmxUrl) {
	var error = '';
	var isValid = true;
	if ($('#txtEmailYourName').val() == "") {
		isValid = false;
		error += "* Your Name Is Not Provided\n";
	}
	if (!checkEmailStr($('#txtEmailYourEmailAddress').val())) {
		isValid = false;
		error += "* Your Email Address Is Not Provided Or Valid\n";
	}
	if (!checkEmailStr($('#txtEmailRecipientEmailAddress').val())) {
		isValid = false;
		error += "* Recipient''s Email Address Is Not Provided Or Valid\n";
	}
	if (isValid)
		$.ajax({
			type: "POST",url: asmxUrl,
			data:	"{name: '"+ $('#txtEmailYourName').val() +
					"',yourEmail: '"+ $('#txtEmailYourEmailAddress').val() +
					"',recipientEmail: '"+ $('#txtEmailRecipientEmailAddress').val() +
					"',text: '"+ $('#txtEmailPersonalMessage').val() +
					"',url: '"+ GetEmailURL() + "' }",
					contentType: "application/json; charset=utf-8",
			dataType: "text",
			success: function(response) {
				var sendinfo = (typeof response) == 'string' ? eval('(' + response + ')') : response;
				if (sendinfo != "Server error"){
					document.getElementById('divEmailResponceContent').style.display = 'block';
					document.getElementById('divEmailContent').style.display = 'none';
					document.getElementById('spanEmailResponceYourName').innerHTML = sendinfo.split('¸')[0];
					document.getElementById('spanEmailResponceRecipientEmail').innerHTML = sendinfo.split('¸')[1];
				} else {
					alert("Server Error");
				}
			},
			failure: function(msg) {
				$('#output').text(msg);
			}
		});
	else
		alert(error);
}

function OnButtonMouseMove(elm, newImage) {
	elm.src = newImage;// + "<%=SiteSettings.ImagePathFolder%>btnsearch.gif";
}

function bookMarkThis(title, url) {
	if (window.sidebar) { 
		window.sidebar.addPanel(document.title, document.location.href,""); 
	} else if( document.all ) {
		window.external.AddFavorite(document.location.href, document.title);
	} else if(window.opera && window.print) {
		return true;
	}
}

function onSearchBuilderClick(label, eventObject, activeTabName) {
	var div = document.getElementById('keyWordsBuilderDiv');

	//div.className = 'KeyWordsBuilderShow';
	//document.getElementById('refineFirstBox').className = 'KeyWordsBuilderFirstBoxShow';
	//document.getElementById('refineSecondBox').className = 'KeyWordsBuilderSecondBoxShow';
	//document.getElementById('refineFirstBox').style.display = 'block';
	//document.getElementById('refineSecondBox').style.display = 'block';

	var offSet = label.offsetTop;
	var parentObject = label.offsetParent;
	while (parentObject.tagName != 'BODY') {
		offSet = offSet + parentObject.offsetTop;
		parentObject = parentObject.offsetParent;
	}
	//div.style.display = 'block';   
	div.style.top = offSet + label.offsetHeight + 3 + 'px';
	div.style.left = eventObject.clientX + 'px';

	// change active tab 
	newActiveTab = document.getElementById('keywordBuilderCategory' + activeTabName);
onKeywordBuilderPropertyChange(newActiveTab);
}

function onCloseSearchBuilderClick() {  
	var div = document.getElementById('keyWordsBuilderDiv');
	//div.style.display = 'none';
	//document.getElementById('refineFirstBox').style.display = 'none';
	//document.getElementById('refineSecondBox').style.display = 'none';
	//div.className = 'KeyWordsBuilder';    
	//document.getElementById('refineFirstBox').className = 'KeyWordsBuilderFirstBox';
	//document.getElementById('refineSecondBox').className = 'KeyWordsBuilderSecondBox';    
div.style.left = -500 + 'px';
}

function onKeywordBuilderPropertyChange(elm) {
	var keywordBuilderIndicator = document.getElementById('keywordBuilderPropertyIndicator');
	var oldActiveKeywordBuilderProperty = document.getElementById(keywordBuilderIndicator.value);
	oldActiveKeywordBuilderProperty.className = 'InactiveSearchCategoryID';
	elm.className = 'ActiveSearchCategoryID';
	var selectBoxIndicator = document.getElementById('keywordBuilderSelectIndicator');
	var selectElm = elm.id + 'Select';
	var selectBox = document.getElementById(selectElm);
	var oldSelectBox = document.getElementById(selectBoxIndicator.value);
	oldSelectBox.className = 'InactiveSelectBox';  
	selectBox.className = 'ActiveSelectBox';   
	selectBoxIndicator.value = selectBox.id;
	// Change content
	var oldActiveContentControl = document.getElementById(keywordBuilderIndicator.value + 'Content');
	var newActiveContentControl = document.getElementById(elm.id + 'Content');
	oldActiveContentControl.className = 'RefineSearchMainBoxItemInactive';
	newActiveContentControl.className = 'RefineSearchMainBoxItemActive';
keywordBuilderIndicator.value = elm.id;
}

// Required to suppport XMLHttp call back functionality. 
function DisplayModelsTrims(models, context) {
	var newContent = models.split('¸')
	var objDivModels = document.getElementById("divRefineSearchModels");
	var objDivTrims = document.getElementById("divRefineSearchTrims");
	objDivModels.innerHTML = newContent[0];
	objDivTrims.innerHTML = newContent[1];
	var objModels = document.getElementById("drpModels");
	onAddToKeywordSearch(objModels, 'models');
	var objTrims = document.getElementById("drpTrims");
onAddToKeywordSearch(objTrims, 'trims');
}

// Required to suppport XMLHttp call back functionality. 
function ChangeSaveToFavoritesConext(newSaveToFavoritesConent, context) {
	var newContent = newSaveToFavoritesConent.split('¸')
	var spanAddToFavorites = document.getElementById("AddToFavorites" + newContent[0]);
	spanAddToFavorites.innerHTML = newContent[1];
	spanAddToFavorites.className = "VehicleItemDescriptionTitle";
}

function GetValue(obj) {
	if (obj.id == "drpMakes" || obj.id == "drpModels" || obj.id == "drpTrims" || obj.id == "drpGears" 
		|| obj.id == "drpLowMiles" || obj.id == "drpHighMiles" || obj.id == "drpDistance"
		|| obj.id == "drpYearLow" || obj.id == "drpYearHigh" 
		|| obj.id == "drpInteriorColor" || obj.id == "drpExteriorColor"
		|| obj.id == "drpLowPrice" || obj.id == "drpHighPrice"
		|| obj.id == "drpBodyStyles" || obj.id == "drpBedStyles" || obj.id == "drpCabStyles") {
			if (obj.selectedIndex == -1) {
				// Async synchronization. Models and Years is not filled out yet. But the first item will be default
				return '';
			}
			if (obj.options[obj.selectedIndex].value == "All Models" || obj.options[obj.selectedIndex].value == "All Trims") {
				return '';
			}
			return obj.options[obj.selectedIndex].value;
		}
	if (obj.id == "rdConditionAll" || obj.id == "rdConditionNew" || obj.id == "rdConditionUsed" 
		|| obj.id == "rdTransAll" || obj.id == "rdTransAuto" || obj.id == "rdTransManual")     
		return obj.value;

	if (obj.id == "chkCPO") {
		if (obj.checked)
			return obj.value;
		else
			return '';
	}
}

function doYears(objid) {
	if (objid == "drpYearLow") {
		return "&yearsHigh=" + document.getElementById("drpYearHigh").value;
	} else {
		return "&drpYearLow=" + document.getElementById("drpYearLow").value;
	}
}

function deleteYears() {
    // defining new value
	var def = document.getElementById("searchStringDefiner");
	var defValues = def.value;
	var keyWordsGroups = defValues.split("&");
	var newDefValue = '';
	// Trying to find object's value in group

	newDefValue = defValues;

	for(i = 0; i < keyWordsGroups.length; i++) {
		var keyValuePair = keyWordsGroups[i].split("=");
		if (keyValuePair[0] == "years") {// Element is found in "def" string.
			// Finding position
			var start = defValues.indexOf(keyValuePair[0]);
			var end = defValues.indexOf("&", start);
			if (end == -1)
				end = defValues.length;
	
			// element should be deleted
			if (start == 0) {
				// first element
				newDefValue = defValues.replace(keyValuePair[0] + "=" + keyValuePair[1] + "&", "");
			} else {
				// not first element
				newDefValue = defValues.replace("&" + keyValuePair[0] + "=" + keyValuePair[1], "");
			}
		}
	}

return newDefValue;
}

function onAddToKeywordSearch(obj, keyword) {
	// defining new value
	var newValue = GetValue(obj);
	var def = document.getElementById("searchStringDefiner");
	var defValues = def.value;
	var keyWordsGroups = defValues.split("&");
	var newDefValue = '';
	// Trying to find object's value in group
	var newValueApplied = false;
	
	for(i = 0; i < keyWordsGroups.length; i++) {
		var keyValuePair = keyWordsGroups[i].split("=");
		if (keyValuePair[0] == keyword) {// Element is found in "def" string.
			// Finding position
			var start = defValues.indexOf(keyValuePair[0]);
			var end = defValues.indexOf("&", start);
			if (end == -1)
				end = defValues.length;
	
			if (newValue == '') {
				// element should be deleted
				if (start == 0) {
					// first element
					newDefValue = defValues.replace(keyValuePair[0] + "=" + keyValuePair[1] + "&", "");
				} else {
					// not first element
					newDefValue = defValues.replace("&" + keyValuePair[0] + "=" + keyValuePair[1], "");
				}
			} else {
				// change value
				newDefValue = defValues.replace(keyValuePair[0] + "=" + keyValuePair[1], keyValuePair[0] + "=" + newValue);
			}
			newValueApplied = true;
		}
	}
	if (!newValueApplied && newValue.length > 0) {
		// new parameter
		if (defValues.length > 0)
			newDefValue = defValues + "&" + keyword + "=" + newValue;
		else  
			newDefValue = defValues + keyword + "=" + newValue;
	} else if (!newValueApplied) {
		newDefValue =  def.value;  
	} 

	def.value = newDefValue;
	
	//Special Years Handler
	if(obj.id == "drpYearLow" || obj.id == "drpYearHigh") {
		//alert('1: '+newDefValue);
		newDefValue = deleteYears();
		/* alert('2: '+newDefValue);
		//newDefValue = newDefValue + doYears(obj.id);
		//alert('3: '+newDefValue); */
		def.value = newDefValue;
	}
}

function submitRequest(root, page) {
	var def = document.getElementById("searchStringDefiner");
	var queryString = def.value;
	if (queryString.length > 0)
		window.location = root + page + '?' + queryString;
	else
		window.location = root + page
}

// Standard
function trim(str) {
	var i,j;
	i = 0;
	j = str.length - 1;
	str = str.split("");
	while(i < str.length) {
	if(str[i]==" ") {
	  str[i] = ""
	} else {
	  break;
	}
	i++;
	}
	while(j > 0) {
	if(str[j]== " ") {
	  str[j]=""
	} else {
	  break;
	}
	j--;
	}
	return str.join("");
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return [curleft,curtop];
}

//Email a Friend
function onEmailClick(label, eventObject) {
	if (userAgent=='IE' && userAgentVersion<=6) {
		var sltRequestMoreInfoPurchaseFrame = document.getElementById('sltRequestMoreInfoPurchaseFrame');
		if (sltRequestMoreInfoPurchaseFrame) {
			if (hasFormToBeDisplayedAllTheTime)
				sltRequestMoreInfoPurchaseFrame.style.visibility = "hidden";
		}
		var sltBestTime = document.getElementById('sltBestTime');
		if (sltBestTime) {
			if (hasFormToBeDisplayedAllTheTime)
				sltBestTime.style.visibility = "hidden";
		}
	}

	var div = document.getElementById('divEmail');
	var offSet = findPos(label)[1];

	div.style.top = offSet + label.offsetHeight- 10 + 'px';
	div.style.left = eventObject.clientX - div.offsetWidth  + 'px';

	var divEmailContent = document.getElementById('divEmailContent');
	divEmailContent.style.display = 'block';
	var divEmailResponceContent = document.getElementById('divEmailResponceContent');
	divEmailResponceContent.style.display = 'none'; 
}

function onCloseEmailClick() {  
	if (userAgent=='IE' && userAgentVersion<=6) {
		var sltRequestMoreInfoPurchaseFrame = document.getElementById('sltRequestMoreInfoPurchaseFrame');
		if (sltRequestMoreInfoPurchaseFrame) {
			if (hasFormToBeDisplayedAllTheTime)
				sltRequestMoreInfoPurchaseFrame.style.visibility = "visible";
		}
		var sltBestTime = document.getElementById('sltBestTime');
		if (sltBestTime) {
			if (hasFormToBeDisplayedAllTheTime)
				sltBestTime.style.visibility = "visible";
		}
	}
	var div = document.getElementById('divEmail');
	//div.style.display = 'none';
div.style.left = -500 + 'px';
}

function OnEmailValidation() {
	var div = document.getElementById('divEmail');
	if (div.style.left != '-500px') {
		var yourName = document.getElementById("txtEmailYourName");
		var result = true;
		var errorList = '';
		if (trim(yourName.value).length == 0) {
			errorList += '* Your Name Is Not Provided \n';
			result = false;
		}
		var yourEmail = document.getElementById("txtEmailYourEmailAddress");
		if (!checkEmail(yourEmail)) {
			errorList += '* Your Email Address Is Not Provided Or Valid\n';
			result = false;
		}
		var recipientEmail = document.getElementById("txtEmailRecipientEmailAddress");
		if (!checkEmail(recipientEmail)) {
			errorList += "* Recipient's Email Address Is Not Provided Or Valid\n";
			result = false;
		}
		if (!result) {
			alert(errorList);
		}
	}
	return result;
}

function checkEmail(emailElm) {
	var email = emailElm.value;
	if(!(/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(email))) {
		return false;
	} else {
		return true;
	}
}

function ShowMessageSentNotification(feedback, context) {
	var divEmailContent = document.getElementById('divEmailContent');
	divEmailContent.style.display = 'none';
	var divEmailResponceContent = document.getElementById('divEmailResponceContent');
	divEmailResponceContent.style.display = 'block';

	var params = feedback.split('¸');

	var spanEmailResponceYourName = document.getElementById('spanEmailResponceYourName') ;
	spanEmailResponceYourName.innerHTML = params[0];
	var spanEmailResponceRecipientEmail = document.getElementById('spanEmailResponceRecipientEmail') ;
	spanEmailResponceRecipientEmail.innerHTML = params[1];
}

function CutOffSubstring(url, cutString) {
	var start = url.indexOf(cutString);
	if (start != -1) {
		var end = url.indexOf("&", start + cutString.length);
		if (end == -1)
			end = url.length;
		if (start == 0) {
			url = url.replace(url.substring(start, 1), '');
		} else {
			url = url.replace(url.substring(start - 1, end), '');
		}
	}
return url;
}

function GetEmailURL() {
	var loc = window.location.toString();
	var res = CutOffSubstring(loc, 'frame');
	res = CutOffSubstring(res, 'referer');  
	return res; 
}

//Saved Search
function onSaveSearchClickClick(label, eventObject) {
	var div = document.getElementById('divSaveSearch');

	var offSet = label.offsetTop;
	var parentObject = label.offsetParent;
	while (parentObject.tagName != 'BODY') {
		offSet = offSet + parentObject.offsetTop;
		parentObject = parentObject.offsetParent;
	}
	//div.style.display = 'block';
	div.style.top = offSet + label.offsetHeight + 3 + 'px';
	div.style.left = eventObject.clientX - div.offsetWidth + 'px';

	var divSeachContent = document.getElementById('divSaveSearchContent');
	divSeachContent.style.display = 'block';
	var divSaveSearchResponceContent = document.getElementById('divSearchResponceContent');
	divSaveSearchResponceContent.style.display = 'none';
}

function onCloseSaveSearchesClick() {
	var div = document.getElementById('divSaveSearch');
	//div.style.visibility = 'hidden';
	div.style.left = -500 + 'px';
}

function OnSaveSearchesValidation() {
	var saveSearchesName = document.getElementById("txtSaveSearchName");
	if (trim(saveSearchesName.value).length == 0) {
		alter('* Your Save Search Name Could not Be Empty!');
		return false;
	}
	return true;
}

function onShowSavingResultCalls(feedback, context) {
	var divSearchResponceContent = document.getElementById("divSearchResponceContent");
	if (feedback == 'true') {
		divSearchResponceContent.innerHTML = '<center><strong>Your Search Has Been Saved!</strong></center><br /><center>Go to <a href="' + AppRoot + 'saved.aspx" class="ThemeLink">Saved Searches</a>&nbsp;|&nbsp;<a href="javascript:onCloseSaveSearchesClick();" class="ThemeLink">Close Window</a></center>';
		var divSaveSearchContent = document.getElementById('divSaveSearchContent');
		divSaveSearchContent.style.display = 'none';
		divSearchResponceContent.style.display = 'block';        
	} else {
		alert('The Search Name Is Not Unique!');
	}
}


//Popular Cars Feature
function showNext(strPage) {
	var strURL = AppRoot + 'remotepopularcars.aspx?remote=1&page=' + strPage ;
	fcnMakeRequest(strURL,1,'PopularContent');
}

//Detail Page Javascript
function checkFrame() {
	if(top.document.getElementById('DetailFrame') == null) {
		var res = CutOffSubstring(self.location.toString(), 'originsearch');
		res = CutOffSubstring(res, 'requestsearch');
		res = CutOffSubstring(res, 'unrecognizedsearch');  
		res = CutOffSubstring(res, 'frame');
		res = CutOffSubstring(res, 'referer');  
		res = CutOffSubstring(res, 'addToFavoritesCookieNew');
		top.location = res; 
	}
}
function extend() {
	if (top.document.getElementById('DetailFrame') != null && top.document.getElementById('DetailFrame').rows != '525,*') {
		currentRows = top.document.getElementById('DetailFrame').rows;
		top.document.getElementById('DetailFrame').rows='525,*'; 
	}
}

function retract() {
	if (top.document.getElementById('DetailFrame') != null) {
		top.document.getElementById('DetailFrame').rows= currentRows; 
	}
}

function changecss(theClass,element,value) {
	var cssRules;
		if (document.all) {
			cssRules = 'rules';
		}
		else if (document.getElementById) {
			cssRules = 'cssRules';
		}
		for (var S = 0; S < document.styleSheets.length; S++){
		for (var R = 0; R < document.styleSheets[S][cssRules].length; R++) {
			if (document.styleSheets[S][cssRules][R].selectorText == theClass) {
				document.styleSheets[S][cssRules][R].style[element] = value;
			}
		}
	}
}

function noPhotoReplace() {
	var imageList = document.getElementsByTagName('img');
	var i;
	for(i=0;i<imageList.length;i++){
		if (imageList[i].id.indexOf('photo') != -1) {
			if (imageList[i].height <= 1 || imageList[i].complete != true)
				imageList[i].src = 'http://images.zibe.com/portals/zibe/nophoto.gif';
			//if (imageList[i].height <= 1 || imageList[i].height != 80)
				//imageList[i].height = 80;
		}
	}
}

// Google Adsense JS Vars

function setGoogleAdsenseVars(iFrameHeight) {
	google_ad_client = "pub-6879558457257679";
	google_ad_width = 234;
	google_ad_height = iFrameHeight;
	google_ad_format = "234x60_as";
	google_ad_type = "text";
	//2006-11-01: eBizAutos
	google_ad_channel = "9042146736";
	google_color_border = "FFFFFF";
	google_color_bg = "FFFFFF";
	google_color_link = "16387C";
	google_color_text = "000000";
	google_color_url = "16387C";
}

var userAgentVersion = 3;
var userAgent = "Firefox";

function detectUserAgent() {
	if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
		userAgentVersion=new Number(RegExp.$1) // capture x.x portion and store as a number
		userAgent="IE";
	}
	else
	if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){ //test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
		userAgentVersion=new Number(RegExp.$1) // capture x.x portion and store as a number
		userAgent="Firefox";
	}
	else
	if (/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent)){ //test for Opera/x.x or Opera x.x (ignoring remaining decimal places);
		userAgentVersion=new Number(RegExp.$1) // capture x.x portion and store as a number
		userAgent="Opera";
	}
	else
	if (/Safari[\/\s](\d+\.\d+)/.test(navigator.userAgent)){ //test for Safari/x.x or Safari x.x (ignoring remaining decimal places);
		userAgentVersion=new Number(RegExp.$1) // capture x.x portion and store as a number
		userAgent="Safari";
	}
}

detectUserAgent();

window.onload=function() {
	var agt=navigator.userAgent.toLowerCase();

	//No Photo Replacement
	if (userAgent != "safari") {
		noPhotoReplace();
	}
	    
	// height replace for search input text box
	if (userAgent != "IE" || userAgentVersion>=8) {
		changecss('.ActiveSearchTextBox','height','20px');
		changecss('.InactiveSearchTextBox','height','20px');
		changecss('input.SaveSearchTextBox','height','20px');
	}
}

function flashLoader(flashMovie, flashVars, flashHeight, flashWidth, flashAlign, flashQuality, flashBGColor, flashID, flashScale) {
	var flashPluginSpace = 'http://www.macromedia.com/go/getflashplayer';
	document.write('<OBJECT type="application/x-shockwave-flash"  classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" WIDTH="' + flashWidth + '" HEIGHT="' + flashHeight + '" id="' + flashID + '" ALIGN="' + flashAlign + '">');
	document.write('<PARAM NAME="FlashVars" VALUE="' + flashVars + '">');
	document.write('<PARAM NAME="movie" VALUE="' + flashMovie + '">');
	document.write('<PARAM NAME="quality" VALUE="' + flashQuality + '">');
	if (flashScale == null) {
		var flashScale = '';
		var flashScaleParam = '';
	} else {
		document.write('<PARAM NAME="scale" VALUE="' + flashScale + '">');
		var flashScaleParam = ' scale="' + flashScale + '"';
	}
	document.write('<PARAM NAME="bgcolor" VALUE="' + flashBGColor + '">');
	document.write('<param name="wmode" value="transparent">');
	document.write('<param name="allowScriptAccess" value="always">');
	document.write('<EMBED src="' + flashMovie + '" quality="' + flashQuality + '"' + flashScaleParam + ' bgcolor="' + flashBGColor + '"  WIDTH="' + flashWidth + '" HEIGHT="' + flashHeight + '" NAME="' + flashID + '" ALIGN="' + flashAlign + '" TYPE="application/x-shockwave-flash" PLUGINSPAGE="' + flashPluginSpace + '" FlashVars="' + flashVars + '" wmode="transparent" allowScriptAccess="always"></EMBED>');
	document.write('</OBJECT>');
}

// Begin AJAX calls
function fcnMakeRequest(strURL,returnData,target) { 
	var url = strURL;
	var http_request = null;
	if (window.XMLHttpRequest) // If IE7, Mozilla, Safari, and so on: Use native object.
		http_request = new XMLHttpRequest();
	else
		if (window.ActiveXObject) // ...otherwise, use the ActiveX control for IE5.x and IE6.
			http_request = new ActiveXObject('MSXML2.XMLHTTP.3.0');
	        
	http_request.onreadystatechange = function() { fcnAlertContents(http_request,returnData,target); };
	http_request.open('GET', url);
	http_request.send(null);
} 

function fcnAlertContents(http_request,returnData,target) {
	if (http_request.readyState == 4)
		if (http_request.status == 200) {
			if (http_request.responseText.indexOf('Error: ')==0) // show error message
				alert(http_request.responseText.substring(7,http_request.responseText.length));
			else
				if (returnData && target.length > 0)
					document.getElementById(target).innerHTML = http_request.responseText;
		}
		else
			alert('There was a problem with the request: ' + http_request.statusText);
}
// End AJAX calls

// Detail/Inventory
function clearZipCode() {
	var elem = document.getElementsByName('ZipCodeInputBox');
	 for(i = 0; i < elem.length; i++) {
		zipCode = elem[i];
		if (zipCode.value == 'Enter Zip'){ 
			zipCode.value = '';
			zipCode.style.color = '#000000';
		}
	}
//	if (zipCode.value == 'Enter Zip'){ 
//		zipCode.value = '';
//		zipCode.style.color = '#000000';
//	}
	return true;
}

// Detail
function validateZipCode(strURL,itemLatitude,itemLongitude) {
	var zipCode = null;//document.getElementById('ZipCodeInputBox');
	
	var elem = document.getElementsByName('ZipCodeInputBox');
	 for(i = 0; i < elem.length; i++) {
		zipCodeN = elem[i];
		if (zipCodeN.value != 'Enter Zip' && zipCodeN.value != ''){ 
			zipCode = zipCodeN;
		}
	}
	
	zipCodeRegex = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
	if (zipCode == null || !zipCodeRegex.test(zipCode.value)) {
		alert('Zip code is not valid');
		return false;
	} else {
		strURL = strURL + 'userzipcode=' + zipCode.value + '&itemlatitude=' + itemLatitude + '&itemlongitude=' + itemLongitude;
		fcnMakeRequest(strURL,1,'DistanceContent');
		return true;
	}
}

// Inventory
function validateZipCodeChange(strURL, elementId, currentPage) {
	var zipCode = null;//document.getElementById(elementId);
	
	var elem = document.getElementsByName('ZipCodeInputBox');
	if (elem == null || elem.length == 0)
		elem = document.getElementsByName('ZipCodeChangeBox');
	
	 for(i = 0; i < elem.length; i++) {
		zipCodeN = elem[i];
		if (zipCodeN.value != 'Enter Zip' && zipCodeN.value != ''){ 
			zipCode = zipCodeN;
		}
	}
	zipCodeRegex = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
	if (zipCode == null || !zipCodeRegex.test(zipCode.value) ) {
		alert('Zip code is not valid');
		return false;
	} else {
		var refreshURL = window.location.href;
		if (refreshURL.indexOf('.html') > 0 && refreshURL.indexOf('-classifieds-refine') > 0) {
			// html refine system
			var distStartIndex = refreshURL.indexOf('-' + constDistance + '-', 0);
			if (distStartIndex != -1) {
				var distEndIndex = refreshURL.indexOf('-', distStartIndex + constDistance.length + 2);
				if (distEndIndex < 0)
					distEndIndex = refreshURL.indexOf('.html', distStartIndex + constDistance.length + 2);
				refreshURL = refreshURL.replace(refreshURL.substring(distStartIndex, distEndIndex), '');
			}            
			refreshURL = refreshURL.replace('-classifieds-refine', '-classifieds-refine-' + constDistance + '-' + constInventoryDefaultDistance).replace('-page-' + currentPage.toString(), '');
		} else if (refreshURL.indexOf('.html') > 0 && refreshURL.indexOf('-classifieds') > 0) {
			// html system
			var distStartIndex = refreshURL.indexOf('-' + constDistance + '-', 0);
			if (distStartIndex != -1) {
				var distEndIndex = refreshURL.indexOf('-', distStartIndex + constDistance.length + 2);
				if (distEndIndex < 0)
					distEndIndex = refreshURL.indexOf('.html', distStartIndex + constDistance.length + 2);
				refreshURL = refreshURL.replace(refreshURL.substring(distStartIndex, distEndIndex), '');
			}            
			refreshURL = refreshURL.replace('-classifieds', '-classifieds-' + constDistance + '-' + constInventoryDefaultDistance).replace('-page-' + currentPage.toString(), '');
		} else if (refreshURL.indexOf('.aspx')) {
			// aspx system
			if (refreshURL.indexOf('?') > 0) {
				if (refreshURL.indexOf('&' + constDistance + '=') >= 0) {
					var startIndex = refreshURL.indexOf('&' + constDistance + '=');
					var endIndex = refreshURL.indexOf('&', startIndex + 1);
					if (endIndex == -1) // last element
						refreshURL = refreshURL.substring(0, startIndex) + '&' + constDistance + '=' + constInventoryDefaultDistance;
					else
						refreshURL = refreshURL.substring(0, startIndex) + '&' + constDistance + '=' + constInventoryDefaultDistance + refreshURL.substring(endIndex);
				} else
					refreshURL = refreshURL + '&' + constDistance + '=' + constInventoryDefaultDistance;
			} else if (refreshURL.substring(refreshURL.length - 5) == '.aspx')
				refreshURL = refreshURL + '?' + constDistance + '=' + constInventoryDefaultDistance;
			refreshURL = refreshURL.replace('&page=' + currentPage.toString(), '');
		}
		strURL = strURL + 'userzipcode=' + zipCode.value;
		strURL = strURL + '&userid=' + document.getElementById('userId').value;
		strURL = strURL + '&userscreenname=' + document.getElementById('userScreenName').value;
		fcnMakeRequest(strURL, 1, '');
		setTimeout('window.location.href = ' + '\'' +  refreshURL + '\'', 1000);
		return true;
	} 
return false;
}

// New and Used Cars
function validateZipCodeBrowseCars(strURL,redirectURL) {
	var refreshURL  = 'window.location.href = \'' + redirectURL + 'makes=' + document.getElementById('sltMake').value;
	refreshURL = refreshURL + '&' + constDistance + '=' + constInventoryDefaultDistance + '\'';
	var zipCode = null;//document.getElementById(elementId);

	var elem = document.getElementsByName('txtZipCode');
	for(i = 0; i < elem.length; i++) {
		zipCodeN = elem[i];
		if (zipCodeN.value != 'Enter Zip' && zipCodeN.value != ''){ 
			zipCode = zipCodeN;
		}
	}

	zipCodeRegex = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
	if (zipCode == null || !zipCodeRegex.test(zipCode.value)) {
		alert('Zip code is not valid');
		return false;
	} else {
		strURL = strURL + 'userzipcode=' + zipCode.value;
		strURL = strURL + '&userid=' + document.getElementById('userId').value;
		strURL = strURL + '&userscreenname=' + document.getElementById('userScreenName').value;
		fcnMakeRequest(strURL,1,'');
		setTimeout(refreshURL, 1000);
		return true;
	}
}

/* Begin div popup common */
function mX(evt) {
	if (evt.pageX) return evt.pageX;
	else if (evt.clientX) return evt.clientX + (document.documentElement.scrollLeft ?
		document.documentElement.scrollLeft :
		document.body.scrollLeft);
	else return null;
}

function mY(evt) {
	if (evt.pageY) return evt.pageY;
	else if (evt.clientY) return evt.clientY + (document.documentElement.scrollTop ?
		document.documentElement.scrollTop :
		document.body.scrollTop);
	else return null;
}
/* End div popup common */

/* Begin Popup Help fuctions */
var popupTimer;
var currentPopup;
var insideLogo = false;
var insidePopup = false;

function RefreshPopup(el, evt, popupId1, dx, dy, popupId2) {
	if (insidePopup || insideLogo) {
		showPopup(el, evt, popupId1, dx, dy, popupId2);
	} else {
		hidePopup(popupId1, 1000, popupId2);
	}
}

function showHidePopup(popupId1, popupId2) {
	document.getElementById(popupId1).style.display = 'none'; 
	document.getElementById(popupId2).style.display = 'block'; 
}
function showPopup(el, evt, popupId1, dx, dy, popupId2) {
	var div = document.getElementById(popupId1);	
	if (div != currentPopup) {
		if (null != currentPopup) {
			currentPopup.style.visibility = 'hidden';
			currentPopup = null;
		}
//		div.style.left = (mX(evt) + dx) + 'px';
//		div.style.top = (mY(evt) + dy) + 'px';
		div.style.left = (findPos(el)[0] + el.offsetWidth / 2 + dx) + 'px';
		div.style.top = (findPos(el)[1] + el.offsetHeight / 2 + dy) + 'px';
		div.style.visibility = 'visible';
		currentPopup = div;
		if (popupId2 != '') {
			var div2 = document.getElementById(popupId2);
			if (div2 != null)
				div2.style.visibility = 'hidden';
		}
	}
	clearTimeout(popupTimer);
}

function PopupHelpHide(popupId1, popupId2) {
	var div = document.getElementById(popupId1);
	div.style.visibility = 'hidden';
	currentPopup.style.visibility = 'hidden';
	currentPopup = null;
	if (popupId2 != ''){
		var div2 = document.getElementById(popupId2);
		if (div2 != null)
			div2.style.visibility = 'visible';
	}
}

function hidePopup(popupId1, delay, popupId2) {
	popupTimer = setTimeout('PopupHelpHide("' + popupId1 + '","' + popupId2 + '")', delay);
}
/* End Popup Help fuctions  */
//--> 

/* Refine Search Block */
function ChangeDvRefineSearchChangeDiv(controlName) {
	var dvControl = document.getElementById(controlName);
	var hidden = document.getElementById('hidden' + controlName);
	var image = document.getElementById('img' + controlName);
	dvControl.style.display = hidden.value;
	if (hidden.value == 'none') {
		hidden.value='block';
		image.src = ImagePathFolder + 'arrowRight.gif';
	} else {
		hidden.value='none';
		image.src = ImagePathFolder + 'ArrowDown2.gif';
	}
}
/* End Refine Search Block */

function RefineSearchYears(url, ctrYearLowName, ctrYearHighName) {
	var newQuery;
	var path = '';
	if (url.indexOf('?') > -1) {
		path = url.substring(0, url.indexOf('?') + 1);
		newQuery = url.substring(url.indexOf('?') + 1) + '&';
	} else
		newQuery = url + '?';

	var ctrYearLow = document.getElementById(ctrYearLowName);
	var ctrYearHigh = document.getElementById(ctrYearHighName);
	newQuery = path + newQuery + ctrYearLowName + '=' + ctrYearLow.value + '&' + ctrYearHighName + '=' + ctrYearHigh.value;

window.location.href = newQuery;
}


function checkEmail(emailCtrl) {
	var email = emailCtrl.value;
	return checkEmailStr(email);
}

function checkEmailStr(email) {
	if(!(/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$/.test(email))) {
		return false;
	} else {
		return true;
	}
}

function checkEmpty(ctrl) {
	if (ctrl.value.length > 0)
		return true;
	else
		return false;
}

function checkAllowedChars(ctrl) {
	var regularExpression  =  /<|>/;
	var result = regularExpression.test(ctrl.value);
	if (result) 
		return false;
	else
		return true;
}

// show / hide tip text
function onfocus_search(tipText, ID, className) {
	var inputControl = document.getElementById(ID);
	inputControl.className = className;
	if (inputControl.value == tipText)
		inputControl.value = "";
}
function onblur_search(tipText, ID, className) {
	var inputControl = document.getElementById(ID);
	if (inputControl.value == "") {
		inputControl.className = className;
		inputControl.value = tipText;
	}
}
function validate_form(tipText, ID) {
	var inputControl = document.getElementById(ID);
	if (inputControl.value == tipText)
		return false;
	else
		return true;
}
function DealerInfoPopup(mylink, windowname) {
	if (!window.focus)
		return true;
	window.open(mylink.href, windowname, 'width=765,height=600,scrollbars=1,location=0');
	return false;
}

//validate leads
var errorMessage = "";

function checkFirstName() {
	var firstName = document.getElementById('txtFirstName').value; 
	if (firstName.length == 0) {
		errorMessage = errorMessage + "- Please provide your first name. \n";
		return false;
	}
	else
		return true;
}

function checkLastName() {
	var lastName = document.getElementById('txtLastName').value; 
	if (lastName.length == 0) {
		errorMessage = errorMessage + "- Please provide your last name. \n";
		return false;
	}
	else
		return true;	
}

function checkEmailAddress() {
	var email = document.getElementById('txtEmail').value;
	if(!(/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(email))) {
		errorMessage = errorMessage + '- Please provide your email address, so we may respond to your inquiry.\n';
		return false;
	} else {
		return true;
	}	
}

function checkPhoneNumber() {
	var obj = document.getElementById('txtPhone');
	if (obj.value.length > 0) {
		if (/^[0-9]{3}\-[0-9]{3}\-[0-9]{4}$/.test(obj.value)) {
			return true;
		} else {
			errorMessage = errorMessage + '- Please enter a phone number in 999-999-9999 format.\n';
			obj.value = "";
			obj.focus();
			return false;
		}
	}
	return true;
}

function checkComments() {
	var txtText = document.getElementById('txtRequestMoreInfoComment');
	var regularExpression  =  /<|>/;
	var result = regularExpression.test(txtText.value);
	if (result) {
		errorMessage = errorMessage + "<' and '>' chars are not allowed";
		txtText.focus();
		return false;
	}
	else
		return true;
}

function validateContactInformation(isFirstNameRequired, isLastNameRequired, isPhoneNumberRequired) {
	errorMessage = "";
	var error = checkComments(); 
	error = error & checkEmailAddress();
	if(isFirstNameRequired){
		error = error & checkFirstName();
	}
	if(isLastNameRequired){
		error = error & checkLastName();
	}
	if(isPhoneNumberRequired){
		error = error & checkPhoneNumber();
	}
	return error;
}

//Browser Detection and Redirection
function mobileRedirect(destination) {

	var browser = navigator.userAgent;

	if (browser.indexOf('802SH') != -1 ||
		browser.indexOf('Alcatel-') != -1 ||
		browser.indexOf('amoi') != -1 ||
		browser.indexOf('Android') != -1 ||
		browser.indexOf('AnexTek') != -1 ||
		browser.indexOf('AvantGo') != -1 ||
		browser.indexOf('AU-MIC') != -1 ||
		browser.indexOf('AUDIOVOX-') != -1 ||
		browser.indexOf('BlackBerry') != -1 ||
		browser.indexOf('Blazer') != -1 ||
		browser.indexOf('CDM-') != -1 ||
		browser.indexOf('Dopod-') != -1 ||
		browser.indexOf('Ericsson') != -1 ||
		browser.indexOf('hiptop') != -1 ||
		browser.indexOf('Hitachi-') != -1 ||
		browser.indexOf('HPiPAQ-') != -1 ||
		browser.indexOf('HTC-') != -1 ||
		browser.indexOf('iPhone') != -1 ||
		browser.indexOf('iPod') != -1 ||
		browser.indexOf('KDDI') != -1 ||
		browser.indexOf('LG') != -1 ||
		browser.indexOf('MM-') != -1 ||
		browser.indexOf('MO01') != -1 ||
		browser.indexOf('Mobile') != -1 ||
		browser.indexOf('MOT-') != -1 ||
		browser.indexOf('Motorola') != -1 ||
		browser.indexOf('N515i') != -1 ||
		browser.indexOf('N525i') != -1 ||
		browser.indexOf('NEC-') != -1 ||
		browser.indexOf('Nokia') != -1 ||
		browser.indexOf('NOKIA') != -1 ||
		browser.indexOf('OpenWeb') != -1 ||
		browser.indexOf('Opera mini') != -1 ||
		browser.indexOf('OPWV') != -1 ||
		browser.indexOf('Palm') != -1 ||
		browser.indexOf('Panasonic') != -1 ||
		browser.indexOf('Pantec') != -1 ||
		browser.indexOf('PG-') != -1 ||
		browser.indexOf('PLS') != -1 ||
		browser.indexOf('PM-') != -1 ||
		browser.indexOf('PN-') != -1 ||
		browser.indexOf('portalmmm') != -1 ||
		browser.indexOf('QCI-') != -1 ||
		browser.indexOf('RL-') != -1 ||
		browser.indexOf('SAGEM') != -1 ||
		browser.indexOf('Samsung') != -1 ||
		browser.indexOf('SAMSUNG') != -1 ||
		browser.indexOf('SCH') != -1 ||
		browser.indexOf('SCP-') != -1 ||
		browser.indexOf('SEC-') != -1 ||
		browser.indexOf('Sendo') != -1 ||
		browser.indexOf('SGH-') != -1 ||
		browser.indexOf('SHARP-') != -1 ||
		browser.indexOf('SIE-') != -1 ||
		browser.indexOf('Smartphone') != -1 ||
		browser.indexOf('SonyEricsson') != -1 ||
		browser.indexOf('SPH') != -1 ||
		browser.indexOf('SPV') != -1 ||
		browser.indexOf('UP.Browser') != -1 ||
		browser.indexOf('UP.Link') != -1 ||
		browser.indexOf('V60t') != -1 ||
		browser.indexOf('VI600') != -1 ||
		browser.indexOf('VK530') != -1 ||
		browser.indexOf('VM4050') != -1 ||
		browser.indexOf('Vodafone') != -1 ||
		browser.indexOf('VX10000') != -1 ||
		browser.indexOf('Windows CE') != -1 ||
		browser.indexOf('ZTE') != -1) {
			window.location=destination;
	}
}
//---------------Home page-----------------------------
//SaveState
function saveState() {

	for (i in boxArray) {
		var c = boxArray[i];
		if(!getVisibility(c+'Content')) {
			setCookie('home'+c);
		} else {
			delCookie('home'+c);
		}
	}
}

//RecallState
function recallState(boxName) {
	//alert(boxName + ' cookie = ' + evalCookie('home'+boxName));
	if(evalCookie('home'+boxName)) {
	   // toggle(boxName, eval(boxName+'Height'));
	}
}

//Welcome
function recallWelcome() {
	if (document.getElementById('BuyersContent').style.display == "none")
		expandObject('DealersContent');
	if (document.getElementById('DealersContent')) 
		if (document.getElementById('DealersContent').style.display == "none")
			expandObject('BuyersContent');
	toggleWelcome();
}

//HomePage Boxes
function getVisibility(obj) {
	var e = document.getElementById(obj);
	if (e) {
		if (e.style.display != "none") {
			return true;
		} else {
			return false;
		}
	}
}

function toggle(obj, h1) {
	toggleVisibility(obj + 'Content');
	if (document.getElementById(obj+'Table') != null) {
		toggleHeight(obj, h1, 30);
		toggleArrow(obj + 'Arrow');
	}
}

function toggleVisibility(obj) {
	var e = document.getElementById(obj);
	if ( e.style.display != "none" ) {
		e.style.display = 'none';
	} else {
		e.style.display = '';
	}
}

function toggleHeight(obj, h1, h2) {
	var et = document.getElementById(obj + 'Table');
	var eb = document.getElementById(obj + 'Body');
	if ( et.style.height == h1 + 'px') {
		et.style.height = h2 + 'px';
		eb.style.height = h2-2 + 'px';
	} else {
		et.style.height = h1 + 'px';
		eb.style.height = h1-2 + 'px';
	}
}

function toggleArrow(obj) {
	var e1 = document.getElementById(obj+'Up');
	var e2 = document.getElementById(obj+'Down');
	if ( e2.style.display == 'none') {
		e2.style.display = 'inline';
		e1.style.display = 'none';
	} else {
		e1.style.display = 'inline';
		e2.style.display = 'none';
	}
}

//Cookie Functionality
function setCookie(cookieName) {
	//if(evalCookie(cookieName) == false) {
		var expire = new Date ();
		expire.setTime (expire.getTime() + (2592000000)); //24 months from now!
		document.cookie = cookieName + '=true;expires=' + expire.toGMTString();
	//}
}

function delCookie(cookieName) {
	var ckyDate = new Date;
	document.cookie = cookieName+'=false;expires=' + 
		ckyDate.toGMTString( ) + ';';
}

function parseCookie() {
	tmpArray = document.cookie.split(';');
	cookieArray = new Array();
	j = 0;
	for (i in tmpArray) {
	  cookieArray[j] = tmpArray[i].split('=');
	  j++;
	}
}

function getCookie(cookieName) {
	for (i in cookieArray) {
	  if (cookieArray[i][0].toString().replace(' ', '') == cookieName) {
		 return cookieArray[i][1];
		}
	}
	return undefined;
}

function evalCookie(cookieName) {

	if (getCookie(cookieName) == undefined) {
		return false;
	} else {
		return true;
	}
}

function expandObject(obj) {
	document.getElementById(obj).style.width='100%';
}

function toggleWelcome() {
	if (document.getElementById('BuyersContent').style.display == "none" && document.getElementById('DealersContent').style.display == "none")
		toggleVisibility('WelcomeTable');
}

//Setup Boxes
function setup() {
	boxArray = new Array();
	boxArray[0] = 'Favorites';
	boxArray[1] = 'SavedSearches';
	boxArray[2] = 'Popular';
	boxArray[3] = 'Buyers';
	boxArray[4] = 'Dealers';
} 

//Parse Cookies
setup();
parseCookie();

// Functionality from Hendrick Search Vehicles control
var timerID = 0;

function btnSearchTab(obj, side, width) {
	tabList = 'Make,VehicleType,PriceRange,Features,MoreOptions';
	tabArray = tabList.split(",");
	for(var i=0; i<tabArray.length; i++){
		if (obj != tabArray[i]) {
			resetTab(tabArray[i]);
		}
	}

	if (obj != '') {
		tab = document.getElementById('Tab'+obj);
		tabLink = document.getElementById('TabLink'+obj);
		tabContent = document.getElementById('TabContent');
		tabContentType = document.getElementById('TabContent'+obj);

		if (tabLink.className != 'SearchVehiclesLinkOverlay') {
			intX = getRealLeft('Tab'+obj);
			intY = getRealTop('Tab'+obj);
			if (side == 1) intX = intX - width + 159;
			Flip = '';
			if (side == 1) Flip = 'Flip';
			tabContent.style.left = intX + (userAgent=='IE' ? 8 : 4) + 'px';
			tabContent.style.top = intY + (userAgent=='IE' ? 60 : 56) + 'px';
			document.getElementById('TabContentMiddle').style.width = width + 'px';
			tabContent.style.minWidth = width + 20 + 'px';
			tabContent.style.width = width + 20 + 'px';
			tab.className = 'SearchVehiclesButtonOverlay';
			tabLink.className = 'SearchVehiclesLinkOverlay';
			document.getElementById('TabContentLeft').className = 'SearchVehiclesLeft' +Flip;
			document.getElementById('TabContentTop').className = 'SearchVehiclesTop' +Flip;
			document.getElementById('TabContentRight').className = 'SearchVehiclesRight' +Flip;
			tabContent.style.display = '';
			tabContentType.style.display = '';
			document.getElementById('SelectedTab').value = obj;
			document.getElementById('SelectedTabSide').value = side;
			document.getElementById('SelectedTabWidth').value = width;
			clearTimeout(timerID);
		}
	} else {
		document.getElementById('TabContent').style.display = 'none';
	}
}

function setTabTimer(){
	if(timerID) {
		clearTimeout(timerID);
		timerID  = 0;
	}
	timerID = setTimeout("btnSearchTab('', 0, 0)", 500);
}

function resetTab(obj) {
	if (document.getElementById('Tab'+obj).className != 'SearchVehiclesButton') {
		document.getElementById('Tab'+obj).className = 'SearchVehiclesButton';
		document.getElementById('TabContent'+obj).style.display = 'none';
		document.getElementById('TabLink'+obj).className = 'SearchVehiclesLink';
	}
}

window.onresize = function () {
	if (document.getElementById('SelectedTab')) {
		obj = document.getElementById('SelectedTab').value;

		if (obj != "") {
			side = document.getElementById('SelectedTabSide').value;
			width = document.getElementById('SelectedTabWidth').value;

			tab = document.getElementById('Tab'+obj);
			tabContent = document.getElementById('TabContent');
			intX = getRealLeft('Tab'+obj);
			if (side == 1) { intX = intX - width + 159; }

			tabContent.style.left = intX + (userAgent=='IE' ? 8 : 4) + 'px';
		}
	}
}

function getRealLeft(el){
	xPos = document.getElementById(el).offsetLeft;
	tempEl = document.getElementById(el).offsetParent;
	while (tempEl != null) {
		xPos += tempEl.offsetLeft;
		tempEl = tempEl.offsetParent;
	}
	return xPos;
}

function getRealTop(el){
	yPos = document.getElementById(el).offsetTop;
	tempEl = document.getElementById(el).offsetParent;
	while (tempEl != null) {
		yPos += tempEl.offsetTop;
		tempEl = tempEl.offsetParent;
	}
	return yPos;
}

var timer = null;

function HideTab(tabName) {
	if (document.getElementById('Tab'+tabName).className != 'SearchVehiclesButton') {
		document.getElementById('Tab'+tabName).className = 'SearchVehiclesButton';
		document.getElementById('TabContent'+tabName).style.display = 'none';
		document.getElementById('TabLink'+tabName).className = 'SearchVehiclesLink';
	}
}
var _semaphore = false;
function HideAllWithExclude(excludeName) {
	var tabList = 'Make,VehicleType,PriceRange,Features,MoreOptions';
	var tabArray = tabList.split(",");
	for(var i=0; i<tabArray.length; i++){
		if (tabArray[i] != excludeName) {
			HideTab(tabArray[i]);
		}
	}
}

function HideAll() {
	HideAllWithExclude('');
	document.getElementById('TabContent').style.display = 'none';
}

function ShowTab(tabName, side, width) {
	if (_semaphore)
		return;
	_semaphore = true;
	HideAllWithExclude(tabName);
	if (tabName != '') {
		var tab = document.getElementById('Tab'+tabName);
		var tabLink = document.getElementById('TabLink'+tabName);
		var tabContent = document.getElementById('TabContent');
		var tabContentType = document.getElementById('TabContent'+tabName);

		if (tabLink.className != 'SearchVehiclesLinkOverlay') {
			var position = $('#Tab' + tabName).offset();
			//var intX = getRealLeft('Tab'+tabName);
			//var intY = getRealTop('Tab'+tabName);
			
			var Flip = '';
			switch (side) {
				case 0:
					position.left = position.left + 4;
					position.top = position.top + 56;
					break;
				case 1:
					position.left = position.left - width + 163;
					position.top = position.top + 56;
					Flip = 'Flip';
					break;
				case 2:
					position.left = position.left + 174 + 25 + 4;
					break;
				case 3:
					position.left = position.left + 174 + 25 + 4;
					position.top = position.top  - 177;
					break;
			}
			$(tabContent).css(position);
			
			document.getElementById('TabContentMiddle').style.width = width + 'px';
			tabContent.style.minWidth = width + 20 + 'px';
			tabContent.style.width = width + 20 + 'px';
			tab.className = 'SearchVehiclesButtonOverlay';
			tabLink.className = 'SearchVehiclesLinkOverlay';
			document.getElementById('TabContentLeft').className = 'SearchVehiclesLeft' + Flip;
			document.getElementById('TabContentTop').className = 'SearchVehiclesTop' + Flip;
			document.getElementById('TabContentRight').className = 'SearchVehiclesRight' + Flip;
			tabContent.style.display = '';
			tabContentType.style.display = '';
			document.getElementById('SelectedTab').value = tabName;
			document.getElementById('SelectedTabSide').value = side;
			document.getElementById('SelectedTabWidth').value = width;
		}
	} else {
		document.getElementById('TabContent').style.display = 'none';
	}
	_semaphore = false;
}		

// FindYourCar Home page's control
function validateZipCodeFindYourCar(strURL,redirectURL) {
	var refreshURL = 'window.location.href = \'' + redirectURL;
	if (document.getElementById('sltMake').value != 0) {
		refreshURL = refreshURL + 'makes=' + document.getElementById('sltMake').value;
		if (document.getElementById('sltModel').value != 0) {
			refreshURL = refreshURL + '&models=' + document.getElementById('sltModel').value;
		}
		if (document.getElementById('txtZipCode').value != 0) {
			refreshURL = refreshURL + '&zip=' + document.getElementById('txtZipCode').value;
		}
		if (document.getElementById('sltDistance')!= null && document.getElementById('sltDistance').value != 0) {
			refreshURL = refreshURL + '&' + constDistance + '=' + document.getElementById('sltDistance').value+ '\'';
		}else {
			refreshURL = refreshURL + '&' + constDistance + '=' + constInventoryDefaultDistance + '\'';
		}
	} else {
		alert('Selected make is not valid');
		return false;
	}

	
	var zipCode = document.getElementById('txtZipCode');
	zipCodeRegex = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
	if (zipCode == null || !zipCodeRegex.test(zipCode.value)) {
		alert('Zip code is not valid');
		return false;
	} else {
		if (zipCode.value != '') {
			strURL = strURL + 'userzipcode=' + zipCode.value;
			strURL = strURL + '&userid=' + document.getElementById('userId').value;
			strURL = strURL + '&userscreenname=' + document.getElementById('userScreenName').value;
			fcnMakeRequest(strURL,1,'');
		}
		setTimeout(refreshURL, 1000);
		return true;
	}
}

// FindYourCar2 Home page's control
function validateZipCodeFindYourCar2(strURL,redirectURL) {
	var refreshURL = 'window.location.href = \'' + redirectURL;
	if (document.getElementById('findCarsMakeId').value != 0) {
		refreshURL = refreshURL + 'makes=' + document.getElementById('findCarsMakeId').value;
		if (document.getElementById('findCarsModelId').value != 0) {
			refreshURL = refreshURL + '&models=' + document.getElementById('findCarsModelId').value;
		}
		if (document.getElementById('findCarsZipId').value != 0) {
			refreshURL = refreshURL + '&zip=' + document.getElementById('findCarsZipId').value;
		}
		if (document.getElementById('findCarsWithinId')!= null && document.getElementById('findCarsWithinId').value != 0) {
			refreshURL = refreshURL + '&' + constDistance + '=' + document.getElementById('findCarsWithinId').value+ '\'';
		}else {
			refreshURL = refreshURL + '&' + constDistance + '=' + constInventoryDefaultDistance + '\'';
		}
	} else {
		alert('Selected make is not valid');
		return false;
	}

	
	var zipCode = document.getElementById('findCarsZipId');
	zipCodeRegex = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
	if (zipCode == null || !zipCodeRegex.test(zipCode.value)) {
		alert('Zip code is not valid');
		return false;
	} else {
		if (zipCode.value != '') {
			strURL = strURL + 'userzipcode=' + zipCode.value;
			strURL = strURL + '&userid=' + document.getElementById('userId').value;
			strURL = strURL + '&userscreenname=' + document.getElementById('userScreenName').value;
			fcnMakeRequest(strURL,1,'');
		}
		setTimeout(refreshURL, 1000);
		return true;
	}
}

function insertZipCodeIntoMakeControl(Zip){
	var zipInput = document.getElementById('txtZipCode');
	if (zipInput != null)
		zipInput.value = Zip;
}
//Ajax JQuery
function getModelList() {
	$.ajax({
		type: "POST",
		url: AppRoot + "templates/hometemplates/home.asmx/GetModelList",
		data: "{makeId: "+ $('#sltMake').attr('value')+" }",
		contentType: "application/json; charset=utf-8",
		dataType: "text",
		success: function(response) {
			var cars = (typeof response) == 'string' ? eval('(' + response + ')') : response;
			$('#sltModel').empty();
			$('#sltModel').append('<option value="0">Select Model</option>');
			$('#sltModel').append(cars);
		},
		failure: function(msg) {
			$('#output').text(msg);
		}
	});
}

//----------------Inventory-------------------------------

/* Begin Contact Popup */
var _isFirstNameRequired = true, _isLastNameRequired = true, _isPhoneNumberRequired = true;

function ContactPopupShow(url, evt, isFirstNameRequired, isLastNameRequired, isPhoneNumberRequired) {
	var div = document.getElementById('InventoryContact');
	div.style.top = mY(evt) - 42 + 'px';
	div.style.left = mX(evt) - 350 + 'px';
	div.style.visibility = 'visible';
	div.action = url;
	_isFirstNameRequired = isFirstNameRequired;
	_isLastNameRequired = isLastNameRequired;
	_isPhoneNumberRequired = isPhoneNumberRequired;
	return;
}

function ContactPopupHide() {
	var div = document.getElementById('InventoryContact');
	div.style.visibility = 'hidden';
	return;
}

function ContactPopupConfirmationShow() {
	var div = document.getElementById('InventoryContactConfirmation');
	var divOrig = document.getElementById('InventoryContact');
	div.style.top = divOrig.style.top;
	div.style.left = divOrig.style.left;
	div.style.visibility = 'visible';
	return;
}

function ContactPopupConfirmationHide() {
	var div = document.getElementById('InventoryContactConfirmation');
	div.style.visibility = 'hidden';
	return;
}

function validateContactSellerOnInventoryPage() {
	if(validateContactInformation(_isFirstNameRequired, _isLastNameRequired, _isPhoneNumberRequired)) {
		document.getElementById('InventoryContact').submit();
		ContactPopupConfirmationShow();
		ContactPopupHide();
		return true;
	} else {
		alert('You must enter a proper value in the following fields:\n' + errorMessage);
		return false;
	}
}
/* End Contact Popup */

/* Begin Zip Code Change Popup */
var zipChangeDelay = null;
var zipChangeDelayTime = 3000;

function ZipCodeChangePopupShow(zipCode,evt) {
	document.getElementById('ZipCodeChangeBox').value = zipCode;
	var div = document.getElementById('ZipCodeChange');
	div.style.top = mY(evt) - 90 + 'px';
	div.style.left = mX(evt) - 20 + 'px';
	div.style.visibility = 'visible';
	return;
}

function ZipCodeChangePopupHide() {
	var div = document.getElementById('ZipCodeChange');
	div.style.visibility = 'hidden';
	return;
}

function onZipCodeChangePopupHover() {
	if (zipChangeDelay) clearTimeout(zipChangeDelay);
	return;
}

function onZipCodeChangePopupOut() {
	zipChangeDelay = setTimeout('ZipCodeChangePopupHide()', zipChangeDelayTime);
	return;
}
/* End Zip Code Change Popup */

function responseFromInventorySubmitContact(result, context) {
	var fileref=document.createElement('div')
	fileref.innerHTML = result;
	document.getElementById("CustomHtmlPlaceholder").appendChild(fileref)
}

function setPageSize(rows, refreshURL) {
	var expire = new Date();
	expire.setTime (expire.getTime() + (2592000000)); //30 days from now!
	document.cookie = 'EBizAutosBuyersSiteCookiePageSizeNew=' + rows + ';expires=' + expire.toGMTString() + ';path=/';
	UpdatePageSize(rows);
	setTimeout('window.location.href = ' + '\'' +  refreshURL + '\'', 200);
}

function OnPageSizeUpdate(res) {
}
/*   Popup Cpo       */
function RefreshPopupCpo(el, evt, popupId, dx, dy, url) {
	if (insidePopup || insideLogo) {
		showPopupCpo(el, evt, popupId, dx, dy, url);
	} else {
		hidePopup(popupId, 1000, '');
	}
}

function showPopupCpo(el, evt, popupId, dx, dy, url) {
	if (!insidePopup) {
		var div = document.getElementById(popupId);
		var link = document.getElementById(popupId + 'DetailLink');
		
		if (div != currentPopup || div.style.visibility == 'visible') {
			if (null != currentPopup) {
				currentPopup.style.visibility = 'hidden';
				currentPopup = null;
			}
			var position = $(el).offset();
			position.left = position.left + el.offsetWidth / 2 + dx;
			position.top = position.top + el.offsetHeight / 2 + dy;
			$(div).css(position);
			div.style.visibility = 'visible';
			
			link.href=url;
			currentPopup = div;
			}
		}	
	clearTimeout(popupTimer);
}

//------------Details------------------------

/* Begin Contact Us Form */

function validateContactInfo(isFirstNameRequired, isLastNameRequired, isPhoneNumberRequired) {
	if(validateContactInformation(isFirstNameRequired, isLastNameRequired, isPhoneNumberRequired)) {
		document.getElementById('DetailContact').submit();
		document.getElementById('DetailContact').style.display = 'none';
		document.getElementById('DetailContactConfirmation').style.display = '';
		return true;
	} else {
		alert('You must enter a proper value in the following fields:\n' + errorMessage);
		return false;
	}
}
/* End Contact Us Form */

/* Share Vodeo */
function SwitchToVideo() {
	document.getElementById('Video0').style.display = 'block';
	document.getElementById('ShareVideo0').style.display = 'none';
}			
function SwitchToForm() {
	document.getElementById('Video0').style.display = 'none';
	document.getElementById('ShareVideo0').style.display = 'block';
}			
function validateShareVideoControls() {
	errorMessage = "";
	var firstNameCtrl = document.getElementById('txtName');
	error = true;
	if (!checkEmpty(firstNameCtrl)) {
		errorMessage = errorMessage + "- Please provide your name. \n";
		error = false;
	} else {
		if (!checkAllowedChars(firstNameCtrl)) {
			errorMessage = errorMessage + "- Chars '<' and '>' are not allowed in Your Name \n";
			error = false;
		} 
	}
	
	if (!checkEmail(document.getElementById('txtYourEmail'))) {
		error = false;
		errorMessage =  errorMessage + "- Please provide your email address  \n";
	}
	var emails = document.getElementById('txtRecipientEmails').value.replace(/\s/gi," ").split(',');
	for(i = 0; i < emails.length; i++) {
		if (trim(emails[i]).length > 0 && !checkEmailStr(trim(emails[i]))) {
			error = false;
			errorMessage =  errorMessage + "- Please provide correct recepient email addresses (separated by commas)  \n";
			break;
		}
	}
	if (!checkAllowedChars(document.getElementById('txtMessage'))) {
		error = false;
		errorMessage =  errorMessage + "- - Chars '<' and '>' are not allowed in Personal Message text \n";
	}
	if (!error) {
		alert('You must enter a proper value in the following fields:\n' + errorMessage);
		return false;
	}
	return true;
}

function clearShareVideoControls() {
	document.getElementById('txtName').value = "";
	document.getElementById('txtYourEmail').value = "";
	document.getElementById('txtRecipientEmails').value = "";
	document.getElementById('txtMessage').value = "";
	document.getElementById('chkSendCopy').checked = false;
}
function responseFromAJAX(result, context) {
	if ('True' == result) {
		alert('Your message has been sent.');
		SwitchToVideo();
	} else {
		alert('An error occured while sending your message. Please try again later.');
	}
}
/* End Share Vodeo */

function responseFromDetailSubmitContact(result, context) {
//	document.getElementById("CustomHtmlPlaceholder").innerHTML = result; // this is an example of how IT SHOULD NOT BE CODED. Please use below code as refer.

	var fileref=document.createElement('div')
	fileref.innerHTML = result;
	document.getElementById("CustomHtmlPlaceholder").appendChild(fileref)
}

function VehicleBrochurePopupHide(){
var div = document.getElementById('VehicleBrochure');
	div.style.display = 'none';
	return;
}
function VehicleBrochurePopupShow() {
	var div = document.getElementById('VehicleBrochure');
	var testEl = document.getElementById('test');
	var testPos = findPos(testEl);    
	div.style.display = 'block';
	div.style.top = (testPos[1] - 180) + 'px';
	div.style.left = (testPos[0] + 10) + 'px';
	return;
}

function CreditApp(mylink, windowname) {
	if (!window.focus)
		return true;
	window.open(mylink.href, windowname, 'width=780,height=600,scrollbars=1,location=0');
	return false;
}

// --------------- SocialLinksPopup start
var isActive_SocialLinks = false;
var isActiveLinks_SocialLinks = false;
var timeId_SocialLinks = 0;

function hideLinksPopup_SocialLinks() {
	if (!isActive_SocialLinks && !isActiveLinks_SocialLinks) {
		document.getElementById("SocialLinksIconsImageHover").style.display = "none";
		document.getElementById("SocialLinksIconsImage").style.display = "inline";

		var div = document.getElementById("SocialLinksPopup");
		div.style.display = "none";
	} else {
		timeId_SocialLinks = setTimeout(hideLinksPopup_SocialLinks, 200);
	}
}

function showLinksPopup_SocialLinks() {
	document.getElementById("SocialLinksIconsImage").style.display = "none";
	document.getElementById("SocialLinksIconsImageHover").style.display = "inline";
	var img = $("#SocialLinksIconsImageHover");
	var newPos = img.offset();

	var div = $("#SocialLinksPopup");
	newPos.top = newPos.top + img.height() - 1;
	newPos.left = newPos.left + img.width() - div.width();
	div.css(newPos);
	div.css("display", "block");
}

function on_mouseover_SocialLinks() {
	if (!isActive_SocialLinks) {
		isActive_SocialLinks = true;
		showLinksPopup_SocialLinks();
	}

	clearTimeout(timeId_SocialLinks);
	timeId_SocialLinks = setTimeout(hideLinksPopup_SocialLinks, 200);
}

function on_mouseout_SocialLinks() {
	isActive_SocialLinks = false;
}

function on_mouseoverLinks_SocialLinks() {
	if (!isActiveLinks_SocialLinks) {
		isActiveLinks_SocialLinks = true;
		showLinksPopup_SocialLinks();
	}

	clearTimeout(timeId_SocialLinks);
	timeId_SocialLinks = setTimeout(hideLinksPopup_SocialLinks, 200);
}

function on_mouseoutLinks_SocialLinks() {
	isActiveLinks_SocialLinks = false;
}
// --------------- SocialLinksPopup end



// --------------- FindYourCar start
function initMakesList(){
	if ($(".dropdownMakeList").html() != "")
		return;
	$('.dropdownMake').bgiframe();
	var resultingHTML = '<div class="makeItem">Select Make</div>';
	for (i = 0; i < _globalMakesList.length; i++) {
		resultingHTML += '<div class="makeItem selectorMakeId-' + 
					_globalMakesList[i].makeId  + 
					'">' + 
					_globalMakesList[i].makeName  + 
					'</div>'						
	}
	$(".dropdownMakeList").html(resultingHTML);
	//hover style handler;
	$(".makeItem").mouseenter(function(){
		$(this).toggleClass("itemsHovered");
	});
	$(".makeItem").mouseleave(function(){
		$(this).toggleClass("itemsHovered");
	});
	//on item click handler for make
	$(".makeItem").click(function(){
		$(".wrapperMake > .initialLabel").html($(this).html());
		$(".wrapperMake > .dropdownMake").addClass("hidden");
		var classes = $(this).attr("class").split(" ");
		for (i=0; i < classes.length; i++) {
			if (classes[i].indexOf("selectorMakeId") > -1) {
				var makeId = classes[i].split("-")[1];
				getModelListJson(makeId, fillInModels);
				$("#findCarsMakeId").val(makeId);
				clearTimeout(timerMake);
				return;
			}	
		}
	});
	//slider initialization
	var listHeight = $(".dropdownMakeList").height() -  194;
	$(".dropdownMakeScrollerArea").slider({
						animate: true, 
						orientation: "vertical", 
						min: -listHeight, 
						max: 0,
						value: 0,
						slide: slideMakes
	});
	// button up initialization
	$(".dropdownMakeButtonUp").click(function() {
		var currentValue = $(".dropdownMakeScrollerArea").slider("value");
		currentValue += 15;
		$(".dropdownMakeScrollerArea").slider("value", currentValue);
		if (currentValue < -listHeight)
			currentValue = -listHeight;
		if (currentValue > 0)
			currentValue = 0;
		$(".dropdownMakeList").css("top", currentValue + "px");	 	
	});
	// button down initialization
	$(".dropdownMakeButtonDown").click(function() {
		var currentValue = $(".dropdownMakeScrollerArea").slider("value");
		currentValue -= 15;
		$(".dropdownMakeScrollerArea").slider("value", currentValue);
		if (currentValue < -listHeight)
			currentValue = -listHeight;
		if (currentValue > 0)
			currentValue = 0;
		$(".dropdownMakeList").css("top", currentValue + "px");
	});
	//hide if mouse out of list for more than 200ms
	var timerMake;
	$(".dropdownMake").mouseleave(function() {
		timerMake = setTimeout('$(".dropdownMake").addClass("hidden");', 500);
	})
	$(".dropdownMake").mouseenter(function() {
		clearTimeout(timerMake);
	});							

}

function slideMakes (event, ui) {
	$(".dropdownMakeList").css("top", ui.value + "px");	
}
function slideModels (event, ui) {
	$(".dropdownModelList").css("top", ui.value + "px");	
}

function fillInModels(modelList, dontCorrectInitialLabel) {
	if (!dontCorrectInitialLabel)
		$(".wrapperModel > .initialLabel").html("Select Model");	
	var resultingHTML = '<div class="modelItem">Select Model</div>';
	for (i = 0; i < modelList.length; i++) {
		resultingHTML += '<div class="modelItem selectorModelId-' + 
					modelList[i].modelId  + 
					'">' + 
					modelList[i].modelName  + 
					'</div>'						
	}
	$(".dropdownModelList").html(resultingHTML);
	
	
	
} 

function initModelsList() {
	//remove item listeners;
	$(".modelItem").unbind('mouseenter');
	$(".modelItem").unbind('mouseleave');
	$(".modelItem").unbind('click');
	//remove button listeners;
	$(".dropdownModelButtonUp").unbind('click');
	$(".dropdownModelButtonDown").unbind('click');
	$(".dropdownModel").unbind('mouseleave');
	$(".dropdownModel").unbind('mouseenter');		

	//hover style handler;
	$(".modelItem").bind('mouseenter',function(){
		$(this).toggleClass("itemsHovered");
	});
	$(".modelItem").bind('mouseleave',function(){
		$(this).toggleClass("itemsHovered");
	});
	var timerModel;
	//on item click handler for make
	$(".modelItem").bind('click',function(){
		$(".wrapperModel > .initialLabel").html($(this).html());
		$(".wrapperModel > .dropdownModel").addClass("hidden");
		var classes = $(this).attr("class").split(" ");
		for (i=0; i < classes.length; i++) {
			if (classes[i].indexOf("selectorModelId") > -1) {
				var modelId = classes[i].split("-")[1];
				$("#findCarsModelId").val(modelId);
				clearTimeout(timerModel);
				return;
			}	
		}
	});
					//clear slider;
	if ($(".dropdownModelScrollerArea").slider)
		$(".dropdownModelScrollerArea").slider("destroy");
	//new slider initialization
	var listHeight = $(".dropdownModelList").height() -  194;
	if (listHeight > 0) {
		$(".dropdownModelList").css("top", "0px");	
		$(".dropdownModelScrollerArea").slider({
							animate: true, 
							orientation: "vertical", 
							min: -listHeight, 
							max: 0,
							slide: slideModels
		});
		// button up initialization
		$(".dropdownModelButtonUp").bind('click',function() {
			var currentValue = $(".dropdownModelScrollerArea").slider("value");
			currentValue += 15;
			$(".dropdownModelScrollerArea").slider("value", currentValue);
			if (currentValue < -listHeight)
				currentValue = -listHeight;
			if (currentValue > 0)
				currentValue = 0;
			$(".dropdownModelList").css("top", currentValue + "px");	 	
		});
		// button down initialization
		$(".dropdownModelButtonDown").bind('click',function() {
			var currentValue = $(".dropdownModelScrollerArea").slider("value");
			currentValue -= 15;
			$(".dropdownModelScrollerArea").slider("value", currentValue);
			if (currentValue < -listHeight)
				currentValue = -listHeight;
			if (currentValue > 0)
				currentValue = 0;
			$(".dropdownModelList").css("top", currentValue + "px");	 	
		});
	}
	//hide if mouse out of list for more than 500ms
	$(".dropdownModel").bind('mouseleave',function() {
		timerModel = setTimeout('$(".dropdownModel").addClass("hidden");', 500);		
	})
	$(".dropdownModel").bind('mouseenter',function() {
		clearTimeout(timerModel);
	});
	$('.dropdownModel').bgiframe();
}

function initDropdownWithin() {
	if ($(".dropdownWithin").html() != "")
		return; 
	$('.dropdownWithin').bgiframe();
	var timerWithin;              
	var selectedClass = "";
	var resultingHTML = "";
	resultingHTML = '<div class="withinItem firstWithinItem">' + 'Pick value' + '</div>';
	for (i = 0; i < withinList.length; i++) {
		if (withinList[i].withinName == $(".wrapperWithin .initialLabel").html())
			selectedClass = " itemsSelected";
		else 
			selectedClass = "";
		resultingHTML += '<div class="withinItem selectorWithinId-' + 
					withinList[i].withinId  + selectedClass +
					'">' + 
					withinList[i].withinName  + 
					'</div>'						
	}
	$(".dropdownWithin").html(resultingHTML);
	//hover style handler;
	$(".withinItem").mouseenter(function(){
		$(this).toggleClass("itemsHovered");
	});
	$(".withinItem").mouseleave(function(){
		$(this).toggleClass("itemsHovered");
	});
	//on item click handler for make
	$(".withinItem").click(function(){
		$(".wrapperWithin > .initialLabel").html($(this).html());
		$(".wrapperWithin > .dropdownWithin").addClass("hidden");
		var classes = $(this).attr("class").split(" ");
		for (i=0; i < classes.length; i++) {
			if (classes[i].indexOf("selectorWithinId") > -1) {
				$(".wrapperWithin .itemsSelected").removeClass("itemsSelected");
				$(this).addClass("itemsSelected");
				var withinId = classes[i].split("-")[1];
				$("#findCarsWithinId").val(withinId);
				clearTimeout(timerWithin);
				return;
			}	
		}
	});
	//hide if mouse out of list for more than 500ms
	$(".dropdownWithin").bind('mouseleave',function() {
		timerWithin = setTimeout('$(".dropdownWithin").addClass("hidden");', 500);
	})
	$(".dropdownWithin").bind('mouseenter',function() {
		clearTimeout(timerWithin);
	});	
}
var withinList = [
			{withinId: 50, withinName: "50 Miles"},
			{withinId: 100, withinName: "100 Miles"},
			{withinId: 250, withinName: "250 Miles"},
			{withinId: 500, withinName: "500 Miles"},
			{withinId: 9999, withinName: "Any Distance"}
		];


function getModelListJson(makeId, fnCallback) {
	$.ajax({
		type: "POST",
		url: AppRoot + "templates/hometemplates/home.asmx/GetModelListJson",
		data: "{makeId: "+makeId+"}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(response) {
			fnCallback(eval(response));
		},
		failure: function(msg) {
			return [];
		}
	});
}
function setInitialValuesForDropdown(makeId, makeName, modelId, modelName, distance) {
	//make label and makeId 
	if (makeId > 0) {
		$(".wrapperMake > .initialLabel").html(makeName);
		$("#findCarsMakeId").val(makeId);
		//fetch models for this make
		if (modelId > 0)
			getModelListJson(makeId, function(modelList) {
										fillInModels(modelList, true);
									});
		else 
			getModelListJson(makeId, function(modelList) {
										fillInModels(modelList);
									});
	}
	if (modelId > 0) {
		//model label and modelId
		$(".wrapperModel > .initialLabel").html(modelName);
		$("#findCarsModelId").val(modelId);
	}
	//within = distance
	for (var i = 0; i < withinList.length; i++) 
		if (withinList[i].withinId == distance) 
			$(".wrapperWithin > .initialLabel").html(withinList[i].withinName);
	$("#findCarsWithinId").val(distance);
			
}
// --------------- FindYourCar end

//------------------Dealer Locator start

function initDropdownState() {
	if ($(".dropdownStateList").html() != "")
		return; 
	var timerState;                
	resultingHTML = '<div class="stateItem">Select State</div>';
	for (i = 0; i < _statesList.length; i++) {
		resultingHTML += '<div class="stateItem">' + 
					_statesList[i].stateName  + 
					'</div>'						
	}
	$(".dropdownStateList").html(resultingHTML);
	//hover style handler;
	$(".stateItem").mouseenter(function(){
		$(this).toggleClass("itemsHovered");
	});
	$(".stateItem").mouseleave(function(){
		$(this).toggleClass("itemsHovered");
	});
	//on item click handler for make
	$(".stateItem").click(function(){
		$(".wrapperState > .initialLabel").html($(this).html());
		$(".wrapperState > .dropdownState").addClass("hidden");
		$("#stateDealerLocator").val($(this).html());
	});
	//slider initialization
	var listHeight = $(".dropdownStateList").height() -  194;
	$(".dropdownStateScrollerArea").slider({
						animate: true, 
						orientation: "vertical", 
						min: -listHeight, 
						max: 0,
						value: 0,
						slide: slideStates
	});
	// button up initialization
	$(".dropdownStateButtonUp").click(function() {
		var currentValue = $(".dropdownStateScrollerArea").slider("value");
		currentValue += 15;
		$(".dropdownStateScrollerArea").slider("value", currentValue);
		if (currentValue < -listHeight)
			currentValue = -listHeight;
		if (currentValue > 0)
			currentValue = 0;
		$(".dropdownStateList").css("top", currentValue + "px");	 	
	});
	// button down initialization
	$(".dropdownStateButtonDown").click(function() {
		var currentValue = $(".dropdownStateScrollerArea").slider("value");
		currentValue -= 15;
		$(".dropdownStateScrollerArea").slider("value", currentValue);
		if (currentValue < -listHeight)
			currentValue = -listHeight;
		if (currentValue > 0)
			currentValue = 0;
		$(".dropdownStateList").css("top", currentValue + "px");
	});
	//hide if mouse out of list for more than 500ms
	$(".dropdownState").bind('mouseleave',function() {
		timerState = setTimeout('$(".dropdownState").addClass("hidden");', 500);
	})
	$(".dropdownState").bind('mouseenter',function() {
		clearTimeout(timerState);
	});	
	
}

function slideStates (event, ui) {
	$(".dropdownStateList").css("top", ui.value + "px");	
}

function initDropdownMakeLocator() {
	if ($(".dropdownMakeLocatorList").html() != "")
		return; 
	var timerState;                
	resultingHTML = '<div class="makeLocatorItem">Select Make</div>';
	for (i = 0; i < _globalMakesListDealerLocator.length; i++) {
		resultingHTML += '<div class="makeLocatorItem">' + 
					_globalMakesListDealerLocator[i].makeName  + 
					'</div>'						
	}
	$(".dropdownMakeLocatorList").html(resultingHTML);
	//hover style handler;
	$(".makeLocatorItem").mouseenter(function(){
		$(this).toggleClass("itemsHovered");
	});
	$(".makeLocatorItem").mouseleave(function(){
		$(this).toggleClass("itemsHovered");
	});
	//on item click handler for make
	$(".makeLocatorItem").click(function(){
		$(".wrapperMakeLocator > .initialLabel").html($(this).html());
		$(".wrapperMakeLocator > .dropdownMakeLocator").addClass("hidden");
		$('#brandDealerLocator').val($(this).html());
	});
	//slider initialization
	var listHeight = $(".dropdownMakeLocatorList").height() -  194;
	$(".dropdownMakeLocatorScrollerArea").slider({
						animate: true, 
						orientation: "vertical", 
						min: -listHeight, 
						max: 0,
						value: 0,
						slide: slideMakeLocator
	});
	// button up initialization
	$(".dropdownMakeLocatorButtonUp").click(function() {
		var currentValue = $(".dropdownMakeLocatorScrollerArea").slider("value");
		currentValue += 15;
		$(".dropdownMakeLocatorScrollerArea").slider("value", currentValue);
		if (currentValue < -listHeight)
			currentValue = -listHeight;
		if (currentValue > 0)
			currentValue = 0;
		$(".dropdownMakeLocatorList").css("top", currentValue + "px");	 	
	});
	// button down initialization
	$(".dropdownMakeLocatorButtonDown").click(function() {
		var currentValue = $(".dropdownMakeLocatorScrollerArea").slider("value");
		currentValue -= 15;
		$(".dropdownMakeLocatorScrollerArea").slider("value", currentValue);
		if (currentValue < -listHeight)
			currentValue = -listHeight;
		if (currentValue > 0)
			currentValue = 0;
		$(".dropdownMakeLocatorList").css("top", currentValue + "px");
	});
	//hide if mouse out of list for more than 500ms
	$(".dropdownMakeLocator").bind('mouseleave',function() {
		timerState = setTimeout('$(".dropdownMakeLocator").addClass("hidden");', 500);
	})
	$(".dropdownMakeLocator").bind('mouseenter',function() {
		clearTimeout(timerState);
	});	
	
}

function slideMakeLocator (event, ui) {
	$(".dropdownMakeLocatorList").css("top", ui.value + "px");	
}
//------------------Dealer Locator end