﻿<!-- 

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, 'addToFavoritesCookie');
        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://www.zibe.com/image/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 zipCode = document.getElementById('ZipCodeInputBox');
    if (zipCode.value == 'Enter Zip'){ 
        zipCode.value = '';
        zipCode.style.color = '#000000';
    }
    return true;
}

// Detail
function validateZipCode(strURL,itemLatitude,itemLongitude) {
    var zipCode = document.getElementById('ZipCodeInputBox');
    zipCodeRegex = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
    if (!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 = document.getElementById(elementId);
    zipCodeRegex = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
    if (!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 = document.getElementById('txtZipCode');
    zipCodeRegex = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
    if (!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 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('?')) {
        path = url.substring(0, url.indexOf('?') + 1);
        newQuery = url.substring(url.indexOf('?') + 1);
    } else
        newQuery = url;
    if (newQuery.length > 0)
        newQuery += '&';
    else
        newQuery = '?';

    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;
}