/**
 * Manages messages sent to C21 from eN
 * Assumes that eN is in a framed page
 */
window.C21Transport = (function() {
   // We have to do this before we attempt to access the outer frame
   document.domain = getTopLevelDomain();

   // If we're not in an iFrame with access to C21, do NOT continue
   // Try/Catch will not catch an XSS error
   if ((!parent) || (!parent.portalAjax)) return;

   // Whether or not the page type has been set by eN
   var m_bPageTypeIsSet = false,

      // Cookie socket
      m_socketChild = true,
      
      // Messages sent before the javascript is loaded
      // and the socket is initialized
      m_aQueuedMessages = [];
      
   /**
    * Get the domain
    * @return ex: century21.com
    */
   function getTopLevelDomain() {
      var strDomain = document.location.host,
         aDomainParts = strDomain.split('.'),
         strTopLevelDomain = aDomainParts[aDomainParts.length - 2];

      return strTopLevelDomain + '.com';
   }

   /**
    * Send the height of the document
    */
   function sendHeight() {
      // eNeighborhoods has a table that will expand to 100% height
      // (this resets the table height, which seems to not break anything)
      var jTable = $('#framedcontainer > table, #container > table').attr('height', ''),
         iDocumentHeight = jTable.height();

      queueMessage({
         call: 'resize',
         height: iDocumentHeight
      });
   }

   /**
    * Show the contact form
    */
   function showContactForm() {
      var jAssociation = $("#OfficeAssociation, #PropertyMap_C211_OfficeAssociation");
      queueMessage({
         call: 'showContactForm',
         associationKey: jAssociation.text(),
         lidxurl: $("#pageurl").text(),
         lmls: $("#MlsNumber").text(),
         laddress: $("#Address").text(),
         lcity: $("#City").text(),
         lstate: $("#State").text(),
         lzip: $("#Zip").text(),
         ltype: $("#ListingTypeId").text(),
         lid: $("#ListingId").text(),
         lmlsid: $("#MlsId").text()
      });
   }

   /**
    * Set the comments (for the PDP)
    * @param strComments
    */
   function setComments(strComments) {
      queueMessage({
         call: 'setComments',
         comments: strComments
      });
   }

   /**
    * Show the "See All" link
    */
   function showSeeAllLink() {
      queueMessage({
         call: 'showSeeAllLink'
      });
   }

   /**
    * Set the frame type to PDP
    */
   function showProperty() {
      if (m_bPageTypeIsSet) return;
      m_bPageTypeIsSet = true;
      showContactForm();
   }

   /**
    * Set the frame type to PRP
    */
   function showResults() {
      if (m_bPageTypeIsSet) return;
      m_bPageTypeIsSet = true;
      showSeeAllLink();
   }

   /**
    * Include the specified javascript files in parallel
    * @param aScriptUrls the scripts to include
    * @param fnOnLoad the function to call when all scripts are loaded
    */
   function includeJavascript(aScriptUrls, fnOnLoad) {
      var m_aLoadedScripts = [],
         elHead = document.getElementsByTagName("head")[0];

      function onJavascriptLoad(strScriptUrl) {
         // If the script is already included, don't continue
         for (var i = 0; i < m_aLoadedScripts.length; i++) {
            var strLoadedScriptUrl = m_aLoadedScripts[i];
            if (strLoadedScriptUrl == strScriptUrl) return;
         }

         // Add to list of included scripts
         m_aLoadedScripts.push(strScriptUrl);

         // If all scripts are loaded
         if (m_aLoadedScripts.length == aScriptUrls.length) {
            fnOnLoad(); 
         }
      }

      for (var i = 0; i < aScriptUrls.length; i++) {
         (function() {
            var strScriptUrl = aScriptUrls[i],
               elScript = document.createElement('script');

            // IE version of 'onload'
            elScript.onreadystatechange = function () {
               if (this.readyState == 'loaded' || this.readyState == 'complete') {
                  onJavascriptLoad(strScriptUrl);
               }
            };

            elScript.onload = function() {
               onJavascriptLoad(strScriptUrl);
            };

            elScript.src = strScriptUrl;
            elHead.appendChild(elScript);
         }());
      }
   }

   /**
    * Queue a message for the socket
    * @param oMessage the JSON object to send
    */
   function queueMessage(oMessage) {
      m_aQueuedMessages.push(oMessage);

      // If the XDM socket has not been loaded yet...
      if (!m_socketChild) return;

      // Assume jQuery is loaded if the socket is instantiated 
      $.each(m_aQueuedMessages, function(i, oMessage) {
         sendMessage(oMessage);
      });

      // Clear the message queue
      m_aQueuedMessages = [];
   }

   /**
    * Send a message to Century21 using the XDM socket
    * DO NOT CALL BEFORE SOCKET IS INSTANTIATED
    *
    * @param oMessage the JSON object to send
    */
   function sendMessage(oMessage) {
      parent.sendHandoff(oMessage);
   }

   function sendPageInformation(socket) {
      setInterval(sendHeight, 500);

      // If the page type has not been set yet
      if (m_bPageTypeIsSet) return;

      var strHref = window.location.href,
         iPosition = strHref.search('localproperties.aspx');

      // Attempt to automatically determine the page type
      if (iPosition > 0) {
         showResults();

      // Default to PDP
      } else {
         showProperty();
         
         var jAddress = $('#leftcol .address');
         if (jAddress.length) {
            setComments("I would like to inquire about the property at " + $.trim(jAddress.text()) + ".");
         } else {
            jAddress = $('.PD_Address');
            if (jAddress.length) {
               var strAddress = $(".PD_Address").html().replace(/<br>/g, ", ").replace(/<[^>]*>/g, '');
               setComments("I would like to inquire about the property at " + $.trim(strAddress) + ".");
            }
         }
      }
   }
 
   includeJavascript([
      // These don't have to be on the same domain
      'http://www.century21.com/js/jquery-1.5.js'
   ], function() {
      parent.portalAjax.scrollToTop();
      $(document).ready(sendPageInformation);
   });

   /** Public-facing methods **/
   return {
      showProperty: showProperty,
      setComments: setComments,
      showResults: showResults
   }
}());

var g_strFranchiseSiteUrl = 'http://www.century21.com';
var g_strPoweredByUrl = 'http://www.century21.com';

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


function ffLoadZone( iZoneNumber ) {
   //TO-DO: load zone
   //Call to national site to get zone list, with jump off to other IDX site.
   document.location.href="http://www.century21.com";
}

function ffGetMultiZoneRoutingLinks()
{
   QueryString_Parse();
   var iNumZones = QueryString('c21numzones');
   var iThisZone = QueryString('c21thiszone');
   if( iNumZones != null ) { 
      //We have a new request, thank you.
      SetCookie("c21numzones", iNumZones, null, null, null, false);
   } else {
      iNumZones = GetCookie("c21numzones");
   }
   if ( iNumZones != null && iNumZones != '' ) {
      var iParsedZones = parseInt(iNumZones);
      for (var i=0;i<iParsedZones;i++) {
         var strName = 'Zone ' + (i+1);
         var strUrl = 'javascript:ffLoadZone('+i+');';
         var strClass = '';
         if( iThisZone == i ) strClass = ' class="c21zoneactive"';
         var strHtml = '<div class="c21idxzonecontainer">' +
                       '<li class="c21zoneactive"> <a href="'+strUrl+'"> ' + strName + '</a></li>' +
                       '</div>';
         return strHtml;
      }
   }
   return '';
}

function ffsBuildParameterObject( pArguments )
{
   var aParameters = new Array();
   if (pArguments.length%2==0){
      for (var i=0; i < pArguments.length; i+=2) {
         aParameters[pArguments[i]] = pArguments[i+1];
      }
   }
   return aParameters;
}

function ffSetInnerHtml( aParameters, strHtml )
{
   try {
      if( 'divid' in aParameters ) {
         var pDiv = document.getElementById( aParameters['divid'] );
         if( pDiv ) {
            pDiv.innerHTML = strHtml;
         }
      }
   } catch( e ){
      alert( e.message );
   }
}

function validateRequiredParameters( aParameters, aRequired, strApiFunctionName )
{
   var bOk = true;
   var aMissing = new Array();
   for( var i=0; i < aRequired.length; i++ ) {
      if( aRequired[i] in aParameters) {
      } else {
         aMissing.push( aRequired[i] );
         bOk = false;
      }
   }
   if( !bOk ) {
      var bAlertWritten = false;
      var strError = strApiFunctionName + ' requires the following missing parameter(s): ';
      for( var key in aMissing ) {
         strError += '\n   - ' + aMissing[key];
      }
      if( 'divid' in aParameters ) {
         var pDiv = document.getElementById( aParameters['divid'] );
         if( pDiv ) {
            pDiv.innerHTML = '<pre>' + strError + '</pre>';
            bAlertWritten = true;
         }
      }
      if( !bAlertWritten ) {
         alert( strError );
      }
   }

   return bOk;
}

function FranchiseFrameMultiZoneRouting()
{
   var aParameters = ffsBuildParameterObject(arguments);
   if( !validateRequiredParameters( aParameters, ['divid'], 'FranchiseFrameMultiZoneRouting' ) ) {
      return;
   }
   ffSetInnerHtml( aParameters, ffGetMultiZoneRoutingLinks() );
}

function FranchiseFrameNeighborhoodInfo()
{
   var aParameters = ffsBuildParameterObject(arguments);
   if( !validateRequiredParameters( aParameters, ['divid', 'zip'], 'FranchiseFrameNeighborhoodInfo' ) ) {
      return;
   }
   var strHtml = '<iframe src="'+g_strPoweredByUrl+'/enidxstatic/neighborhoodinfo.jsp?zip='+aParameters['zip']+'" width="984" height="650" frameborder="0"></iframe>'
   ffSetInnerHtml( aParameters, strHtml );
}

function FranchiseFrameRecentHomeSales()
{
   var aParameters = ffsBuildParameterObject(arguments);
   if( !validateRequiredParameters( aParameters, ['divid', 'zip'], 'FranchiseFrameRecentHomeSales' ) ) {
      return;
   }
   var strHtml = '<iframe src="'+g_strPoweredByUrl+'/enidxstatic/recentlysoldhomes.jsp?zip='+aParameters['zip']+'" width="984" height="650" frameborder="0"></iframe>'
   ffSetInnerHtml( aParameters, strHtml );
}

function FranchiseFrameSchools()
{
   var aParameters = ffsBuildParameterObject(arguments);
   if( !validateRequiredParameters( aParameters, ['divid', 'zip'], 'FranchiseFrameSchools' ) ) {
      return;
   }
   var strHtml = '<iframe src="'+g_strPoweredByUrl+'/enidxstatic/schools.jsp?zip='+aParameters['zip']+'" width="984" height="650" frameborder="0"></iframe>'
   ffSetInnerHtml( aParameters, strHtml );
}

function FranchiseFrameMortgageInfo()
{
   var aParameters = ffsBuildParameterObject(arguments);
   if( !validateRequiredParameters( aParameters, ['divid'], 'FranchiseFrameMortgageInfo' ) ) {
      return;
   }
   //No mortgage information
   ffSetInnerHtml( aParameters, '' );
}

function FranchiseFrameMortgageCalc()
{
   var aParameters = ffsBuildParameterObject(arguments);
   if( !validateRequiredParameters( aParameters, ['divid'], 'FranchiseFrameMortgageCalc' ) ) {
      return;
   }
   var strHtml = '<iframe src="'+g_strPoweredByUrl+'/enidxstatic/mortgagecalc.jsp" width="984" height="650" frameborder="0"></iframe>'
   ffSetInnerHtml( aParameters, strHtml );
}

function FranchiseFrameOfficeSearch()
{
   var aParameters = ffsBuildParameterObject(arguments);
   if( !validateRequiredParameters( aParameters, ['divid'], 'FranchiseFrameOfficeSearch' ) ) {
      return;
   }
   var strHtml = '<iframe src="'+g_strPoweredByUrl+'/enidxstatic/officesearch.jsp" width="230" height="500" frameborder="0" scrolling="no"></iframe>'
   ffSetInnerHtml( aParameters, strHtml );
}

function FranchiseFrameAgentSearch()
{
   var aParameters = ffsBuildParameterObject(arguments);
   if( !validateRequiredParameters( aParameters, ['divid'], 'FranchiseFrameAgentSearch' ) ) {
      return;
   }
   var strHtml = '<iframe src="'+g_strPoweredByUrl+'/enidxstatic/agentsearch.jsp" width="230" height="350" frameborder="0" scrolling="no"></iframe>'
   ffSetInnerHtml( aParameters, strHtml );
}

function FranchiseFrameOfficeProfile()
{
   var aParameters = ffsBuildParameterObject(arguments);
   if( !validateRequiredParameters( aParameters, ['divid', 'officekey'], 'FranchiseFrameOfficeProfile' ) ) {
      return;
   }
   var strHtml = '<iframe src="'+g_strPoweredByUrl+'/enidxstatic/officeprofile.jsp?officekey='+aParameters['officekey']+'" width="984" height="800" frameborder="0" scrolling="no"></iframe>'
   ffSetInnerHtml( aParameters, strHtml );
}

function FranchiseFrameAgentProfile()
{
   var aParameters = ffsBuildParameterObject(arguments);
   if( !validateRequiredParameters( aParameters, ['divid', 'sakey'], 'FranchiseFrameAgentProfile' ) ) {
      return;
   }
   var strHtml = '<iframe src="'+g_strPoweredByUrl+'/enidxstatic/agentprofile.jsp?sakey='+aParameters['sakey']+'" width="984" height="800" frameborder="0" scrolling="no"></iframe>'
   ffSetInnerHtml( aParameters, strHtml );
}

function FranchiseFrameAgentCallingCard()
{
   var aParameters = ffsBuildParameterObject(arguments);
   if( !validateRequiredParameters( aParameters, ['divid', 'sakey'], 'FranchiseFrameAgentCallingCard' ) ) {
      return;
   }
   var strUrl = g_strPoweredByUrl+'/enidxstatic/agentcallingcard.jsp?sakey='+aParameters['sakey'];
   if( aParameters['contactformurl'] ) strUrl += '&contactformurl=' + escape( aParameters['contactformurl'] );
   var strHtml = '<iframe src="'+strUrl+'" width="230" height="130" frameborder="0" scrolling="no"></iframe>'
   ffSetInnerHtml( aParameters, strHtml );

}

function FranchiseFrameOfficeCallingCard()
{
   var aParameters = ffsBuildParameterObject(arguments);
   if( !validateRequiredParameters( aParameters, ['divid', 'officekey'], 'FranchiseFrameOfficeCallingCard' ) ) {
      return;
   }
   var strUrl = g_strPoweredByUrl+'/enidxstatic/officecallingcard.jsp?officekey='+aParameters['officekey'];
   if( aParameters['contactformurl'] ) strUrl += '&contactformurl=' + escape( aParameters['contactformurl'] );
   var strHtml = '<iframe src="'+strUrl+'" width="230" height="130" frameborder="0" scrolling="no"></iframe>'
   ffSetInnerHtml( aParameters, strHtml );
}

function FranchiseFrameSlideShowLink()
{
   var aParameters = ffsBuildParameterObject(arguments);
   if( !validateRequiredParameters( aParameters, ['divid', 'mlsnum', 'price', 'beds', 'city', 'state', 'zip'], 'FranchiseFrameSlideShowLink' ) ) {
      return;
   }
   //C21: No Property advanced feature link(s)
   ffSetInnerHtml( aParameters, '');
}

function FranchiseFrameVirtualTourLink()
{
   var aParameters = ffsBuildParameterObject(arguments);
   if( !validateRequiredParameters( aParameters, ['divid', 'mlsnum', 'price', 'beds', 'city', 'state', 'zip'], 'FranchiseFrameVirtualTourLink' ) ) {
      return;
   }
   //C21: No Property advanced feature link(s)
   ffSetInnerHtml( aParameters, '');
}

function FranchiseFrameTalkingGalleryLink()
{
   var aParameters = ffsBuildParameterObject(arguments);
   if( !validateRequiredParameters( aParameters, ['divid', 'mlsnum', 'price', 'beds', 'city', 'state', 'zip'], 'FranchiseFrameTalkingGalleryLink' ) ) {
      return;
   }
   //C21 does not provide printable brocures
   ffSetInnerHtml( aParameters, '');
}

function FranchiseFramePrintableBrochureLink()
{
   var aParameters = ffsBuildParameterObject(arguments);
   if( !validateRequiredParameters( aParameters, ['divid', 'mlsnum', 'price', 'beds', 'city', 'state', 'zip'], 'FranchiseFramePrintableBrochureLink' ) ) {
      return;
   }
   //C21 does not provide printable brocures
   ffSetInnerHtml( aParameters, '');
}


