// important to namespace all js that we add to client DOM
var Everett = Object; 
Everett.parent_domain = 'liveworld.com';
Everett.parent_window_url_search = window.location.search;
Everett.iframe_domain = 'livebar.liveworld.com';
Everett.base_url      = window.location.protocol + '//'+Everett.iframe_domain;
Everett.strip_www     = true; // switch to false to leave www in urls
client_page_url = (Everett.strip_www) ? decodeURIComponent(document.location.href).split("?")[0].replace(/\/\/www\./, '//') : decodeURIComponent(document.location.href).split("?")[0];
Everett.bundle_url    = encodeURIComponent(client_page_url);
Everett.widget_id     = 0;
Everett.init_added    = false; // boolean to track whether the initialization call has been added to the client site.
Everett.isIE6         = (navigator.appName == 'Microsoft Internet Explorer' && navigator.appVersion.indexOf('MSIE 6') > -1);
Everett.has_scrolled_ie6  = false; // IE6 flag that triggers when the window is scrolled; needed by modal_window to position the overlay

// this bootstrap method is executed when the page's content is loaded
Everett.init = function() {
  document.domain = Everett.parent_domain

  Everett.write_iframe();
  Everett.load_css();
  Everett.fix_ie6();
  // delay this call to account for flash content that is dynamically added by the page's javascript;
  // even if the actual resource hasn't loaded in the first second, the DOM HTML manipulation should
  // have easily completed.
  setTimeout('Everett.fix_ff2_mac_flash()', 1000);
}

// --------------- methods invoked during initialization ---------------------

Everett.fix_ie6 = function() {
  // sniff for IE6; since IE6 doesn't support position:fixed, a JS implementation is required to not
  // impact global CSS for the parent page.
  if (Everett.isIE6) {
    /**
    * Calculate the bottom of the viewport minus the height of the bar. Returns an integer
    */
    Everett.get_fixed_scroll_position = function() {
      var heightString = document.getElementById('everett_iframe_div').style.height.replace(/px/, '');
      // document.documentElement['clientHeight'] == the height of the viewport (borrowed from prototype)
      // window.document.documentElement['scrollTop'] == vertical scroll offset from top of document
      // heightString == the height of the bar
      return (document.documentElement['clientHeight'] + window.document.documentElement['scrollTop']) - parseInt(heightString);
    }
  
    /**
    * Reposition bar on IE 6 window onScroll. Switches positioning from bottom to top and calls get_fixed_scroll_position() 
    * to determine the new position. 
    */
    Everett.fix_scroll_position = function() {
      document.getElementById('everett_iframe_div').style.bottom = 'auto';
      document.getElementById('everett_iframe_div').style.top = Everett.get_fixed_scroll_position() + 'px';
      Everett.has_scrolled_ie6 = true;
    }
  
    /**
    * Reposition bar on IE 6 window onResize. Switches positioning from top to bottom, which IE consistently renders properly.
    */
    Everett.fix_resize_position = function() {
//      setTimeout("Everett.iframe_execute('Everett.IE6_resize_drag_handle()')", 1000);
      document.getElementById('everett_iframe_div').style.top = 'auto';
      document.getElementById('everett_iframe_div').style.bottom = '-1px';
    }
  
    /**
    * Foundation work for the repositioning calls to work: sets document.domain, makes the initial function call to reposition
    * and then attaches positioning calls to the window's onresize and onscroll events.
    */
    Everett.fixed_position_patch = function() {
      document.domain = Everett.parent_domain;
      // first one is for the equivalent of onload, though since the page has loaded and this is 
      // being appended to the DOM we have to sort of pretend...
      Everett.fix_resize_position();
  
      // attach to window scroll and resize events
      window.attachEvent('onscroll', Everett.fix_scroll_position);
      window.attachEvent('onresize', Everett.fix_resize_position);
    }
    
    // initial positioning call
    Everett.fixed_position_patch();
  } 
};

/* Firefox 2 on Mac has issues with Flash showing through a CSS-positioned layer, even if it's an iframe, even if it's not transparent.
   the following 2 functions determine if the user agent is FF2 on a Mac and if so examines the client page for embedded flash and hides
   any it finds. */
Everett.fix_ff2_mac_flash = function() {
  if (Everett.isFF2Mac) {
    htmlObjects = document.getElementsByTagName('object');
    for (i=0 ; i<htmlObjects.length ; i++) {
      if (htmlObjects[i].getAttribute('codebase').indexOf('flash') > -1) {
        htmlObjects[i].style.visibility = 'hidden';        
      }
    }
    htmlIFrames = document.getElementsByTagName('iframe');
    for (i=0 ; i<htmlIFrames.length ; i++) {
      if (htmlIFrames[i].id != 'everett_iframe' && htmlIFrames[i].id != 'livebar_iframe') {
        htmlIFrames[i].style.visibility = 'hidden';
      }
    }
  }
}

// Need to hide all Flash in FF2 on Mac as they show through the iframe
Everett.detectMacXFF2 = function() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (/firefox[\/\s](\d+\.\d+)/.test(userAgent)) {
    var ffversion = new Number(RegExp.$1);
    if (ffversion < 3 && userAgent.indexOf('mac') != -1) {
      return true;
    }
  }
}

Everett.isFF2Mac = Everett.detectMacXFF2();

/* IE 6 shows select menus through CSS-positioned layers, even through the everett iframe. loop through all select menus and hide them. */
Everett.toggle_select_menus = function(visiblity_to_set) {
  var select_menus_to_toggle = document.getElementsByTagName('select');
  for (i=0 ; i<select_menus_to_toggle.length ; i++) {
    select_menus_to_toggle[i].style.visibility = visiblity_to_set;
  }
}

Everett.write_iframe = function() {
  document.body.innerHTML += '<div id="everett_iframe_div" style="height:50px">'+
                             '<iframe id="everett_iframe" name="everett_iframe" src="'+
                             Everett.base_url + Everett.get_everett_link() +
                             '?t=' + parseInt(new Date().getTime()) + 
                             '&url=' + Everett.bundle_url + '" scrolling="no" frameborder="0"'+
                             ' allowtransparency="false"></iframe></div>';
};

Everett.load_css = function() {
  // appending timestamp forces reload of stylesheet  
  var timestamp = parseInt(new Date().getTime()/86400000);

  // Safari does not like the document.head.innerHTML to be modified,
  //  so we need to use DOM manipulation to add elements to it
  var cssNode = document.createElement('link');
  cssNode.type = 'text/css';
  cssNode.rel = 'Stylesheet';
  cssNode.href = Everett.base_url + '/stylesheets/iframe.css';
  document.getElementsByTagName("head")[0].appendChild(cssNode);
};

// ------------- utility methods used in the context of the client page (ie not in our iframe) -------------

Everett.iframe_execute = function(codeToExecute) {
  document.domain = Everett.parent_domain;
  window.top.frames.everett_iframe.eval(codeToExecute);
};

Everett.get_everett_link = function ()
{
  document.domain = Everett.parent_domain

  var regex = new RegExp( "everett_link=([^&]*)" );
  var results = regex.exec( decodeURIComponent(Everett.parent_window_url_search));
  if( results == null ){
    return "";
  } else {
    return results[1];
  }
};

Everett.get_goto_url_link = function ()
{
  document.domain = Everett.parent_domain

  var regex = new RegExp( "goto_url=([^&]*)" );
  var results = regex.exec( decodeURIComponent(Everett.parent_window_url_search));
  if( results == null ){
    return "";
  } else {
    return results[1];
  }
};

// options = { 'widget_action' : 'url',
//             'query'         : 'parameters to pass',
//             'css_classname  : 'name of css class to apply to widget' }
Everett.widget = function(resource, options) {
  options.widget_action = options.widget_action ? ('/' + options.widget_action) : '';
  options.query = options.query ? ('&' + options.query) : '';
  options.css_classname = (options.css_classname) ? ' ' + options.css_classname : '';
  document.write( '<div class="everett_widgets everett_widgets_' + resource + options.css_classname + '" ' +
                  'id="everett_widget_'+Everett.widget_id++ +'" ' +
                  'lang="/widgets/' + resource + options.widget_action +
                  '?url='+Everett.bundle_url + options.query + '"></div>');
};

// Dean Edwards/Matthias Miller/John Resig, edited by Everett Team
Everett.add_load_event = function() {
  // quit if this function has already been called
  if (arguments.callee.done) return;

  // flag this function so we don't do the same thing twice
  arguments.callee.done = true;

  // kill the timer
  if (_timer) clearInterval(_timer);
  
  Everett.init();
};

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
  document.write("<s"+"cri"+"pt id=__ie_onload defer src=javascript:void(0)><\/script>");
  var script = document.getElementById("__ie_onload");
  script.onreadystatechange = function() {
    if (this.readyState == "complete") {
      Everett.add_load_event(); // call the onload handler
    }
  };
  Everett.init_added = true;
/*@end @*/

/* for Mozilla/Opera9 */
if (document.addEventListener) {
  document.addEventListener("DOMContentLoaded", Everett.add_load_event, false);
  Everett.init_added = true;
};

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
  var _timer = setInterval(function() {
    if (/loaded|complete/.test(document.readyState)) {
      Everett.add_load_event(); // call the onload handler
    }
  }, 10);
  Everett.init_added = true;
};

/* for other browsers */
if (!Everett.init_added) {
  var oldonload = window.onload; 
  if (typeof window.onload != 'function') { 
    window.onload = func; 
  } else { 
    window.onload = function() { 
      if (oldonload) { 
        oldonload(); 
      } 
      func(); 
    } 
  }
  
  Everett.add_load_event();
};


// set display none to all select menus; needed for the modal window in IE 6 only
Everett.hideSelectMenus = function() {

};

//  Developed by Robert Nyman, http://www.robertnyman.com
//  Code/licensing: http://code.google.com/p/getelementsbyclassname/
Everett.getElementsByClassName = function (className, tag, elm){
  if (document.getElementsByClassName) {
    getElementsByClassName = function (className, tag, elm) {
      elm = elm || document;
      var elements = elm.getElementsByClassName(className),
        nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
        returnElements = [],
        current;
      for(var i=0, il=elements.length; i<il; i+=1){
        current = elements[i];
        if(!nodeName || nodeName.test(current.nodeName)) {
          returnElements.push(current);
        }
      }
      return returnElements;
    };
  }
  else if (document.evaluate) {
    getElementsByClassName = function (className, tag, elm) {
      tag = tag || "*";
      elm = elm || document;
      var classes = className.split(" "),
        classesToCheck = "",
        xhtmlNamespace = "http://www.w3.org/1999/xhtml",
        namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
        returnElements = [],
        elements,
        node;
      for(var j=0, jl=classes.length; j<jl; j+=1){
        classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
      }
      try  {
        elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
      }
      catch (e) {
        elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
      }
      while ((node = elements.iterateNext())) {
        returnElements.push(node);
      }
      return returnElements;
    };
  }
  else {
    getElementsByClassName = function (className, tag, elm) {
      tag = tag || "*";
      elm = elm || document;
      var classes = className.split(" "),
        classesToCheck = [],
        elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
        current,
        returnElements = [],
        match;
      for(var k=0, kl=classes.length; k<kl; k+=1){
        classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
      }
      for(var l=0, ll=elements.length; l<ll; l+=1){
        current = elements[l];
        match = false;
        for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
          match = classesToCheck[m].test(current.className);
          if (!match) {
            break;
          }
        }
        if (match) {
          returnElements.push(current);
        }
      }
      return returnElements;
    };
  }
  return getElementsByClassName(className, tag, elm);
};
