var isIE = false;
var searchBackground = true;
//Support autofocus attribute
if(jQuery('<input autofocus="autofocus" />')[0].autofocus !== true){
	jQuery(function($){
		$(':input[autofocus]').focus();
	});
}

jQuery(function($){
  isIE = $.browser.msie;
  //hideEditLinks();
  setupEditControls();
  startImageRotator();
  vertCenterStuff();
  addShadowBoxes();
  decorateSearchBox();
  decoratePdfLinks();
  sitemapColumns();
  decorateGlossary();
});

function decorateSearchBox()
{
  $("#searchInput").addClass("background");
  $("#searchInput").hover(function() {
    $(this).addClass("backgroundPoweredBy").removeClass("background"); 
  }, function() {
    if (searchBackground)
    {
      $(this).addClass("background").removeClass("backgroundPoweredBy");
    } else
    {
      $(this).removeClass("background").removeClass("backgroundPoweredBy");
    }
  });
  $("#searchInput").focus(function () { 
    $(this).removeClass("background").removeClass("backgroundPoweredBy"); 
    searchBackground = false;
  });
  /*
  $("#searchInput").blur(function () { 
    if ($(this).val() == "")
    {
      $(this).addClass("background");
    }
  });
  */
  
}

function decoratePdfLinks()
{
  $("a[href$='pdf']").addClass("pdfLink");
  
}

function vertCenterStuff()
{
  var toCenter = $(".vertCenter");
  var n = toCenter.length
  for(var i = 0; i < n; i++)
  {
    thisHeight = $(toCenter[i]).outerHeight();
    containerHeight = $(toCenter[i]).parent().outerHeight();
    if (containerHeight > thisHeight)
    {
      //alert(" adding " + $(toCenter[i]).css("padding-top") + " : " + (containerHeight/2 - thisHeight/2));
      $(toCenter[i]).css("padding-top", (containerHeight/2 - thisHeight/2) + "px");
    }
    
    //alert($(toCenter[i]).parent().outerHeight());
  }
}



function startImageRotator()
{
  // front page image rotator
  $("#imageRotator").cycle({
    fx:                 'fade',
    timeout:            6000, 
    speed:              1250,
    fastOnEvent:        500,
    pause:              1,
    pauseOnPagerHover:  1,
    slideExpr:          'div.slide',
    //before:             turnRotatorNavOn,
    //after:              turnRotatorNavOn,
    debug:              1,
    pager:              '#imageRotator .nav', 
    pagerAnchorBuilder: function(idx, slide) { 
      // return selector string for existing anchor
      return '#imageRotator .nav td:eq(' + idx + ') a' }
    });
  
  //$("#imageRotator").find(".nav").find("div.active").removeClass("active");
  //$($("#imageRotator").find(".nav").find("div.item")[0]).addClass("active");
  
  // vertically center the nav
  var offset = ($("#imageRotator").height()/2) - ($("#imageRotator").find(".nav").height()/2) - 24;
  $("#imageRotator").find(".nav").css({"top": ""+offset+"px"});
  
}

function turnRotatorNavOn()
{
  var n = $("#imageRotator").find(".nav").find("div.item").children().length;
  var j = 0;
  for (var i = 0; i < n; i++)
  {
    if ($($("#imageRotator").find(".nav").find("div.item")[i]).hasClass("active"))
    {
      j = i;
    }
  }
  j++;
  j = j % n;
  $("#imageRotator").find(".nav").find("div.active").removeClass("active");
  $($("#imageRotator").find(".nav").find("div.item")[j]).addClass("active");
}

function addShadowBoxes()
{
  var n = $(".shadowBoxNarrow").length;
  for (var i = 0; i < n; i++)
  {
    decorateShadowBoxNarrow($(".shadowBoxNarrow")[i]);
  }

  n = $(".shadowBoxWide").length;
  //alert("wide shadowboxes: " + n);
  
  for (i = 0; i < n; i++)
  {
    decorateShadowBoxWide($(".shadowBoxWide")[i]);
  }
  
  n = $(".shadowBoxTable").length;
  for (i = 0; i < n; i++)
  {
    decorateShadowBoxTable($(".shadowBoxTable")[i]);
  }
  
}

function decorateShadowBoxTable(shadowBox)
{
  //var heightChange = 16;
  var heightChange = 16;
  var widthChange = 12;
  
  //$(shadowbox).closest("table").attr("cellspacing", "0");
  $(shadowBox).attr("cellspacing", "0").attr("cellpadding", "0");
  $(shadowBox).find("td:empty").html("&nbsp;");
  
  var sB = '<div class="lb shadowBoxWrapper"><div class="rb"><div class="bb"><div class="blc"><div class="brc"><div class="tb"><div class="tlc"><div class="trc"><div class="dsboxcontent">';
  $(shadowBox).wrap(sB);
  
  $(shadowBox).closest("div.lb").width($(shadowBox).outerWidth() + widthChange);
  $(shadowBox).closest("div.lb").height($(shadowBox).closest("div.dsboxcontent").outerHeight() + heightChange);
  $(shadowBox).closest("div.rb").height($(shadowBox).closest("div.dsboxcontent").outerHeight() + heightChange);
  $(shadowBox).closest("div.bb").height($(shadowBox).closest("div.dsboxcontent").outerHeight() + heightChange);
  $(shadowBox).parent().parent().height($(shadowBox).closest("div.dsboxcontent").outerHeight() + heightChange);

  // move margins to outside container
  $(shadowBox).closest("div.lb").css("margin-left",   $(shadowBox).css("margin-left"));
  $(shadowBox).closest("div.lb").css("margin-right",  $(shadowBox).css("margin-right"));
  $(shadowBox).closest("div.lb").css("margin-top",    $(shadowBox).css("margin-top"));
  $(shadowBox).closest("div.lb").css("margin-bottom", $(shadowBox).css("margin-bottom"));

  $(shadowBox).css("margin-left",   0);
  $(shadowBox).css("margin-right",  0);
  $(shadowBox).css("margin-top",    0);
  $(shadowBox).css("margin-bottom", 0);
  
  $(shadowBox).css({'margin-left': '3px', 
                    'margin-right': '5px',
                    'margin-top': '6px',
                    'margin-bottom': '2px'});
  if ($(shadowBox).hasClass("floatLeft"))
  {
    $(shadowBox).closest("div.lb").addClass("floatLeft");
  }
  
  // stripe the table, add borders
  var thNum = $(shadowBox).find("th").length;
  var tdRows = $(shadowBox).find("tr").find("td").parent();
  
  for(var i = 0; i < tdRows.length; i++)
  {
    if ((i == 0) && (thNum > 0))
    {
      $(tdRows[i]).find("td").css("border-top", "1px solid #cccccc");
    }
    
    if (i % 2)
    {
      $(tdRows[i]).addClass("highlight");
    }
    
    $(tdRows[i]).find("td:gt(0)").css("border-left", "1px solid #cccccc");
    
  }
  
  
}



function decorateShadowBoxWide(shadowBox)
{
  var heightChange = 6;
  var widthChange = 6;
  //alert("width: " + $(shadowBox).width());
  //alert("width: " + $(shadowBox).outerWidth(true));
  //alert("height: " + $(shadowBox).height());
  //alert("height: " + $(shadowBox).outerHeight(true));
  
  //$(shadowBox).width($(shadowBox).width());
  //$(shadowBox).height($(shadowBox).height())
  //var sB = '<div class="lb"><div class="rb"><div class="bb"><div class="blc"><div class="brc"><div class="tb"><div class="tlc"><div class="trc"><div class="dsboxcontent"><div class="clear"></div></div></div></div></div></div></div></div></div></div></div>';
  // real one: var sB = '<div class="lb shadowBoxWrapper"><div class="rb"><div class="bb"><div class="blc"><div class="brc"><div class="tb"><div class="tlc"><div class="trc"><div class="dsboxcontent"></div></div></div></div></div></div></div></div></div></div>';
  //var sB = '<div class="lb"><div class="rb"><div class="bb"><div class="blc"><div class="brc"><div class="tb"><div class="tlc"><div class="trc"><div class="dsboxcontent"></div></div></div></div></div></div></div></div></div></div>';
  //var sB = '<div class="lb"><div class="rb"><div class="bb"><div class="blc"><div class="brc"><div class="tb"></div></div></div></div></div></div></div>';
  //var sB = '<div class="borderTest"></div>';
  var sB = '<div class="lb shadowBoxWrapper"><div class="rb"><div class="bb"><div class="blc"><div class="brc"><div class="tb"><div class="tlc"><div class="trc"><div class="dsboxcontent">';
  $(shadowBox).wrap(sB);
  
  /*
  if (isIE)
  {
    alert($(shadowBox).html());
    alert($(shadowBox).parent().html());
    //alert("IE!");
    //$(shadowBox).parent().css("border", "1px solid green");
    //$(shadowBox).parent().parent().css("border", "1px solid blue");
    //$(shadowBox).parent().parent().css("padding-bottom", "10px");
    //$(shadowBox).closest("div.lb").width($(shadowBox).outerWidth() - widthChange);
    //alert($(shadowBox).closest("div.lb").html());
  }
  */
  
  //alert("width x height: " + $(shadowBox).outerWidth() + " x " + $(shadowBox).outerHeight());
  
  $(shadowBox).closest("div.lb").width($(shadowBox).outerWidth() + widthChange);
  $(shadowBox).closest("div.lb").height($(shadowBox).outerHeight() + heightChange);
  $(shadowBox).closest("div.rb").height($(shadowBox).outerHeight() + heightChange);
  $(shadowBox).closest("div.bb").height($(shadowBox).outerHeight() + heightChange);
  $(shadowBox).parent().parent().height($(shadowBox).outerHeight() + heightChange);

  // move margins to outside container
  $(shadowBox).closest("div.lb").css("margin-left",   $(shadowBox).css("margin-left"));
  $(shadowBox).closest("div.lb").css("margin-right",  $(shadowBox).css("margin-right"));
  $(shadowBox).closest("div.lb").css("margin-top",    $(shadowBox).css("margin-top"));
  $(shadowBox).closest("div.lb").css("margin-bottom", $(shadowBox).css("margin-bottom"));

  $(shadowBox).css("margin-left",   0);
  $(shadowBox).css("margin-right",  0);
  $(shadowBox).css("margin-top",    0);
  $(shadowBox).css("margin-bottom", 0);
  
  $(shadowBox).css({'margin-left': '3px', 'margin-right': '0px'});
  if ($(shadowBox).hasClass("floatLeft"))
  {
    $(shadowBox).closest("div.lb").addClass("floatLeft");
  }
  
}

function decorateShadowBoxNarrow(shadowBox)
{
  //var sB = '<div class="lb"><div class="rb"><div class="bb"><div class="blc"><div class="brc"><div class="tb"><div class="tlc"><div class="trc"><div class="dsboxcontent"><div class="clear"></div></div></div></div></div></div></div></div></div></div></div>';
  //var sB = '<div class="lb shadowBoxWrapper"><div class="rb"><div class="bb"><div class="blc"><div class="brc"><div class="tb"><div class="tlc"><div class="trc"><div class="dsboxcontent"></div></div></div></div></div></div></div></div></div></div>';
  var sB = '<div class="lb shadowBoxWrapper"><div class="rb"><div class="bb"><div class="blc"><div class="brc"><div class="tb"><div class="tlc"><div class="trc"><div class="dsboxcontent">';
  $(shadowBox).wrap(sB);
  
  $(shadowBox).closest("div.lb").width($(shadowBox).width()+6);
  $(shadowBox).closest("div.lb").height($(shadowBox).height());
  $(shadowBox).parent().parent().height($(shadowBox).height());
  
  $(shadowBox).css({'margin-left': '2px', 'margin-right': '0px'});
  if ($(shadowBox).hasClass("floatLeft"))
  {
    $(shadowBox).closest("div.lb").addClass("floatLeft");
  }

  /*
  <div class="lb">
    <div class="rb">
    <div class="bb"><div class="blc"><div class="brc">
    <div class="tb"><div class="tlc"><div class="trc">
    <!--  -->
        
    <div class="dsboxcontent">
      <!-- start content -->
      <!-- end content -->
      <div class="clear"></div>
    </div>
    <!--- end of box border -->
    </div></div></div></div>
    </div></div></div></div>
    <!-- -->
  </div>
  */

}



function wrapWithDivs(target, classNames){

  var parentDivs = [];
  var parentDiv;
  
  while (classNames.length){
    var div = document.createElement('div');
    div.className = classNames.pop();
    if (parentDiv) {
      parentDiv.appendChild(div);
    }
    parentDivs.push(div);
    parentDiv = div;
  }
  
  parentDivs[parentDivs.length-1].appendChild(target.cloneNode(true));
  
  target.parentNode.replaceChild(parentDivs[0], target);
  
  return parentDivs[0];
}

/*
console.info(wrapWithDivs(document.getElementById('HELLO'), [
    'a',
    'b',
    'c',
    'd',
    'e',
    'f'
]));
*/


function hideEditLinks()
{
  $("p.editPost").hide().each(function() { 
      $(this).parent().hover(function() {
          $(this).find('>p.editPost').show()
          /*
          $(this).css('outline','1px solid red').click(function() {
          }); 
          */
          
      }, function() {
          $(this).css('outline','');
          $(this).find('p.editPost').hide();
      });
  });
        
}

function setupEditControls()
{
  if ($("#editControlsWrapper").length > 0)
  {
    
    $("#showHideControls").click(function () {
      $("#editControls").toggle(250);

      if ($("#editControlsWrapper").css("opacity") == 1)
      {
        // fade out
        $("#editControlsWrapper").fadeTo(250, .25);
        $.cookie("hindsShowEditControls", "hide", {expires: 1000, path: '/' }); 
      } else
      {
        // fade in
        $("#editControlsWrapper").fadeTo(250, 1.0);
        $.cookie("hindsShowEditControls", "show", {expires: 1000, path: '/' }); 
      }
      
    });
    
    $("#controlWrappers .hideEditLinks").click(function () {
      $.cookie("hindsShowEditLinks", "hide", {expires: 1000, path: '/' });
      hideEditLinks();
      $("#controlWrappers .showEditLinks").show();
      $("#controlWrappers .hideEditLinks").hide();
      return false;
    });
    
    $("#controlWrappers .showEditLinks").click(function () {
      $.cookie("hindsShowEditLinks", "show", {expires: 1000, path: '/' });
      showEditLinks();
      $("#controlWrappers .showEditLinks").hide();
      $("#controlWrappers .hideEditLinks").show();
      return false;
    });
    
    
    $("#linkHighlightWrappers .showLinkHighlight").click(function () {
      $.cookie("hindsShowHighlightLinks", "show", {expires: 1000, path: '/' });
      showLinkHighlight();
      return false;
    });
    
    $("#linkHighlightWrappers .hideLinkHighlight").click(function () {
      $.cookie("hindsShowHighlightLinks", "hide", {expires: 1000, path: '/' });
      hideLinkHighlight();
      return false;
    });
    
    if ($.cookie("hindsShowEditControls"))
    {
      if ($.cookie("hindsShowEditControls") == "hide")
      {
        hideEditControls();
      }
      
      if ($.cookie("hindsShowEditLinks") == "hide")
      {
        hideEditLinks();
        $("#controlWrappers .showEditLinks").show();
        $("#controlWrappers .hideEditLinks").hide();
      } else
      {
        $("#controlWrappers .showEditLinks").hide();
        $("#controlWrappers .hideEditLinks").show();
      }
      
      if ($.cookie("hindsShowHighlightLinks") == "hide")
      {
        hideLinkHighlight();
      } else
      {
        showLinkHighlight();
      }
      
      
    } else
    {
      hideAllEditControls();
      $.cookie("hindsShowEditLinks", "hide", {expires: 1000, path: '/' });
      $.cookie("hindsShowEditControls", "hide",  {expires: 1000, path: '/' });
      $.cookie("hindsShowHighlightLinks", "hide",  {expires: 1000, path: '/' });
    }
  }
}

function hideAllEditControls()
{
  hideEditLinks();
  hideEditControls();
  hideLinkHighlight();
}

function hideEditLinks()
{
  $("p.editPost").hide();
  $("#controlWrappers .showEditLinks").show();
  $("#controlWrappers .hideEditLinks").hide();
}

function hideLinkHighlight()
{
  $('.content a').each(function() {
    $(this).css("background", null).attr("data-highlight", null);
  });
  
  $("span[data-highlight='true']").each(function() {
    $(this).css("background", null).css("color", null).attr("data-highlight", null);
  });
  
  $("#linkHighlightWrappers .showLinkHighlight").show();
  $("#linkHighlightWrappers .hideLinkHighlight").hide();
}

function showLinkHighlight()
{
    
  $('.content a').each(function() {
    // check to see if it links to same page
    if ($(this).attr("href") == window.location)
    {
      $(this).css("background", "#f69679").attr("data-highlight", "true");
    } else
    {
      $(this).css("background", "#82ca9c").attr("data-highlight", "true");
    }
  });
  
  $("span[style='text-decoration: underline;']").each(function() {
    $(this).css("background", "#ff0000").css("color", "#ffffff").attr("data-highlight", "true");
  });
    
  $("#linkHighlightWrappers .showLinkHighlight").hide();
  $("#linkHighlightWrappers .hideLinkHighlight").show();
}

function showEditLinks()
{
  $("p.editPost").show();
  $("#controlWrappers .showEditLinks").hide();
  $("#controlWrappers .hideEditLinks").show();
}
  
function hideEditControls()
{
  $("#editControls").hide();
  $("#editControlsWrapper").fadeTo(250, 0.25);
  //alert($("#editControlsWrapper").css("opacity"));
}


function sitemapColumns()
{
  if ($("#theSitemap").length > 0)
  {
    var splitIndex = 2;
    var topLevel = $("#theSitemap > li > a").parent();

    for (var i = splitIndex; i < topLevel.length; i++)
    {
      //alert($(topLevel[i]).html());
      $("#sitemap .rightCol").html($("#sitemap .rightCol").html() + "<li>" + $(topLevel[i]).html() + "</li>");
      $(topLevel[i]).remove();
      //alert(i);
    }
    $("#sitemap .rightCol").html("<ul>" + $("#sitemap .rightCol").html() + "</ul>");
    $("#sitemap .leftCol").removeClass("wide");
    $("#sitemap .rightCol").removeClass("narrow");
  }
}


function decorateGlossary()
{
  if (($("body.page-id-736").length > 0) && ($(".glossaryItem").length > 0))
  {
    $(".glossaryItem + br").remove();
    var glossary = $(".glossaryItem");
    var gI = '<table class="glossaryIndex" cellspacing="0" cellpadding="0"><tr>';
    //var gI = "";
    for(var i = 0; i < glossary.length; i++)
    { 
      //alert($(glossary[i]).attr("data-alpha"));
      gI += "<td id=\"glossaryIndex-" + $(glossary[i]).attr("data-alpha") + "\" data-alpha=\"" + $(glossary[i]).attr("data-alpha") + "\"><a data-href=\"#glossary-" + $(glossary[i]).attr("data-alpha") + "\">" + $(glossary[i]).attr("data-alpha") + "</a></td>";
      
    }
    gI += "</tr></table>";
    $(".content h1").after(gI);
    
    $("table.glossaryIndex td").hover(function() {$(this).addClass("highlightHover"); }, function () { $(this).removeClass("highlightHover")});
    $("table.glossaryIndex td").click(function() {
      $("table.glossaryIndex td").removeClass("highlight");
      $(this).addClass("highlight");
      $(".glossaryItem").slideUp("slow");
      $("#glossary-" + $(this).attr("data-alpha") + "-noJump").slideDown("slow", function () {
          window.location.hash = "#glossary-" + $(this).attr("data-alpha");
      });
      
      
    });
    
    if (window.location.hash == "")
    {
      var first = $("table.glossaryIndex td:first");
    } else
    {
      var alpha = window.location.hash.split("-").pop();
      var first = $("table.glossaryIndex td#glossaryIndex-" + alpha);
    }
    
    $("table.glossaryIndex td").removeClass("highlight");
    $(first).addClass("highlight");
    $(".glossaryItem").hide();
    $("#glossary-" + $(first).attr("data-alpha") + "-noJump").slideDown("fast", function () {
        window.location.hash = "#glossary-" + $(first).attr("data-alpha");
    });
    
    //alert("here");
    //alert(gI);
    //var gT = $(gI).wrap(gW);
    //alert(gT.html());
    //alert($(gT).html());
  }
}
