//=====================================================================||
//               CBC RealEstate General Include                        ||
//                                                                     ||
// This JS should be included on all CBC.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    ||
//                                                                     ||
//=====================================================================||

//---------------------------------------------------------------------||
// GLOBAL VARIABLES                                                    ||
//---------------------------------------------------------------------||
var g_strRedirectLegalDisclaimer = "You have selected a link to a website that is not owned or maintained by Coldwell Banker Real Estate Corporation.  Different terms of use and privacy policies will apply.";

//---------------------------------------------------------------------||
// FUNCTION:    ClearDefault                                           ||
// PARAMETERS:  field, default string                                  ||
// RETURNS:     N/A                                                    ||
// PURPOSE:     Clears an input text field if it's value is == default ||
//---------------------------------------------------------------------||
function ClearDefault(pField, strDefault){
    if( pField && pField.value == strDefault ){
        pField.value = '';
        pField.style.color = '#222';
    }
}

//---------------------------------------------------------------------||
// 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:    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.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:    UrlDecode                                              ||
// PARAMETERS:  String to url decode                                   ||
// RETURNS:     Decoded string                                         ||
// PURPOSE:     Returns plain text string urldecoded.                  ||
//---------------------------------------------------------------------||
function UrlDecode(strEncodeString) 
{
  var lsRegExp = /\+/g;
  return unescape(String(strEncodeString).replace(lsRegExp, " ")); 
}

//---------------------------------------------------------------------||
// FUNCTION:    QueryString                                            ||
// PARAMETERS:  Key to read                                            ||
// RETURNS:     value of key                                           ||
// PURPOSE:     Read data passed in via GET mode                       ||
//---------------------------------------------------------------------||
QueryString.keys = new Array();
QueryString.values = new Array();
function QueryString(key) {
   var value = null;
   for (var i=0;i<QueryString.keys.length;i++) {
      if (QueryString.keys[i]==key) {
         value = QueryString.values[i];
         break;
      }
   }
   return value;
}


//---------------------------------------------------------------------||
// FUNCTION:    QueryString_Parse                                      ||
// PARAMETERS:  (URL string)                                           ||
// RETURNS:     null                                                   ||
// PURPOSE:     Parses query string data, must be called before Q.S.   ||
//---------------------------------------------------------------------||
function QueryString_Parse() {
   QueryString.keys = new Array();
   QueryString.values = new Array();
   var query = window.location.search.substring(1);
   var pairs = query.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);
         QueryString.keys[QueryString.keys.length] = argname;
         QueryString.values[QueryString.values.length] = value;
      }
   }
}


//---------------------------------------------------------------------||
// FUNCTION:    SavedQueryString_Parse                                 ||
// PARAMETERS:  (URL string)                                           ||
// RETURNS:     null                                                   ||
// PURPOSE:     Parses query string data, must be called before Q.S.   ||
//              -- parses passed in string URL instead of current QS   ||
//---------------------------------------------------------------------||
function SavedQueryString_Parse( strUrl ) {
   QueryString.keys = new Array();
   QueryString.values = new Array();
   if ( strUrl == null ) return;
   var query = '';
   var qpos = strUrl.indexOf('?');
   if( qpos > 0 ){
      query = strUrl.substring(qpos+1);
   } else {
      query = strUrl;
   }   
   var pairs = query.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);
         QueryString.keys[QueryString.keys.length] = argname;
         QueryString.values[QueryString.values.length] = value;
      }
   }
}


//---------------------------------------------------------------------||
// 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:    phoneFormat                                            ||
// PARAMETERS:  Number to be formatted                                 ||
// RETURNS:     Formatted Number                                       ||
// PURPOSE:     Reformats Dollar Amount to #.## format                 ||
//---------------------------------------------------------------------||
function PhoneFormat(strPhone) {
   var bFormatted = false;
   strPhone = strPhone.toString();
   if( strPhone.indexOf('(') > -1 ) bFormatted = true;
   if( (strPhone.length > 9) && !bFormatted) {
      //(386) 775-8633 x1234
      strFormatted = '(';
      strFormatted += strPhone.substring(0, 3);
      strFormatted += ') ';
      strFormatted += strPhone.substring(3, 6);
      strFormatted += '-';
      strFormatted += strPhone.substring(6, 10);
      if( strPhone.length > 10 ) {
          strFormatted += ' x';
          strFormatted += strPhone.substring(10, strPhone.length);
      }
      return strFormatted;
   }

   return strPhone;
}

//---------------------------------------------------------------------||
// FUNCTION:    FormatExternalUrlWithLink                              ||
// PARAMETERS:  URL to be formatted                                    ||
// RETURNS:     HTML fragment with HREF to formatted URL               ||
// PURPOSE:     Link url consistently                                  ||
//---------------------------------------------------------------------||
function FormatExternalUrlWithLink(strUrl) {
   var strLink = '';
   strUrl = strUrl.toString();
   if( strUrl.length > 0 ) {
      var strFqUrl;
      var strDisplay;

      var iProtocolAt = strUrl.indexOf('://');
      if( iProtocolAt > 0 ) {
         strFqUrl = strUrl;
         strDisplay = strUrl.substring(iProtocolAt + 3);
      } else {
         strDisplay = strUrl;
         strFqUrl = 'http://' + strUrl;
      }
      var iDirectoryAt = strDisplay.indexOf('/');
      if( iDirectoryAt > 0 ) {
         strDisplay = strDisplay.substring(0, iDirectoryAt);
      }
      strLink = '<a href="'+strFqUrl+'" target="_external">' + strDisplay + '</a>';
   }

   return strLink;
}

//---------------------------------------------------------------------||
// FUNCTION:    FormatEmailWithLink                                    ||
// PARAMETERS:  email to be formatted                                  ||
// RETURNS:     HTML fragment with HREF to formatted email             ||
// PURPOSE:     Link email consistently                                ||
//---------------------------------------------------------------------||
function FormatEmailWithLink(strEmail) {
   var strLink = '';
   strEmail = strEmail.toString();
   if( strEmail.length > 0 ) {
      var iProtocolAt = strEmail.indexOf('@');
      if( iProtocolAt > 0 ) {
         strLink = '<a href="mailto:'+strEmail+'">' + strEmail + '</a>';
      }
   }
   return strLink;
}

//---------------------------------------------------------------------||
// FUNCTION:    IfLinkNotInCbcNetworkForceConfirmation                 ||
// 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  ||
//---------------------------------------------------------------------||
//'Are you sure you want to go to a site not on the Coldwell Banker Commercial site?'
function IfLinkNotInCbcNetworkForceConfirmation()
{
   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 (!isValidCbcServer(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 isValidCbcServer(strServerName)
{
   var CurrentServer = document.location.host.toLowerCase();

   if( strServerName.indexOf(".coldwellbankercommercial.com") >= 0 ){
      return true;
   }
   if( strServerName == "coldwellbankercommercial.com" ){
      return true;
   }
   if( strServerName.indexOf(".realogy.com") >= 0 ){
      return true;
   }
   if( strServerName.indexOf(".instantclientaccess.com") >= 0 ){
      return true;
   }
   if( strServerName == "instantclientaccess.com" ){
      return true;
   }
   if( strServerName == CurrentServer ){
      return true;
   }

   return false;
}


//---------------------------------------------------------------------||
// FUNCTION:    RestorePreviousFormFill                                ||
// PARAMETERS:  Pointer to form to restore values of, cookie name with ||
//              previous data (GET format URL)                         ||
// RETURNS:     Nothing                                                ||
// PURPOSE:     Restores previous form data based on a saved GET mode  ||
//              URL stored in cookie strCookieName.                    ||
//---------------------------------------------------------------------||
function RestorePreviousFormFill( pForm, strCookieName )
{
   if( !pForm || !strCookieName ){
      return;
   }
   SavedQueryString_Parse( GetCookie(strCookieName) );
   var iNumElements = pForm.elements.length;
   for( var i=0; i < iNumElements; i++ ){
      if(pForm.elements[i].type == 'select-one' ) {
         var strLast = UrlDecode(QueryString( pForm.elements[i].name ));
         if( strLast ) {
            for( var j=0; j<pForm.elements[i].length; j++ ){
               if( pForm.elements[i][j].value == strLast ){
                  pForm.elements[i][j].selected = true;
               }
            }
         }
      } else if(pForm.elements[i].type == 'text' ) {
         var strLast = UrlDecode(QueryString( pForm.elements[i].name ));
         if( strLast && strLast != 'null'  ){
            pForm.elements[i].value = strLast;
         }         
      }
   }

   //Now repeat for postbacks
   QueryString_Parse();
   for( var i=0; i < iNumElements; i++ ){
      if(pForm.elements[i].type == 'select-one' ) {
         var strLast = UrlDecode(QueryString( pForm.elements[i].name ));
         if( strLast && strLast.length > 0) {
            for( var j=0; j<pForm.elements[i].length; j++ ){
               if( pForm.elements[i][j].value == strLast ){
                  pForm.elements[i][j].selected = true;
               }
            }
         }
      } else if(pForm.elements[i].type == 'text' ) {
         var strLast = UrlDecode(QueryString( pForm.elements[i].name ));
         if( strLast && strLast != 'null' && strLast.length > 0   ){
            pForm.elements[i].value = strLast;
         }
      }
   }
}


//---------------------------------------------------------------------||
// FUNCTION:    ImgQuickSwap                                           ||
// PARAMETERS:  N/A                                                    ||
// RETURNS:     True if photo could NOT be swapped                     ||
// PURPOSE:     Swaps out photo without forcing page load.             ||
//---------------------------------------------------------------------||
function CbcImgQuickSwap( pPhotoToSwap, strSrcId, strNewPhoto, strCaption, strLargeFileUrl ) 
{
   var bReturn = true;

   if( !pPhotoToSwap ) return;

   if ( pPhotoToSwap ) {
      if ( pPhotoToSwap.src ) {
         pPhotoToSwap.src = strNewPhoto;
         bReturn = false;
      }
      var pLPE = document.getElementById( strSrcId );
      if( pLPE ) {
         if ( strLargeFileUrl ) {
            pLPE.value = strLargeFileUrl; 
         }
      }
   }

   if( document.getElementById ) {
      var pCaption = document.getElementById('photocaption');
      if( pCaption ) {
         pCaption.innerHTML = strCaption;
      }
   }
   return bReturn;
}


//---------------------------------------------------------------------||
// FUNCTION:    ShowLargePhoto                                         ||
// PARAMETERS:  Name of photo in document                              ||
// RETURNS:     N/A                                                    ||
// PURPOSE:     Create image popup                                     ||
//---------------------------------------------------------------------||
function ShowLargePhotoUrl( strUrl, strCaptionId )
{
   var strCaption = '';
   var pCaption = document.getElementById(strCaptionId);
   if( pCaption ) {
      strCaption = pCaption.innerHTML;
   }
   if( strUrl != '' ) {
      var pWinPop = window.open('', 'largeImage', 'width=760,height=540,resizeable=yes');
      if( pWinPop ) {
         pWinPop.document.write('<html><head><title>Image</title>');
         pWinPop.document.write('</head><body>');
         pWinPop.document.write('<p align=center><img src="'+strUrl+'"></p><p align=center>');
         pWinPop.document.write(strCaption + '</p><p align=center>');
         pWinPop.document.write('<a href="Javascript:window.close()">Close Window</a></p>');
         pWinPop.document.write(' </body></html>');
         setTimeout( function(){ fitWinToPic(pWinPop); }, 1000 );
      }
   }
}
function fitWinToPic( pWinHandle )
{
   if( pWinHandle ) {
       if( document.images[0].complete ) {
          var NS = (navigator.appName=="Netscape")?true:false;
          var iWidth = (NS)?pWinHandle.innerWidth:pWinHandle.document.body.clientWidth;
          var iHeight = (NS)?pWinHandle.innerHeight:pWinHandle.document.body.clientHeight;

          var iThisWidth = (NS)?window.innerWidth:document.body.clientWidth;
          var iThisHeight = (NS)?window.innerHeight:document.body.clientHeight;

          if( iWidth > iThisWidth ) iWidth = iThisWidth + 20;
          if( iHeight > iThisHeight ) iHeight = iThisHeight + 100;

          if( pWinHandle.document.images[0].width > iThisWidth ) pWinHandle.document.images[0].width = iThisWidth - 30;
          else if( pWinHandle.document.images[0].height > iThisHeight) pWinHandle.document.images[0].height = iThisHeight - 30;

          iWidth = (pWinHandle.document.images[0].width - iWidth) + 20;
          iHeight = (pWinHandle.document.images[0].height - iHeight) + 100;
          if( (iWidth > 0) || (iHeight > 0) ) {
             pWinHandle.resizeBy(iWidth, iHeight);
             pWinHandle.focus();
          }
       } else if ( pWinHandle.document.images[0] ) {
          setTimeout( function(){ fitWinToPic(pWinPop); }, 250 );
       }
   }
}

