
// Copyright Frith Content Inc. 2009-10 //
// All rights reserved. //

// Update via proxy iframe:
if (document.location.hash.indexOf('proxy_h_ff') > -1) 
{
  hash = document.location.hash.replace(/proxy_/i, '');
  top.location.hash = hash;
  top.HistMan.cHash = hash;
  top.HistMan.doCallback();
}
  


  function JSONscriptRequest(fullUrl) {
      this.fullUrl = fullUrl;
      this.noCacheIE = '&no_cache=' + new Date().getTime();
      this.headLoc = top.document.getElementsByTagName("head").item(0);
      this.scriptId = 'FrithTransportScript';
  }
  JSONscriptRequest.prototype.buildScriptTag = function () {
      this.scriptObj = top.document.createElement("script");
      this.scriptObj.setAttribute("type", "text/javascript");
      this.scriptObj.setAttribute("charset", "utf-8");
      this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
      this.scriptObj.setAttribute("id", this.scriptId);
  };
  JSONscriptRequest.prototype.removeScriptTag = function () {
      if (top.ff$(this.scriptId)) {this.headLoc.removeChild(top.ff$(this.scriptId));}
  };
  JSONscriptRequest.prototype.addScriptTag = function () {
      this.removeScriptTag();
      this.headLoc.appendChild(this.scriptObj);
  };
  function ffAddContainer() {
      if (ff$(container_id)) return ff$(container_id);
      if (window.ff_placeholder_text === undefined) {
          ff_placeholder_text = "Loading your local content now...";
      }
      var container_div = top.document.createElement('div');
      container_div.setAttribute('id', container_id);
      container_div.setAttribute('class', 'ff_container');
      container_div.innerHTML = '<div style="padding:10px; font-size:11px; color:#555;">' + ff_placeholder_text + '<br /><strong>This will take only a few moments...</strong>' + '<img src="http://www.francisfrith.com/fpn/assets/images/spinner.gif" style="margin: 3px 5px -3px 5px; border: 0px;" />' + '</div>';
      var caller = top.ff$('ff_script_' + ff_apikey);
      caller.parentNode.insertBefore(container_div, caller);
      ffCss();
      return container_div;
  }
  function ffResponseObservers() {
      try{
          var links = ff$('ff_container_' + ff_apikey).getElementsByTagName("a");
          for (i=0;i<=links.length-1;i=i+1) {
            a = links[i];
            a.href = a.href.replace(current_domain, ff_domain);
            if (a.href.match(/^\/.*?/)) {a.href = ff_domain + a.href;}                
            a.onclick = ffLinkHandler;
          };
      }
      catch(e) { alert('Link observers failed: ' + e); }
  }
  function ffLinkHandler(event) {

      if (!event) var event = window.event;
      
      if (event.target) { a = event.target; }
      else if (event.srcElement) { a = event.srcElement; }
      
      a1 = a;
      if (a.nodeName !== 'A') {
          a = a.childNodes[0];
          if (a) if (a.nodeName !== 'A') a = a1.parentNode;
          if (!a) a = a1.parentNode;
          else if (a.nodeName !== 'A') a.parentNode;
      }

      if (ffHasClassName(a, 'ff_external')) {
          a.target = "_blank";
          // Replace FQD specified in a partner's base element:
          if (document.getElementsByTagName('BASE'))
          {
            var base = document.getElementsByTagName('BASE')[0].href;
            if (base.substring(base.length-1, base.length) === '/') base = base.substring(0,base.length-1);
            a.href = a.href.replace(base, 'http://www.francisfrith.com');
          }
          //Append explicit Google Analytics referer tracking:
          var referer = current_domain.replace(/(https?:\/\/)|(www\.)|(\.com)/ig, '');
          a.href = a.href + (a.href.indexOf('?')>-1 ? '&' : '?') + 'partner=' + ff_country + '&utm_source=' + referer + '&utm_medium=api&utm_campaign=fpn';
          container.innerHTML = '<div id="ff_updating" style="width:250px;"><div>Taking you to the Francis Frith site to give you further information...</div></div>' + container.innerHTML;
          setTimeout("var updater = ff$('ff_updating');container.removeChild(updater);ffResponseObservers();", 1000);
          return;
      }
      else {
        
        ffStop(event);
      
        if (ff$('FrithTransportScript') && ff$('ff_updating')) {
            ff$('ff_updating').childNodes[0].innerHTML = 'Loading.....';
            return false;
        }
    
        var o = a.href.replace(/file\:\/\/\/?/,'');
        h = o.replace('http://','');
        h = h.replace('www.francisfrith.com','');    
    
        var api_url = 'http://www.francisfrith.com/fpn/api/?apikey=' + ff_apikey;
        href = api_url + '&service=' + o.replace(/\/pageloader\.asp\?page=/, '') + '&api=y';

        a.blur();
    
        ff_fragment++;
      
        var histObj = {
            hash: 'ff_' + ff_fragment,
            arg: href,
            callback: 'ffGetContent'
        };
        HistMan.register(a, histObj);
        container.innerHTML = '<div id="ff_updating"><div>Loading...</div></div>' + container.innerHTML;
      
        var c_top = ffContainerTop(container).left;
        if (c_top < 0) window.scrollTo(0,0);
     }

  }
	function ffQuestion() {
		var eData = ff$('ff_question_email').value
		var qData = ff$('ff_question_text').value
		
		if (eData == '' || qData =="") return;
		
		var qUrl  = 'http://www.francisfrith.com/fpn/feeds/ws_support_files/question.asp';

		ff$('ffqform').innerHTML = '<div id="ff_updating"><div>Sending Enquiry...</div></div>'
		
		var qReq = new JSONscriptRequest(qUrl+"?e="+eData+"&q="+qData);
		qReq.buildScriptTag();
		qReq.addScriptTag();
		
		setTimeout("ff$('ffqform_content').innerHTML = '<p style=\"font-size: 1.2em;\"><strong>Your message has been sent!</strong></p>'",1500);

	}
  function ffContainerTop( el ) {
      var _y = 0;
      while( el && !isNaN( el.offsetTop ) ) {
          _y += el.offsetTop - el.scrollTop;
          el = el.parentNode;
      }
      return { left: _y };
  }
  function ffStop(e) {
  	if(!e) e        = window.event;
  	e.cancelBubble  = true;
  	e.returnValue   = false;
    if (e.stopPropagation) {
      e.stopPropagation();
      e.preventDefault();
    }
  	return false;
  }
  function ffHasClassName(element, strClass)
   {
      if (element.className)
      {
          var arrList = element.className.split(' ');
          var strClassUpper = strClass.toUpperCase();
          for (var i = 0; i < arrList.length; i++)
          {
              if (arrList[i].toUpperCase() == strClassUpper)
              {
                  return true;
              }
          }
      }
      return false;
  }
  function ffCss() {
      var css;
      if (ff_apikey && !ff$('frith_css')) {
        css = top.document.createElement('link');
          css.setAttribute('rel', 'stylesheet');
          css.setAttribute('id', 'frith_css');          
          css.setAttribute('href', ff_domain + '/fpn/api/' + ff_apikey + '.css');
          css.setAttribute('type', 'text/css');
          css.setAttribute('media', 'all');
          css.setAttribute('charset', 'utf-8');
          top.document.getElementsByTagName('head')[0].appendChild(css);
      }
  }
  function ffGetContent(url) {
      ff_page_jsr = new JSONscriptRequest(url);
      ff_page_jsr.buildScriptTag();
      ff_page_jsr.addScriptTag();
  }
  function writeContent(jsonData) {
      if (!container) {
          alert("Unable to write content because no container matching #" + container_id + " exists.");
      } else {
          if (jsonData.responseText.match(/Error:\s.*?/i) !== null) {
              top.container.innerHTML = 'Sorry, an error occurred whilst fetching your requested content.  Please go back a page and try again.<br />If this error persists, please let us know via email at <b>technical.support' + '@' + 'francisfrith'+'.c' + 'om</b>.'
          } else {
              var content_error_text = '<strong>No local content was found.<\/strong><br \/><br /><br />Technical note: It could be ' + 'that either the location information was not passed to Frith in the expected format, ' + 'or this location is outside the bounds of Frith\'s coverage. You should also check that ' + 'the Frith JavaScript is intact.';
              var a_id = 'h_ff_' + ff_fragment;
              top.container.innerHTML = (jsonData.responseText === '') ? content_error_text : '<a name="' + a_id +'" id="' + a_id +'"></a>' + jsonData.responseText;
              ffResponseObservers();
          }
      }
      if (ff_jsr) {ff_jsr.removeScriptTag();}
  }
  function ffLoader() {
    //console.info('ffLoader');
    container = ffAddContainer();
    HistMan.start();
    var el = null;
    var histObj = {
        hash: 'ff_' + ff_fragment,
        arg: initial_url,
        callback: 'ffGetContent'
    };
    HistMan.register(el, histObj);          
  }
  function ff$(element) {
    return (document.getElementById(element) ? document.getElementById(element) : false);
  }
  
      var current_domain = window.location.href.match(/(https?:\/\/[^\/]+)/)[1];
      var ff_domain = 'http://www.francisfrith.com';
      var api_url = 'http://www.francisfrith.com/fpn/api/?apikey=' + ff_apikey;
      var ff_country = 'UK';
      var initial_service = '';
      var ffLoaded = false;
      var container_id = 'ff_container_' + ff_apikey;
      var container;
      var initial_url = api_url + '&search=' + ff_search;
      var ff_fragment = 1;
      var ff_jsr;


      var HistMan = function () {
      
          var registry    = {};
          var pHash       = '';
          var scriptUri   = 'http://www.francisfrith.com/fpn/assets/javascripts/js_history_manager.asp';
          var callback    = '';

          return {
              cHash: '',
              start: function (fn) {
                  HistMan_loaded = true;
                  callback = 'ffGetContent';
                  //window.location.hash = 'h_ff_1';
                  cHash = HistMan.getHash();
                  pHash = '';
                  if (!document.all) {
                      HistMan.watch();
                  } else {
                      if (!window.location.hash) {window.location.hash = 'h_ff_1';}
                      if (window.location.hash.indexOf('h_ff') === -1) {window.location.hash = 'h_ff_1';}
                      HistMan.proxy();
                      HistMan.add(cHash);
                      HistMan.watch();
                  }
              },
              proxy: function() {
                if (ff$('ff_proxy')) { return; }
                var ifrm = document.createElement('iframe');
                    ifrm.width       = '1';
                    ifrm.height      = '1';
                    ifrm.frameBorder = '0';
                    ifrm.name        = 'ff_proxy';
                    ifrm.id          = 'ff_proxy';
                    ifrm.src         = scriptUri;
                    document.body.appendChild(ifrm);
              },
              watch: function() {
                setInterval(function (pe) {
                    cHash = HistMan.getHash();
                    if (pHash != cHash) {
                        pHash = cHash;
                        HistMan.doCallback();
                    }
                }, 100);
              },
              register: function (element, obj) {
                  var key = (obj.hash) ? obj.hash : obj.arg;
                  if (registry[key]) throw 'Tried to register a key that already exists!';
                  registry[key] = {
                      arg: obj.arg,
                      callback: (obj.callback || false)
                  };
                  HistMan.add(key)
              },
              add: function (key) {
                  if (!key) return;
                  if (!document.all) window.location.hash = 'h_' + key;
                  else {
                    if (!ff$('ff_proxy')) {
                      HistMan.proxy();
                      HistMan.add(key);
                      return;
                    }
                    else {
                      ff$('ff_proxy').src = scriptUri + "?hash=" + key + '&ref=' + escape(window.location.href);
                    }
                  }
              },
              doCallback: function (arg) {
                  var obj = registry[HistMan.getHash()];
                  if (obj) {
                      ffGetContent(arg || obj.arg)
                  } else {
                      ffGetContent(initial_url)
                  }
              },
              getHash: function () {
                  return window.location.hash.replace('#h_', '');                  
              }
          }
      }();


window.onload = ffLoader;
