var debugOn = false;
var cookieUrl = "/for-sale/spanishcookie.action";

//----------------------------------------------------------------------------------------------------------------------//
function debug(s){
if(debugOn){
debug(s);
}
}

//----------------------------------------------------------------------------------------------------------------------//
function writeLang(name, value, expires, remove){

var mode = 1;
if(value){mode=2;}
dojo.io.bind({
url: cookieUrl,
content: {
val: value,
expr: expires
},

handler: function(type, data, evt){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+$/,"");
}


