//=====================================================================||
//               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 = "You have selected a link to a website that is not owned or maintained by ERA.com.  Different terms of use and privacy policies will apply.";

// var g_strRedirectLegalDisclaimer = "[STR#REDIRECTPOLICY#]";

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

   return !opened;
}


//---------------------------------------------------------------------||
// 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=940,resizable=yes,scrollbars=yes,status=yes,location=yes,menubar=yes,titlebar=yes,toolbar=yes');
   if ( wind ) return false;

   return true;
}



//---------------------------------------------------------------------||
// FUNCTION:    MyNeighborhoodLibPopup                                 ||
// PARAMETERS:  Url                                                    ||
// RETURNS:     False on popup successfull                             ||
// PURPOSE:     Create popup, or go to URL ere appropriate             ||
//---------------------------------------------------------------------||
function MyNeighborhoodLibPopup( strUrl )
{
   wind=window.open(strUrl,'','width=640,height=480,toolbar=no,menubar=no,scrollbars=yes,resizable=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("Please select a state to search");
         return false;
      }
   }
   if (pForm.County.value != "") {
      if (pForm.State[pForm.State.selectedIndex].value == "") {
         alert("Please select a state to search");
         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("Please enter an Express Code, MLS/Listing ID#, City, County, or Zip Code to search by");
      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("Please select a country.");
   }
}


//---------------------------------------------------------------------||
// 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("Entre ") >= 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.toUTCString() : "") +
                     ((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 pDiv;
   var pSubDiv;
   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("You may only compare up to 18 properties at a time.  Please remove one or more proeprties from the comparison before trying to add more.");
         return;
      } else {
         if ( !bFirst )
            strNewString += "|";
         strNewString += lProperty;
      }
   }


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

   if ( document.getElementById ) {
      //pDiv = eval( ('document.all.pcd' + lProperty) );
      pDiv = document.getElementById(('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("You have removed this property from your comparison list.");
      } else {
         alert("You have added this property to your comparison list.");
      }
   }

   if( !bAlreadyInCart ){
      strPropString = GetCookie("PropCompare");
      if( strPropString == null || strPropString == '' )
         alert("You must have cookies enabled in your browser to use this feature.");
   }
}


//---------------------------------------------------------------------||
// 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("You must add two or more properties to the comparison list using the 'Add to Compare' feature before you can compare properties.");
      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()
{
   var months=new Array(13);
   months[1]="1";
   months[2]="2";
   months[3]="3";
   months[4]="4";
   months[5]="5";
   months[6]="6";
   months[7]="7";
   months[8]="8";
   months[9]="9";
   months[10]="10";
   months[11]="11";
   months[12]="12";
   var localTime=new Date();
   var localMonth=months[localTime.getMonth() + 1];
   var localDate=localTime.getDate();
   var localYear=localTime.getYear();
   if (localYear < 2000)
      localYear = localYear + 1900;
   document.write("<font face='Verdana,Arial,Helvetica,sans-serif' size='-2' color='Black'> :: " + localMonth + "." + localDate + "." + localYear + "</font>");
}


function URLDecode(psEncodeString) 
{
  // Create a regular expression to search all +s in the string
  var lsRegExp = /\+/g;
  // Return the decoded string
  return unescape(String(psEncodeString).replace(lsRegExp, " "));
}

function PresetQuickSearchForm( pForm )
{
   var strLastSearch = GetCookie("lastsearch");
   if( strLastSearch && strLastSearch.length > 1 ) {
      //We have a previous search
      var strCity = '';
      var strState = '';
      var strCounty = '';
      var strZip = '';
      var pairs = strLastSearch.split("&"); 
      for (var i=0;i<pairs.length;i++) {
         var pos = pairs[i].indexOf('=');
         if (pos >= 0) {
            var argname = pairs[i].substring(0,pos);
            var value = pairs[i].substring(pos+1);
            if( argname == 'MLSXP' ) {
               if( pForm.MLSXP ) pForm.MLSXP.value = URLDecode(value);
            }
            else if( argname == 'City' ) {
               if( pForm.City ) pForm.City.value = URLDecode(value);
            }
            else if( argname == 'State' ) {
               if( pForm.State ) {
                  pForm.State.value = URLDecode(value);
               }
            }
            else if( argname == 'County' ) {
               if( pForm.County ) pForm.County.value = URLDecode(value);
            }
            else if( argname == 'Zip' ) {
               if( pForm.Zip ) pForm.Zip.value = URLDecode(value);
            }
         }
      }
   }
}

function getNodeValue(obj, tag)
{
   if( obj ) {
      var pElement = obj.getElementsByTagName(tag);
      if( pElement && pElement[0] ) {
         if( pElement[0].firstChild ) {
            return pElement[0].firstChild.nodeValue;
         }
      }
   }
   return "";
}

function ClearQuickSearchForm( pForm )
{
   if( pForm.MLSXP ) pForm.MLSXP.value = 'Enter Express Code or MLS/Listing ID#';
   if( pForm.City ) pForm.City.value = '';
   if( pForm.State ) pForm.State.value = '';
   if( pForm.County ) pForm.County.value = '';
   if( pForm.Zip ) pForm.Zip.value = '';
}

//---------------------------------------------------------------------||
// 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;
   var bClickTracker = false;
   

   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) {
               var bClickTracker = false;
               var strClickTrackUrl = aTags[i].getAttribute('href');
               strServerName = getServerName(strClickTrackUrl);
               
               var iClickTrackPos = strClickTrackUrl.indexOf("/ad/click.php");
               if( iClickTrackPos >= 0 ) {
                  if( !aTags[i].onmouseover ) {
                     aTags[i].onmouseover = showOffSiteDisclaim;
                     aTags[i].onmouseout = hideOffSiteDisclaim;
                  }
               } else if (strServerName.length > 0) {
                  if (  (!isValidEraServer(strServerName)) ) {
                     if( !aTags[i].onmouseover ) {
                        aTags[i].onmouseover = showOffSiteDisclaim;
                        aTags[i].onmouseout = hideOffSiteDisclaim;
                     }
                  }
               }
            }
         }
      }
   }
}

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 == "www.netmovein.com" ){
      return true;
   }
   if( strServerName == "www.eramortgage.com" ){
      return true;
   }
   if( strServerName == CurrentServer ){
      return true;
   }

   return false;
}


function hideOffSiteDisclaim(objMouseEvent) {
   document.getElementById('OffSiteDisclaimer').style.display='none';
}

function showOffSiteDisclaim(objMouseEvent) {
   var iPositionX = 0;
   var iPositionY = 0;
   if ( ! objMouseEvent ) objMouseEvent = window.event;
   if ( objMouseEvent.pageX ) {
      iPositionX = objMouseEvent.pageX;
   } else {
      if ( objMouseEvent.clientX ) {
         if ( document.body.scrollLeft ) {
            iPositionX = objMouseEvent.clientX + document.body.scrollLeft;
         } else {
            iPositionX = objMouseEvent.clientX;
         }
      }
   }
   if ( objMouseEvent.pageY ) {
      iPositionY = objMouseEvent.pageY;
   } else {
      if ( objMouseEvent.clientY ) {
         if ( document.body.scrollTop ) {
            iPositionY = objMouseEvent.clientY + document.body.scrollTop;
         } else {
            iPositionY = objMouseEvent.clientY;
         }
      }
   }
   iPositionX = iPositionX+20;
   iPositionY = iPositionY-40;
   document.getElementById('OffSiteDisclaimer').style.display='block';
   document.getElementById('OffSiteDisclaimer').style.position='absolute';
   document.getElementById('OffSiteDisclaimer').style.left=iPositionX+'px';
   document.getElementById('OffSiteDisclaimer').style.top=iPositionY+'px';
}



// hover message for the /eraimages/icon-ics-sm.jpg icon

function hideInternationalCollectionHover(objMouseEvent) {
   document.getElementById('InternationalCollection').style.display='none';
}

function showInternationalCollectionHover(objMouseEvent) {
   var iPositionX = 0;
   var iPositionY = 0;
   if ( ! objMouseEvent ) objMouseEvent = window.event;
   if ( objMouseEvent.pageX ) {
      iPositionX = objMouseEvent.pageX;
   } else {
      if ( objMouseEvent.clientX ) {
         if ( document.body.scrollLeft ) {
            iPositionX = objMouseEvent.clientX + document.body.scrollLeft;
         } else {
            iPositionX = objMouseEvent.clientX;
         }
      }
   }
   if ( objMouseEvent.pageY ) {
      iPositionY = objMouseEvent.pageY;
   } else {
      if ( objMouseEvent.clientY ) {
         if ( document.body.scrollTop ) {
            iPositionY = objMouseEvent.clientY + document.body.scrollTop;
         } else {
            iPositionY = objMouseEvent.clientY;
         }
      }
   }
   iPositionX = iPositionX+10;
   iPositionY = iPositionY-2;
   document.getElementById('InternationalCollection').style.display='block';
   document.getElementById('InternationalCollection').style.position='absolute';
   document.getElementById('InternationalCollection').style.left=iPositionX+'px';
   document.getElementById('InternationalCollection').style.top=iPositionY+'px';
}

function DoInternationalCollectionIconHover()
{
   if( document.getElementsByTagName ) {
      var imageTags = document.getElementsByTagName('img');
      var iImageTagCount = imageTags.length;
      for (var i=0; i < iImageTagCount; i++) {
         if (imageTags[i].src) {
            var strICicon = imageTags[i].getAttribute('src');
            var iICiconPos = strICicon.indexOf("/eraimages/icon-ics-sm.jpg");
            if( iICiconPos >= 0 ) {
               if( !imageTags[i].onmouseover ) {
                  imageTags[i].onmouseover = showInternationalCollectionHover;
                  imageTags[i].onmouseout = hideInternationalCollectionHover;
               }
            }
         }
      }
   }
}
