// ML, somewhere in May 2009.  Created.

function requiredMarkupAdded() {
  // Tests for the DOM to have or not the YUI History required markup.
  // See http://developer.yahoo.com/yui/history/ for details.
  var E1=document.getElementById("yui-history-iframe");
  var E2=document.getElementById("yui-history-field");
  var res = (E1==null?0:1) + (E2==null?0:2);
  return res;
}

function addRequiredMarkup(elemId) {
  // IE Needs this part of the code. An iframe and an input are required for YH to
  // work.  This code makes sure it's added at the proper time.
  // Default value for elemId is 'mailingsubscription'. We insert before the 
  // elem of this id, because it is the closest to the body tag.
  // For some pages implementing YH this may not be the right value.
  // Furthermore, if this ID change, this code breaks.
  if(!requiredMarkupAdded()) {    
//    if(elemId==null) {
//      elemId="mailingsubscription";
//  }
    var iframe1 = document.createElement("iframe");
    iframe1.setAttribute("id", "yui-history-iframe");
    iframe1.setAttribute("src", "/site/img/spacer.gif");
    iframe1.text = "&nbsp;";
    if(elemId==null) {
      var sp1 = document.getElementsByTagName('body')[0];
    } else {
      var sp1 = document.getElementById(elemId);
    }
    var parentDiv1 = sp1.parentNode;
    parentDiv1.insertBefore(iframe1, sp1);

    // Creates <input id="yui-history-field" type="hidden"> 
    // and inserts is as closest as possible to the body tag
    var input1 = document.createElement("input");
    input1.setAttribute("id",   "yui-history-field");
    input1.setAttribute("type", "hidden");
    var parentDiv2 = sp1.parentNode;
    parentDiv2.insertBefore(input1, sp1);
  }
}

function StartYH(uiid,defaultState,changeHandler) {
  // This call fullfills all the YH needs.  
  YAHOO.util.Event.onDOMReady(function(){
    try {
      addRequiredMarkup();     // Required by IE ...
      var initialState = YAHOO.util.History.getBookmarkedState(uiid) || defaultState;
      YAHOO.util.History.register(uiid, initialState, changeHandler);
      YAHOO.util.History.onReady(function()  {
        var state = YAHOO.util.History.getCurrentState(uiid);
        changeHandler(state);
      });
      YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");
     } catch (e) {
      // Uncomment for troubleshooting.
      //alert('ERR! name='+e.name+', message='+e.message);
     }
  });
}

