/* Utility Javascript functions common across pages
 *  $Author:  Rick Critchett
 *  $Date: 11-Sep-03
 *  $Updated date: 01-Jan-2011 By Nigam Patel
 */
 
// Initialization
// Browser determination
var bName = navigator.appName;
var agt = navigator.userAgent.toLowerCase();
var NS = (bName == "Netscape");
var IE = (bName == "Microsoft Internet Explorer");
var IE5x = (agt.indexOf("msie 5") != -1);
var bVer = parseInt(navigator.appVersion);
var NS4 = (NS && bVer < 5);
var NS6 = (NS && bVer >= 5);
// rwc: 15-Sep-03. the above works!  Use these vars.
var IESP2 = (agt.indexOf("sv1") != -1); // IE with Service Pack 2
var isMac = (agt.indexOf('mac') != -1);
var isMacIE5x = (isMac && IE5x);

var winVar = null;
var actionVar;
// Global reference variables
var docRef = "document.";
if(NS4)  docRef = "document.";
if(NS6)  docRef = "document.";
if(IE)  docRef = "document.all.";

//Netscape seems to need these document array initialized here and not lazily
document.preloadArray = new Array();
document.chosenPhotos = new Array();
chosenCaptions = new Array();
var chosenPhotoIMGobjectName = "chosenPhotoIMG";
var chosenPhotoDIVobjectName = "chosenPhotoCaption";
// Vehicle information
var currMake = null;
var currModel = null;

// global var to track currently enlarged photo when choosePhoto(n) is called
// this var is passed to the multi photo popup which autoscrolls to the corresponding pic
var lastChosenPhotoIndex = 0;

//utility merger from search app
var debugOn = false;
var cookieUrl = "/for-sale/spanishcookie.action";

/*
 * swapImage FUNCTION
 * @param refName name of the IMG object
 * @param imgName name of the image-not a complete filename
 * @param imgState desired state of the image-used to complete filename
 */
function swapImage(refName,imgName,imgState)
{
    var imgRef = eval(docRef + refName);
    imgRef.src = "images/" + imgName + imgState + ".gif";
}

/*
 * preloadImages FUNCTION
 * General functions for preloading a set of images
 *
 */
function preloadImages()
{
    if (document.images)
    {
        var imgFiles = preloadImages.arguments;
        if (document.preloadArray==null)
            document.preloadArray = new Array();
        var i = document.preloadArray.length;
        with (document) for (var j=0; j<imgFiles.length; j++)
            if (imgFiles[j].charAt(0)!="#")
            {
                preloadArray[i] = new Image;
                preloadArray[i++].src = imgFiles[j];
            }
    }
}


/*
 * preloadChosenPhoto FUNCTION
 * @param imageFile an image filename to put into the chosenPhotos array of Image objects
   example: preloadChosenPhoto('/stock/386x258/225885.jpg');
*/
function preloadChosenPhoto(imageFile, caption)
{
  if (document.images)
  {
    if (document.chosenPhotos==null)
    {
        document.chosenPhotos = new Array();
    }
    var p = document.chosenPhotos.length;

    if (imageFile.charAt(0)!="#")
    {
        document.chosenPhotos[p] = new Image;
        document.chosenPhotos[p].src = imageFile;
        chosenCaptions[p] = caption;
    }
  }
}

/*
 * getPhotoCaption(index)
 * @param index which photo of the list 
 *
 */
var shownRegExp = new RegExp(" shown", "i");
var appendShown = true;
var appendNAV = false;
function getPhotoCaption(index)
{
    if (index < chosenCaptions.length && null != chosenCaptions[index])
    {
        var caption = chosenCaptions[index];
        caption = caption.replace(shownRegExp, '');
        if (null == caption || "" == caption.replace(/ /g, ""))
        {
            caption = chosenPhotoDIVobjectText;  // reset to default
        }
        else if (appendShown)
        {
            /* only append shown if caption not empty */
            caption += " shown&nbsp;";
            if (appendNAV) {
               caption += "(Not Actual Vehicle)";
            }
        }
        return caption;
    }
}

/*
 * choosePhoto FUNCTION
 * Put the cached image at index 'n' as Chosen Image
 * Uses chosenPhotos variable of large vehicle Image objects and
 * "chosenPhotoIMG" IMG object
 * With highlighting of thumbnail as chosen, use convention that the
 * thumbnail images are named tnImgX where X is passed "n".
 * @param n index into chosenPhotos array of Image objects
*/
function choosePhoto(n,w,h)
{
    var imgRef = eval(docRef + chosenPhotoIMGobjectName);
    if (null != imgRef && n < document.chosenPhotos.length)
    {
        imgRef.src = document.chosenPhotos[n].src;
        if(w){
           if(document.chosenPhotos[n].width > w) {
              imgRef.width = w
           }
        }
        updateChosenPhotoCaption(n);
        highlightPhoto('tnImg' + n);
    }    
    lastChosenPhotoIndex = n;

}

/*
 * highlightPhoto FUNCTION
 * Reference the given image object and change its class so it is highlighted.
 * Must keep a state of currently highlighted image to reset the previous.
 * @param imgName name of image object to highlight
*/
var highlightedPhoto = null;
function highlightPhoto(imgName)
{
    var imgRef = eval(docRef + imgName);
    if (null != imgRef)
    {
        if (null != highlightedPhoto){
            highlightedPhoto.className = "photo";
            //highlightedPhoto.width=66;
            //highlightedPhoto.height=44;
        }
        imgRef.className = "photoHighlight";
        //imgRef.width=59;
        //imgRef.height=38;
        highlightedPhoto = imgRef;
    }
}

/* updateChosenPhotoCaption
 * Attempt to update the caption for the Chosen Photo
 * using the rules shown, assets shown below.
 * @param n index into all the photos and their assets
 */
var chosenPhotoDIVobjectText = null;
function updateChosenPhotoCaption(n)
{
    var divRef = null;
    // Find DIV reference first
    if (IE || NS4)
    {
        divRef = eval(docRef + chosenPhotoDIVobjectName);
    }
    else
    {
        divRef = document.getElementById(chosenPhotoDIVobjectName);
    }

    // Then set its text 
    if (null != divRef)
    {
        // Set the default caption from first time thru
        if (null == chosenPhotoDIVobjectText)
        {
            chosenPhotoDIVobjectText = divRef.innerHTML;
        }

        var caption = getPhotoCaption(n, chosenPhotoDIVobjectText);
        if (null == caption || "" == caption.replace(/ /g, ""))
        {
            divRef.innerHTML = chosenPhotoDIVobjectText;  // reset to default
        }
        else
        {
            divRef.innerHTML = caption;
        }
            
    }
}


/*
 * imageInfoWindow
 * Simple new window with text placed inside.
 * @param contents text contents for the window
 * @param imgSrc URL to an image relating to the text contents
 */
function imageInfoWindow(contents, imgSrc)
{
    newWindow = window.open("", "information",
        "toolbar=yes, location=yes, scrollbars=yes, resizable=yes, height=800, width=400");
    newWindow.document.writeln("<html><head><title>"+imgSrc+"</title></head><body>");
    if (null != imgSrc && "" != imgSrc) newWindow.document.writeln("<img src='"+imgSrc+"'><br>");
    newWindow.document.write(contents);
    newWindow.document.writeln("</body></html>");
    newWindow.document.close();
    newWindow.focus();
}

/*
 * replaceChars
 * Simple function wrapper to the String.replace() function.
 *
 */
function replaceChars(str, regexp, replacement)
{
    newstr = "";
    if (str != null)
    {
        newstr = str.replace(regexp, replacement);
    }
    return newstr;
}

/**   checkEmailAddress Function
 *    this function checks the email address to ensure it is not 
 *    blank and that it is in the correct format
 *    @param emailAddressElement       the email address form element that you want to check
 *    @param emailAddressErrorMessage  the error message to throw if the email is incorrect
 */
function checkEmail(emailAddressElement, emailAddressErrorMessage) {
   var AtSym=emailAddressElement.value.indexOf('@');
   var Period=emailAddressElement.value.lastIndexOf('.');
   var Space=emailAddressElement.value.indexOf(' ');
   var wwwdot=emailAddressElement.value.indexOf('www.');
   var Length=emailAddressElement.value.length - 1;  
   var emailFieldName = "";
   if (emailAddressElement.name == 'sender') emailFieldName = 'From'; else if (emailAddressElement.name == 'recip') emailFieldName = 'To'; else if (emailAddressElement.name == 'cc') emailFieldName = 'CC';
   var errorMessage = 'Make sure the email address in the \"' + emailFieldName + '\" field is entered in the proper format, \nsuch as \"user@domainname.com\". There is a limit of one email address per field.'
   if (emailAddressElement.value==""){
      alert(emailAddressErrorMessage);
      emailAddressElement.focus();
      return false;
   } 
   else if ((AtSym < 1) || (Period <= AtSym+1) || (Period == Length ) || (Space  != -1) || (wwwdot != -1)) {  
      if (emailAddressElement.name == "sender" || emailAddressElement.name == "recip") {
	  	alert(emailAddressErrorMessage);
	  }
	  else {
	  	alert(errorMessage);
	  }
      emailAddressElement.focus();
      return false;
   }
   return true;
}



/*
 * setMainURLwClose
 * Go back to main window and set its location URL
 */
function setMainURLwClose(newURL)
{    
    // Stay within this window if now opener/parent window

    if ((window.opener == null)||(top.window.opener.name=="videopopup"))
    {
        location.href = newURL;
    }
    else
    {
        // Get the window opener and set its location
        window.opener.location.href = newURL;
        window.opener.focus();
    }
    window.close();
}




/*
 * setMainURL
 * Go back to main window and set its location URL
 */
function setMainURL(newURL)
{    
    // Stay within this window if now opener/parent window

    //if ((window.opener == null)||(top.window.opener.name=="videopopup"))
    //{
        location.href = newURL;
    //}
    //else
    //{
        // Get the window opener and set its location
    //    window.opener.location.href = newURL;
    //    window.opener.focus();
    //    window.window.close();
    //}
}

/* *
 * buildVehicle
 * Opens the builder page from a popup.
 * Requires that this be called from a popup AND that the main window
 * has a form called 'quote'.
 */
function buildVehicle(){
    opener.document.forms['quote'].submit();
    self.close();
}

/*
 * openPopup
 * Opens a new window with given URL, name and properties.
 * @param url which page to display in the new window.
 * @param name name of the new window
 * @param properties string of properties
 */
function openPopup(url, name, properties)
{
    if (null != url)
    {
        var popupWin = window.open(url, name, properties);
        if (null != popupWin) popupWin.focus();
    }
}

/* open Panorama popup
   can be used as a resizer if null is passed in. 
   Gallery and Ipix share the same window.
   */
function openPanorama(url){
    if (null == url || window.name == "mediapopup" || window.name == "popup")
    {

        //window.properties = properties;
        if (null != url) location.href = url;
        resizeOuterTo(900,705) //old: 667,636
    }
    else
    {
        openPopup(url,"mediapopup","width=900,height=705,left=50,top=50,scrollbars,resizable");
    }
}
function openIpix(url){
    openPanorama(url);
}


/* open Gallery popup
   can be used as a resizer if null is passed in. */
function openGallery(url){
    if (window.name == "mediapopup" || window.name == "popup")
    {
        //window.properties = properties;
        if (null != url) location.href = url;
        window.resizeTo(795, 695);
    }
    else
    {
        openPopup(url,"mediapopup","width=795,height=695,left=50,top=50,scrollbars=yes,resizable=yes");
    }
    
}

function openVideoGallery(url){
	var popupName = "videopopup";
	if(location.href.indexOf('photogallery')!=-1) var popupName = window.name;
	openPopup(url,popupName,"width=740,height=600,left=50,top=50,scrollbars=no,resizable=yes");
}

/* motorweek videos */
function openMotorweek(url){
    openPopup(url,"motorweekPopUp","width=385,height=289,left=50,top=50,scrollbars,resizable");
}



/* Taken from model reports */
function openPopupSmall(url){
    openPopup(url,"smallPopUp","width=385,height=289,left=50,top=50,scrollbars,resizable");
}

/* Taken from model reports */
function openPopupTall(url){
    openPopup(url,"tallPopUp","width=385,height=480,left=50,top=50,scrollbars,resizable");
}

/* Taken from model reports */
function openWarranty(url){
    openPopup(url,"warrantyPop","width=385,height=300,left=50,top=50");
}

/* Taken from model reports */
function openCompare(url){
    openPopup(url,"compPopUp","width=640,height=480,left=50,top=50,scrollbars,resizable");
}

/* Taken from model reports */
function openTrim(url)
{
    openPopup(url, "trimlistPop","width=590,height=400,left=200,top=200,scrollbars,resizable");
}

/* Taken from model reports */
function openPrint(url){
    openPopup(url, "printlist","width=385,height=375,left=200,top=200,scrollbars,resizable");
}

/* openPhoto
 * opens popup to display a large photo.
 */
function openPhoto(url){
    openPopup(url, "largephoto","width=880,height=700,left=50,top=50,scrollbars");
    //openGallery(url); rwc took out 3-9-04
	//previous dimensions: width=620,height=495
}
/* openPhoto2
 * opens popup to display a large photo: used in the case of Stock photo, the window isn't as large as the IOTF window above
 */
function openPhotoSmall(url){
    openPopup(url, "largephoto","width=675,height=700,left=50,top=50,scrollbars");
    //openGallery(url); rwc took out 3-9-04
	//previous dimensions: width=620,height=495
}


function openJDP(url){
	openPopup(url, "popup-jdp","width=590,height=400,left=200,top=200,toolbar=no,menubar=no,location=no");
}

/* Taken from model reports */
function loadDisclaimer() {               openPopup("/go/configurator/explainer.jsp","wndDisclaimer","height=385,width=450,left=170,top=20,status=no,toolbar=no,menubar=no,location=no,resizable=no,scrollbar=no");
}

/* Taken from model reports */
function loadResidual(url){
    openPopup(url,"residualValues","width=550,height=500,left=50,top=50,resizable,scrollbars");
}


function openMain (URL) { 
   openURL = URL; 
   if (top.opener){
      if (top.opener.closed) {
         var newMain = window.open(URL,'');   
         top.opener = newMain; 
      } 
      else {  
         top.opener.top.location = URL;
         top.opener = top.opener.top;
      }         
   } 
   else {
      var newMain = window.open(URL,'');   
      top.opener = newMain;
   } 
}  
    
/*Strip whitespace from a string*/
var whitespace = " \t\n\r";

function stripCharsInBag (s, bag){   
    var i;
    var returnString = "";
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function stripWhitespace (s){   
   return stripCharsInBag (s, whitespace)
}

/*Ensure that the window resizes the same in netscape and IE*/
function resizeOuterTo(w,h) {
 if (parseInt(navigator.appVersion)>3) {
   if (navigator.appName=="Netscape") {
    top.outerWidth=w;
    top.outerHeight=h;
   }
   else top.resizeTo(w,h);
 }
}

/*Find the value of the selected option in a select list*/
function findSelectedValue(field){
   var selected = "";
   for(var i=0; i < field.length; i++) {
      if(field.options[i].selected == true) {
         selected=field.options[i].value;
         break;
      }
   }
   return selected;
}

/*Find the value of cookie named cookieName*/
function getCookie(cookieName) {
   var cookieValue = "";
   var allCookies = document.cookie;
   var cookiePosition = allCookies.indexOf(cookieName + '=');   
   if(cookiePosition != -1){
      var valueStart = cookiePosition + cookieName.length + 1;
      var valueEnd = allCookies.indexOf(';', valueStart);
      if(valueEnd == -1) {
         valueEnd = allCookies.length;
      }
      cookieValue = allCookies.substring(valueStart, valueEnd);
      cookieValue = unescape(cookieValue);
   }
   return cookieValue
}

/*Set the value of cookie with cookieName, CookieValue)*/
function setCookie(cookieName, cookieValue) {
   document.cookie = cookieName + "=" + escape(cookieValue);
}


function parseQueryString(){
   var query = location.search.substring(1);
   var paramPairs = query.split('&');
   var params = new Array();
   for(i=0; i<paramPairs.length; i++){
      var result = paramPairs[i].match(/(.+)\=(.+)/);
      if(result){               
         if(result.length == 3){
            params[result[1]] = result[2];
         }
      }
   }
   return params;
}

//----------------------------------------------------------------------------------------------------------------------//
function debug(s){
if(debugOn){
debug(s);
}
}

//----------------------------------------------------------------------------------------------------------------------//
function writeLang(name, value, expires, remove){

var mode = 1;
if(value){mode=2;}
$.get(cookieUrl, {val: value, expr: expires },
	      function(data) { specialReload(mode);
	     }
	    );
}
//----------------------------------------------------------------------------------------------------------------------//
function specialReload(mode){
var langRandomizer = Math.floor(Math.random()*10000);
var newUrl = document.location.href;
if(mode==1){newUrl = newUrl.replace("request_locale=es", "request_locale=en");}
if(mode==2){newUrl = newUrl.replace("request_locale=en", "request_locale=es");}
if(newUrl.indexOf('?')>0 && isnet){newUrl = newUrl.replace('?', '?lr=' +langRandomizer + '&');}

if(window.location.href == newUrl){window.location.reload();} else {

window.location.href = newUrl;
}

}
//----------------------------------------------------------------------------------------------------------------------//

function convertNameToValue(opts, nm){
if(startsWith(aliasStrip, nm)){nm = stripStart(aliasStrip,  nm)}
if(startsWith(aliasStrip2, nm)){nm = stripStart(aliasStrip2, nm)}
if(startsWith(aliasStrip3, nm)){nm = stripStart(aliasStrip3, nm)}

var tstNm;
debug("converting:"+nm);
for(i=0;i<opts.length;i++){

tstNm = opts[i].name+"";

if(startsWith(aliasStrip, tstNm)){tstNm = stripStart(aliasStrip, tstNm)}
if(startsWith(aliasStrip2, tstNm)){tstNm = stripStart(aliasStrip2, tstNm)}
if(startsWith(aliasStrip3, tstNm)){tstNm = stripStart(aliasStrip3, tstNm)}
if(tstNm == nm){debug("found:" + opts[i].value);return opts[i].value;}



}
return "";
}
//----------------------------------------------------------------------------------------------------------------------//

function setContainsName(opts, nm){
for(i=0;i<opts.length;i++){
if(opts[i].name == nm){return true;}
}
return false;
}
//----------------------------------------------------------------------------------------------------------------------//

function setContainsTextValue(opts, val){
for(i=0;i<opts.length;i++){

if(opts[i].name == val){return true;}
}
return false; 
}


var aliasStrip = " - ";
var aliasStrip2 = "- ";
var aliasStrip3 = "  - ";
//----------------------------------------------------------------------------------------------------------------------//

function setContainsTextValue(opts, val){
var tstNm;
for(i=0;i<opts.length;i++){

tstNm = opts[i].name+"";

if(startsWith(aliasStrip, tstNm)){tstNm = stripStart(aliasStrip, tstNm)}
if(startsWith(aliasStrip2, tstNm)){tstNm = stripStart(aliasStrip2, tstNm)}
if(startsWith(aliasStrip3, tstNm)){tstNm = stripStart(aliasStrip3, tstNm)}
if(tstNm == val){return true;}
}
return false; 
}
//----------------------------------------------------------------------------------------------------------------------//

function setContainsValue(opts, val){
for(i=0;i<opts.length;i++){
if(opts[i].value == val){return true;}
}
return false;
}
//----------------------------------------------------------------------------------------------------------------------//

function setOptionsX(domObj, opts, show){
domObj.style.display = "none";
var newS = document.createElement("SELECT");
for(i=0;i<opts.length;i++){
newO = document.createElement("OPTION");
newS.appendChild(newO);
newO.text = opts[i].name;
newO.value = opts[i].value;

}
hObj = document.getElementById("hld");
newS.id = domObj.id;
domObj.style.display = "block";
} 
//----------------------------------------------------------------------------------------------------------------------//
function setOptions(domObj, opts, ignoreStart){

var startPoint = 0; 
spAdj = 0;
if(opts.length > 1){if(opts[0].value == "" && opts[1].value == ""){ignoreStart=true;}}

if(ignoreStart){startPoint = 1;spAdj = -1;}
//domObj.style.display = "none";
//domObj.disabled = true;
  /*    for (q=1;q<domObj.options.length;q++)
      {
         domObj.options[q].value = null;
      }
*/

domObj.innerHTML = "";


if(opts.length < 2){disableSelect(domObj);return} else {domObj.disabled = false;}

//domObj.options.length = opts.length;


for(i=startPoint;i<opts.length;i++){

domObj.options[i+spAdj] = new Option(opts[i].name);
domObj.options[i+spAdj].value = opts[i].value;


}
//domObj.disabled = false;
//domObj.style.display = "block";
//debug(domObj.innerHTML);
}  


//----------------------------------------------------------------------------------------------------------------------//
function setOptionsIH(domObj, opts, ignoreStart, valpref, txtpref){
var wrp = domObj.parentNode;
var startPoint = 0;
spAdj = 0;
if(ignoreStart){startPoint = 1;spAdj = -1;}
//domObj.style.display = "none";
//domObj.disabled = true;
  /*    for (q=1;q<domObj.options.length;q++)
      {
         domObj.options[q].value = null;
      }
*/

domObj.innerHTML = "";
if(opts.length < 2){disableSelect(domObj);return} else {domObj.disabled = false;}
//domObj.options.length = opts.length;
var ts = "<select id='"+domObj.id+"'>"
for(i=0;i<opts.length;i++){
ts = ts + "<option value=\""+opts[i].value+"\">"+opts[i].name+"</option>";


}
ts = ts + "</select>";
wrp.innerHTML = ts;





}  



//----------------------------------------------------------------------------------------------------------------------//
function setOptionsWPref(domObj, opts, value){
debug(domObj.id + ':' + value);
setOptions(domObj, opts);

var found =false;
if(value){
found = prePopSelect(domObj, value);
}
debug(found);
return found;

}

//----------------------------------------------------------------------------------------------------------------------//
function getEQVal(str, domObj, delim){
var strArr = str.split(delim);
debug(strArr.length);
for(p=0;p<domObj.options.length;p++){
if(domObj.options[p].value.indexOf(delim) > -1){
debug(domObj.options[p].value);
strArr2 = domObj.options[p].value.split(delim);
if(str == domObj.options[p].value){return str;}
var tempArr, tempArr2, retValue;
tempArr = strArr;tempArr2 = strArr2;
if(strArr.length > strArr2.length){tempArr=strArr2; tempArr2 = strArr;}
tFoundCount = 0;
debug(tempArr.length + "-" + tempArr2.length);
for(f=0;f<tempArr.length;f++){
debug(tempArr[f]);
if(arrayContainsValue(tempArr2, tempArr[f])){tFoundCount++}
}
debug(tFoundCount);
if(tFoundCount == tempArr.length){return domObj.options[p].value}
}
}
return str;
}


//----------------------------------------------------------------------------------------------------------------------//

function arrayContainsValue(opts, val){
for(i=0;i<opts.length;i++){
if(opts[i] == val){return true;}
}
return false;
}
//----------------------------------------------------------------------------------------------------------------------//
function setOptionsWTextPref(domObj, opts, value){
//debug(domObj.id + ':txt:' + value);
setOptions(domObj, opts);

var found =false;
if(value){
found = prePopSelectByText(domObj, value);
}
debug(found);
return found;

}
//----------------------------------------------------------------------------------------------------------------------//
function getOptionText(data){
var got = eval("("+data+")");
var optionText = "";

for(i=0;i<got.options.length;i++){
optionText = optionText + "<option value=\""+got.options[i].value+"\">"+got.options[i].name+"</option>";
}
return optionText;
}
//----------------------------------------------------------------------------------------------------------------------//
function disableSelect(domObj){
domObj.options.length = 1;
domObj.options[0] = new Option("N/A");
domObj.options[0].value = "";
domObj.disabled = true;
}

//----------------------------------------------------------------------------------------------------------------------//

function getCheckValue(domObj){
var chkstring = "";
var found = 0;

for(i=0;i<domObj.length;i++){

if(domObj[i].checked){
if(found>0){chkstring = chkstring + ',';}
chkstring = chkstring + domObj[i].value;
found++;
}

}
return chkstring;
}


//----------------------------------------------------------------------------------------------------------------------//

function getRadioValue(domObj){

for(i=0;i<domObj.length;i++){
if(domObj[i].checked){return domObj[i].value}
}
return "";
}

//----------------------------------------------------------------------------------------------------------------------//

function getSelectValue(domObj){

debug(domObj.options[domObj.selectedIndex].value);
return domObj.options[domObj.selectedIndex].value;
}

//----------------------------------------------------------------------------------------------------------------------//

function getSelectText(domObj){


return domObj.options[domObj.selectedIndex].text;
}
//----------------------------------------------------------------------------------------------------------------------//

function setCookie(name, value, expires, remove)
{

var expString = "";

	var now = new Date();
	if(remove){
	var expiration_date = new Date((new Date()).getTime() - 3600*1000);
	} else {
	if(expires > 0){
	var expiration_date = new Date((new Date()).getTime() + ((expires*24)*3600000));
	var expiration_date = expiration_date.toGMTString();
	expString = "expires="+expiration_date;
	}
	}

	

	document.cookie = name + "=" + value + "; path=/; " + expString;
	

}

//----------------------------------------------------------------------------------------------------------------------//

function setCsCookie(name, value, expires, remove){


alert("cs cookie called: "+value)

var expString = "";

	var now = new Date();
	if(remove){
	var expiration_date = new Date((new Date()).getTime() - 3600*1000);
	} else {
	if(expires > 0){
	var expiration_date = new Date((new Date()).getTime() + ((expires*24)*3600000));
	var expiration_date = expiration_date.toGMTString();
	expString = "expires="+expiration_date;
	}
	}

	

	document.cookie = name + "=" + value + "; path=/; " + expString;
	

}
//----------------------------------------------------------------------------------------------------------------------//

function cs_setCookie(name, value, expires, remove)
{


	var now = new Date();
	if(remove){
	var expiration_date = new Date((new Date()).getTime() - 3600*1000);
	} else {
	var expiration_date = new Date((new Date()).getTime() + ((expires*24)*3600000));
	}

	var expiration_date = expiration_date.toGMTString();

	document.cookie = name + "=" + value + "; path=/;  expires=" + expiration_date;
	

}

//----------------------------------------------------------------------------------------------------------------------//


function getAllCookies(){
var finalarray = new Array();
 var cookiestring = ""+document.cookie;
 var cookiearray = cookiestring.split(';');
 for(i=0;i<cookiearray.length;i++){
 ridx = finalarray.length;
 var indiv = cookiearray[i].split('=');
 finalarray[ridx] = new Object();
 finalarray[ridx].name = indiv[0];
 finalarray[ridx].value = indiv[1];
 debug( finalarray[ridx].name + "=" +  finalarray[ridx].value);
 }
 return finalarray;
}
//----------------------------------------------------------------------------------------------------------------------//

function prePopSelect(domObj, value){
debug(value + ":" + domObj.options.length + ":" + domObj.id);
if(value && value.indexOf(",") > -1){value = getEQVal(value, domObj, ",")}
for(i=0;i<domObj.options.length;i++){
if(domObj.options[i].value == value){domObj.options.selectedIndex = i;return true;}
}
return false;
}

//----------------------------------------------------------------------------------------------------------------------//

function prePopSelectByText(domObj, text){

for(i=0;i<domObj.options.length;i++){
var tstNm = domObj.options[i].text;

if(startsWith(aliasStrip, tstNm)){tstNm = stripStart(aliasStrip, tstNm)}
if(startsWith(aliasStrip2, tstNm)){tstNm = stripStart(aliasStrip2, tstNm)}
if(startsWith(aliasStrip3, tstNm)){tstNm = stripStart(aliasStrip3, tstNm)}
debug(tstNm + ":" + text);
if(tstNm == text){domObj.options.selectedIndex = i;return true;}
}
return false;
}
/*------------------------------------------------------------------------------*/
// advanced search link registration to cookie m/m when clicked...
// not the greatest, but we work with what we have
var storeAndGo = function(url, rForm) { // for generating SessionInfo cookie server side

if(rForm.mkId){

  var baseLink = '/for-sale/sessionInfoUpdater.action?hld=true';
  var myMake = rForm.mkId;
  var myModel = rForm.mdId;
  var buildLink;
  buildLink = baseLink;
  if (myMake.selectedIndex > 0) {
    buildLink += '&AmbMkId=' + myMake.options[myMake.selectedIndex].value + '&AmbMkNm=' + myMake.options[myMake.selectedIndex].text;
    if (myModel.selectedIndex > 0) {
      myMdId = myModel.options[myModel.selectedIndex].value.split(','); // handle aliases
      buildLink += '&AmbMdId=' + myMdId[0] + '&AmbMdNm=' + myModel.options[myModel.selectedIndex].text;
      if (myMdId.length > 1) {
        buildLink += '&alMdId=' + myMdId[0] + '&alMkId=' + myMake.options[myMake.selectedIndex].value;
      }
    } else {
      buildLink += '&AmbMdId=' + '&AmbMdNm=';
    }
    buildLink += '&cacheBreak=' + new Date().getTime();
  } // gotta pass AmbMkId, AmbMkNm, AmbMdId, AmbMdNm (+ alMdId, alMkId for model alias)
  
  
  if(rForm.zc && rForm.zc.value.length > 0) { buildLink += '&zc=' + rForm.zc.value;}
 
  window.sessionSetter = new Image();
  window.sessionSetter.src = buildLink;
  if(url != ""){
  window.setTimeout(function() { // give ping time to set cookie.
    window.location = url;
  }, 350);
  }
  }
  return false;
}
//----------------------------------------------------------------------------------------------------------------------//

function getCookie(cookiename)
{

    var cookiestring = ""+document.cookie;
	
    var index1 = cookiestring.indexOf(';');
    if (index1==-1 || cookiename=="")
        return ""; 


var cookieArray = cookiestring.split(';');
for(i=0;i<cookieArray.length;i++){

if(cookieArray[i].indexOf('=') > -1){

ca2 = cookieArray[i].split('=');

if(ca2[0].trim() == cookiename) {return Url.decode(ca2[1])}
}
}
return "";
}
//----------------------------------------------------------------------------------------------------------------------//

function startsWith(tst, val){
if(val.substring(0, tst.length) == tst){return true;} else {return false;}
}
//----------------------------------------------------------------------------------------------------------------------//

function stripStart(tst, val){
return val.substring(tst.length, val.length)
}

 
//----------------------------------------------------------------------------------------------------------------------//

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}








//----------------------------------------------------------------------------------------------------------------------//
function getFormStuff(){
debug(document.getElementById("advForm").elements[1].tagName);
var newTextArea = document.createElement("TEXTAREA");
for(i=0;i<document.getElementById("advForm").elements.length;i++){
var fE = document.getElementById("advForm").elements[i];
newTextArea.innerHTML = newTextArea.innerHTML + "\n"+fE.name;
}
document.getElementById("geoSearchParams").appendChild(newTextArea);
}
//----------------------------------------------------------------------------------------------------------------------//

function rationalizeRange(loDom, hiDom){
if(loDom.value != '' && hiDom.value != ''){
var loInd = loDom.selectedIndex;
var hiInd = hiDom.selectedIndex;
if(parseInt(loDom.options[loInd].value) > parseInt(hiDom.options[hiInd].value)){
loDom.selectedIndex = hiInd;
hiDom.selectedIndex = loInd;
}
}
/*
if(loDom.selectedIndex == 0 && hiDom.selectedIndex == 0){
loDom.disabled = true;
hiDom.disbaled = true;
}
*/
}



var Url = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}


function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}




