//=====================================================================||
//               ERA RealEstate General Include                        ||
//                                                                     ||
// This JS should be included on all ERA.com pages, and contains only  ||
// shared functions that may be called from most any page.             ||
//                                                                     ||
// Portions of this script are used with permission from the NOP Design||
// Free-Shopping Cart, located at http://www.nopdesign.com/freecart    ||
//                                                                     ||
//=====================================================================||

//---------------------------------------------------------------------||
// FUNCTION:    ERA_openPopup                                          ||
// PARAMETERS:  Url, name of popup, widgets, url to open               ||
// RETURNS:     N/A                                                    ||
// PURPOSE:     Create popup, give focus where appropriate             ||
//---------------------------------------------------------------------||

var g_strRedirectLegalDisclaimer = "Usted ha seleccionado un acoplamiento a a sitio de interneteso no es posea ni es mantenida por ERA.com. Diversos tminos del uso y privacidadlas policas se aplicar.";
// var g_strRedirectLegalDisclaimer = "[STR#REDIRECTPOLICY#]";

function ERA_openPopup( url, name, widgets, openerUrl )
{
   var host = location.hostname;
   var popupWin = window.open( url, name, widgets );
   if ( popupWin && popupWin.opener ) {
      if ( openerUrl ) {
         popupWin.opener.location = openerUrl;
         popupWin.focus();
      }
      popupWin.opener.top.name = "opener";
   }
}


//---------------------------------------------------------------------||
// FUNCTION:    AgentPopup                                             ||
// PARAMETERS:  Url                                                    ||
// RETURNS:     False on popup successfull                             ||
// PURPOSE:     Create popup, or go to URL ere appropriate             ||
//---------------------------------------------------------------------||
function AgentPopup( strUrl )
{
   wind=window.open(strUrl,'','width=790,resizable=yes,scrollbars=yes,status=yes,location=yes,menubar=yes,titlebar=yes,toolbar=yes');
   if ( wind ) return false;

   return true;
}



//---------------------------------------------------------------------||
// FUNCTION:    FallBackPopup                                          ||
// PARAMETERS:  Url, width of popup, height of popup                   ||
// RETURNS:     False on popup successfull                             ||
// PURPOSE:     Create popup, or go to URL ere appropriate             ||
//---------------------------------------------------------------------||
function FallBackPopup( strUrl, iWidth, iHeight )
{
   wind=window.open(strUrl,'','width='+iWidth+',height='+iHeight+',resizable=yes,scrollbars=yes,status=yes');
   if ( wind ) return false;

   return true;
}


//---------------------------------------------------------------------||
// FUNCTION:    QuickSearchSubmit                                      ||
// PARAMETERS:  Form to submit                                         ||
// RETURNS:     True on form ready to be submitted                     ||
// PURPOSE:     Check for valid quick search submittal                 ||
//---------------------------------------------------------------------||
function QuickSearchSubmit( pForm ){
   if ( !pForm ) return true;

   if (pForm.City.value != "") {
      if (pForm.State[pForm.State.selectedIndex].value == "") {
         alert("Seleccione por favor un estado para buscar");
         return false;
      }
   }
   if (pForm.County.value != "") {
      if (pForm.State[pForm.State.selectedIndex].value == "") {
         alert("Seleccione por favor un estado para buscar");
         return false;
      }
   }

   if ( (pForm.City.value == "") && (pForm.County.value == "") && 
        ((pForm.MLSXP.value == "") || (pForm.MLSXP.value == "Enter Express Code or MLS/Listing ID#")) &&
        (pForm.Zip.value == "")) {
      alert("Favor de meter un código expreso, el numero de identificación del listado del MLS (servicio del listado múltiple), la ciudad, el condado, o un código postal para buscar por");
      return false;
   }

   return true;
}


//---------------------------------------------------------------------||
// FUNCTION:    InternationalHandler                                   ||
// PARAMETERS:  Form to submit                                         ||
// RETURNS:     N/A                                                    ||
// PURPOSE:     Opens new popup for internation offices                ||
//---------------------------------------------------------------------||
function InternationalHandler(form)
{
   var URL = "";
   if ( form ) {
      if ( form.InternationalForm )
         if ( form.InternationalForm.Country )
            var URL = form.Country.options[document.InternationalForm.Country.selectedIndex].value;
   } else {
      if ( document.InternationalForm )
         if ( document.InternationalForm.Country )
            var URL = document.InternationalForm.Country.options[document.InternationalForm.Country.selectedIndex].value;
   }
   if ( URL != "" ) {
      win=window.open(URL,"NewWindow","toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes");
      if (!win.opener)win.opener=self;
   } else {
      alert("Seleccione por favor un país.");
   }
}


//---------------------------------------------------------------------||
// FUNCTION:    EmptyIfEnter                                           ||
// PARAMETERS:  Field to scrub                                         ||
// RETURNS:     N/A                                                    ||
// PURPOSE:     Removes Enter... text from fields                      ||
//---------------------------------------------------------------------||
function EmptyIfEnter(pField)
{
   if ( pField ) {
      if ( pField.value )
         if ( pField.value.length > 5 )
            if ( pField.value.indexOf("Enter ") >= 0 || pField.value.indexOf("Introduzca ") >= 0 )
               pField.value = '';
   }
}

//---------------------------------------------------------------------||
// FUNCTION:    getCookieVal                                           ||
// PARAMETERS:  offset                                                 ||
// RETURNS:     URL unescaped Cookie Value                             ||
// PURPOSE:     Get a specific value from a cookie                     ||
//---------------------------------------------------------------------||
function getCookieVal (offset) {
   var endstr = document.cookie.indexOf (";", offset);

   if ( endstr == -1 )
      endstr = document.cookie.length;
   return(unescape(document.cookie.substring(offset, endstr)));
}


//---------------------------------------------------------------------||
// FUNCTION:    FixCookieDate                                          ||
// PARAMETERS:  date                                                   ||
// RETURNS:     date                                                   ||
// PURPOSE:     Fixes cookie date, stores back in date                 ||
//---------------------------------------------------------------------||
function FixCookieDate (date) {
   var base = new Date(0);
   var skew = base.getTime();

   date.setTime (date.getTime() - skew);
}


//---------------------------------------------------------------------||
// FUNCTION:    GetCookie                                              ||
// PARAMETERS:  Name                                                   ||
// RETURNS:     Value in Cookie                                        ||
// PURPOSE:     Retrieves cookie from users browser                    ||
//---------------------------------------------------------------------||
function GetCookie (name) {
   var arg = name + "=";
   var alen = arg.length;
   var clen = document.cookie.length;
   var i = 0;

   while ( i < clen ) {
      var j = i + alen;
      if ( document.cookie.substring(i, j) == arg ) return(getCookieVal (j));
      i = document.cookie.indexOf(" ", i) + 1;
      if ( i == 0 ) break;
   }

   return(null);
}


//---------------------------------------------------------------------||
// FUNCTION:    SetCookie                                              ||
// PARAMETERS:  name, value, expiration date, path, domain, security   ||
// RETURNS:     Null                                                   ||
// PURPOSE:     Stores a cookie in the users browser                   ||
//---------------------------------------------------------------------||
function SetCookie (name,value,expires,path,domain,secure) {
   document.cookie = name + "=" + escape (value) +
                     ((expires) ? "; expires=" + expires.toGMTString() : "") +
                     ((path) ? "; path=" + path : "") +
                     ((domain) ? "; domain=" + domain : "") +
                     ((secure) ? "; secure" : "");
}


//---------------------------------------------------------------------||
// FUNCTION:    DeleteCookie                                           ||
// PARAMETERS:  Cookie name, path, domain                              ||
// RETURNS:     null                                                   ||
// PURPOSE:     Removes a cookie from users browser.                   ||
//---------------------------------------------------------------------||
function DeleteCookie (name,path,domain) {
   if ( GetCookie(name) ) {
      document.cookie = name + "=" +
                        ((path) ? "; path=" + path : "") +
                        ((domain) ? "; domain=" + domain : "") +
                        "; expires=Thu, 01-Jan-70 00:00:01 GMT";
   }
}


//---------------------------------------------------------------------||
// FUNCTION:    MoneyFormat                                            ||
// PARAMETERS:  Number to be formatted                                 ||
// RETURNS:     Formatted Number                                       ||
// PURPOSE:     Reformats Dollar Amount to #.## format                 ||
//---------------------------------------------------------------------||
function moneyFormat(input) {
   var dollars = Math.floor(input);
   var tmp = new String(input);

   for ( var decimalAt = 0; decimalAt < tmp.length; decimalAt++ ) {
      if ( tmp.charAt(decimalAt)=="." )
         break;
   }

   var cents  = "" + Math.round(input * 100);
   cents = cents.substring(cents.length-2, cents.length)
   dollars += ((tmp.charAt(decimalAt+2)=="9")&&(cents=="00"))? 1 : 0;

   if ( cents == "0" )
      cents = "00";

   return(dollars + "." + cents);
}


//---------------------------------------------------------------------||
// FUNCTION:    ToggleCompare                                          ||
// PARAMETERS:  Property ID to toggle, DIV to modify display in        ||
// RETURNS:     N/A                                                    ||
// PURPOSE:     Adds or removes property from compare function         ||
//---------------------------------------------------------------------||
function ToggleCompare( lProperty )
{
   var bAlreadyInCart = false;
   var iCartLocation = 0;
   var bNotify = true;
   var strPropString = GetCookie("PropCompare");   
   var iCurr;
   var aPropertyArray;
   var strNewString;
   var bFirst = true;
   var dtExpiration = (new Date((new Date()).getTime() + 30*150000));
   if ( strPropString ) {
      aPropertyArray = strPropString.split('|');
   } else {
      aPropertyArray = new Array;
   }
   strNewString = "";
   for ( iCurr=0; iCurr < aPropertyArray.length; iCurr++ ) {
      if ( lProperty == aPropertyArray[iCurr] ) {
         bAlreadyInCart = true;
         iCartLocation = iCurr;
      } else {
         if ( !bFirst ) {
            strNewString += "|" + aPropertyArray[iCurr];
         } else {
            strNewString += aPropertyArray[iCurr];
            bFirst = false;
         }            
      }

   }
   if ( !bAlreadyInCart ) {
      if( aPropertyArray.length > 17 ) {
         alert("Usted puede comparar solamente hasta 18 características al mismo tiempo. Quite por favor unos o más proeprties de la comparación antes de intentar agregar más.");
         return;
      } else {
         if ( !bFirst )
            strNewString += "|";
         strNewString += lProperty;
      }
   }


   SetCookie("PropCompare", strNewString, dtExpiration, "/", null, false);

   if ( document.all ) {
      pDiv = eval( ('document.all.pcd' + lProperty) );
      if ( pDiv && pDiv.length && pDiv.length > 1 ) {         
         for ( iCurr = 0; iCurr < pDiv.length; iCurr++ ) {
            pSubDiv = pDiv[iCurr];
            if ( pSubDiv ) {
               if ( bAlreadyInCart ) {
                  pSubDiv.innerHTML = "<img src=\"/eraimages/cpadd.gif\" border=0 align=middle width=20 height=19>Add to Compare";
               } else {
                  pSubDiv.innerHTML = "<img src=\"/eraimages/cprem.gif\" border=0 align=middle width=20 height=19>Remove from Compare";
               }
               bNotify = false;
            }
         }
      } else {
         if ( pDiv ) {
            if ( bAlreadyInCart ) {
               pDiv.innerHTML = "<img src=\"/eraimages/cpadd.gif\" border=0 align=middle width=20 height=19>Add to Compare";
            } else {
               pDiv.innerHTML = "<img src=\"/eraimages/cprem.gif\" border=0 align=middle width=20 height=19>Remove from Compare";
            }
            bNotify = false;
         }
      }
   }

   if ( bNotify ) {
      if ( bAlreadyInCart ) {
         alert("Usted ha quitado esta característica de su lista de la comparación.");
      } else {
         alert("Usted ha agregado esta característica a su lista de la comparación.");
      }
   }

   if( !bAlreadyInCart ){
      strPropString = GetCookie("PropCompare");
      if( strPropString == null || strPropString == '' )
         alert("Usted debe comer galletas permitidas en su browser utilizar esta característica.");
   }
}


//---------------------------------------------------------------------||
// FUNCTION:    GotoCompare                                            ||
// PARAMETERS:  N/A                                                    ||
// RETURNS:     Does not return                                        ||
// PURPOSE:     If the user has 2+ properties, take them to the compare||
//              page                                                   ||
//---------------------------------------------------------------------||
function GotoCompare( )
{
   var aPropertyArray;
   var strPropString = GetCookie("PropCompare");

   if ( strPropString ) {
      aPropertyArray = strPropString.split('|');
   } else {
      aPropertyArray = new Array;
   }

   if( aPropertyArray.length < 2  ){
      alert("Usted debe agregar dos o más características a usar de la lista de la comparación ' agrega para comparar ' la característica antes de que usted pueda comparar características.");
      return false;
   }

   return true;
}

//---------------------------------------------------------------------||
// FUNCTION:    DisplayLocalComputerDate                               ||
// PARAMETERS:  N/A                                                    ||
// RETURNS:     Does not return                                        ||
// PURPOSE:     Write the local computer's date on the screen          ||
//              page                                                   ||
//---------------------------------------------------------------------||
function DisplayLocalComputerDate()
{
   return true;
}




//---------------------------------------------------------------------||
// FUNCTION:    IfLinkNotInEraNetworkForceConfirmation                 ||
// PARAMETERS:  Pointer to form to compare all href's to current site  ||
// RETURNS:     Nothing                                                ||
// PURPOSE:     Adds onClick event to all href's that direct off site  ||
//---------------------------------------------------------------------||
function IfLinkNotInEraNetworkForceConfirmation()
{
   var strServerName;

   if( document.getElementsByTagName ) {
      var aTags = document.getElementsByTagName('a');
      var iAnchorCount = aTags.length;
      for (var i=0; i < iAnchorCount; i++) {
         if (! aTags[i].getAttribute('donotaddlegaldisclaimer')) {
            if (aTags[i].href) {
               strServerName = getServerName(aTags[i].getAttribute('href'));
               if (strServerName.length > 0) {
                  if (!isValidEraServer(strServerName)) {
                     aTags[i].onclick = function () { return confirm(g_strRedirectLegalDisclaimer); };
                  }
               }
            }
         }
      }
   }
}

function getServerName(strValue)
{
   var strServerName;
   var iParmLocation;

   strServerName = strValue.toLowerCase();

   iParmLocation = strServerName.indexOf("?");
   if (iParmLocation >= 0) {
      strServerName = strServerName.substring(0,iParmLocation);
   }
   if (strServerName.indexOf("http") == 0) {
      iParmLocation = strServerName.indexOf("https://");
      if (iParmLocation >= 0) {
         strServerName = strServerName.substring((iParmLocation+8),strServerName.length);
      }
      iParmLocation = strServerName.indexOf("http://");
      if (iParmLocation >= 0) {
         strServerName = strServerName.substring((iParmLocation+7),strServerName.length);
      }
      iParmLocation = strServerName.indexOf("/");
      if (iParmLocation >= 0) {
         strServerName = strServerName.substring(0,iParmLocation);
      }
   } else {
      strServerName = "";
   }

   return strServerName;
}

function isValidEraServer(strServerName)
{
   var CurrentServer = document.location.host.toLowerCase();

   if( strServerName.indexOf(".era.com") >= 0 ){
      return true;
   }
   if( strServerName == "era.com" ){
      return true;
   }
   if( strServerName.indexOf(".teamera.com") >= 0 ){
      return true;
   }
   if( strServerName == "teamera.com" ){
      return true;
   }
   if( strServerName == CurrentServer ){
      return true;
   }

   return false;
}

function PresetQuickSearchForm(pForm)
{
}

