$(document).ready(function () {
    $("body").removeClass("no-js");
    FixSocialWidths();
    LoadPrintStylesheet();
    SetEnterFocus();
    ForceTwitterLinksToOpenInNewWindow();
	//CreateTabs();
	//openTab(window.location.hash);
	heightAdjust('.smallImageComponent.smallComponent .details');
	heightAdjust('.smallImageComponent.smallComponent');
	
	$(".people-wrapper .callToActionLink").click(function() {
		$(this).toggleClass("less").siblings(".people-more").slideToggle();
		return false;
	});
	
});

//Loads Print Stylesheet after main content has rendered.
function LoadPrintStylesheet() {
    var headID = document.getElementsByTagName("head")[0];
    var cssNode = document.createElement('link');
    cssNode.type = 'text/css';
    cssNode.rel = 'stylesheet';
    cssNode.href = '/css/print.min.css';
    cssNode.media = 'print';
    headID.appendChild(cssNode);
}

//if one component is not used make the other 100% width.
function FixSocialWidths() {
    var twitter = $(".socialControls .twitterFeed");
    var linkedin = $(".socialControls .linkedInFeed");

    if (twitter.length == 0 && linkedin.length == 1) {
        $(linkedin[0]).attr("style", "width:100%");
    }
    else if (twitter.length == 1 && linkedin.length == 0)
    {
        $(twitter[0]).attr("style", "width:100%; float:left");
    }

}

function SetEnterFocus() {
    $('.searchBox').keydown(function (e) {
        if (e.keyCode == 13) {
            $(this).children('input[type=button]')[0].click();
        }
    });
}

function ForceTwitterLinksToOpenInNewWindow() {

    $(".twitterFeed a").live("click", function () {
        this.target = "_blank";
    });

}

function heightAdjust(el) {
    var ph = 0;
    var t = $(el)
    t.each(function () {
        var h = $(this).height();
        h > ph ? ph = h : ph = ph;
    });
    t.css("height", ph);
}

function openTab(h) {
	$(h).show().siblings().hide();
	$(".subNav ul li a[href*="+h+"]").parent().addClass("active").siblings().removeClass("active");
}

function CreateTabs() {
	
	$(window).bind("hashchange", function(){
		openTab(window.location.hash);
		return false;
	});
	

//	$(".subNav ul li a").click(function(){
//		var link = $(this);
//		var tab;
//		if (link.attr("href").split("#").length > 1) { 
//			tab = link.attr("href").split("#")[1];
//			link.parent().addClass("active").siblings().removeClass("active");
//			$("#"+tab).show().siblings().hide();
//			return false;
//		} else { 
//			return; 
//		}
//	});
}


/***
 * jQuery.matchColumns - make bottoms of column match 
 * four object parameters at the moment
 * children : (optional, string) children are the nodes within the container that the height is to be added to
 * position : (optional, string - default bottom) position is where you where you want the extra height to be added
 * restart :  (optional, integer) if you want to reset the height at the start of each row, give the column number
 * style :    (optional,string [padding,margin] ) which style attribute the height is to be added to
 * imageWait : (optional, boolean) Waits until all of the images in the columns are loaded before performing the function */

(function(jQuery) {
    jQuery.fn.matchColumns = function( obj ){

    if( !obj ) obj = {};

    if( !this.length ) return;
    
    var columns = this;
      
    var children = obj.children || null;
    var position = obj.position || "bottom";
    var restart = obj.restart || null;
    var style = obj.style || "margin";

    function setColumns()
    {
        var lowest = 0;
        var lowList = [];
        columns.each(
            function(i) 
            {
                if( restart && i % restart == 0 )
                {
                    lowList[lowList.length] = 0;lowest =0;
//                    if( jQuery.browser.msie ) // if rows are floated and not cleared there are problems in IE. Don't know which browser is rendering correctly but assume it is not IE. This is only a problem if the bottom is being found, not the height.
//                    {
                        jQuery(this).before('<div class="REMOVED_AFTER_FOUND_BOTTOM" style="clear:both;font-size:0;height:0;width:100%;"/>');
//                    }
                }
                
                var bottom = jQuery(this).offset().top + this.offsetHeight;
                this.currentBottom = bottom;
                if (bottom>lowest) {lowest = bottom;}
                if( restart ) {lowList[lowList.length-1] = lowest;}
            })
        .css("height", "auto")
        .siblings(".REMOVED_AFTER_FOUND_BOTTOM").remove().end()
        .each(
          function(i)
          {
            if( lowList.length )
            {
                lowest = lowList[ Math.ceil((i+1)/(restart))-1 ];
            }
            var el = this;
            var diff = lowest-this.currentBottom;
            var endHeight = this.offsetHeight + diff;
            if(diff > 0)
            {
              if (children)
              {
                var tries = 0;
                jQuery(el).find( children ).each( function() {
                    while( el.offsetHeight < endHeight && tries < 6 ) // if it can't get it in 4 tries then something if wrong
                    {
                        var exist = jQuery(this).css( style + "-" + position ).replace(/px/,"") * 1;
                        if( isNaN(exist) ) exist = 0;
                        jQuery(this).css( style + "-" + position , endHeight - el.offsetHeight + exist);
                        tries++;
                    }
                });
              } 
              else 
              {
                jQuery(this).css("padding-" + position , diff + jQuery(this).css("padding-" + position ).replace("px","")*1);
              }
            }
          }  
        );
    }; // end function setColumns
    
    if( obj.imageWait )
    {
        var totalToLoad = 0;
        
        function finishedLoad()
        {
            totalToLoad--;
            if( !totalToLoad ) setColumns();
        }
        
        columns.find("img").each( function(i) {
            if( !this.complete ) 
            {
                // IE doesn't return complete for failed images so check to see if it currently loading
                if( jQuery.browser.msie && this.readyState != "loading" ) return;
                totalToLoad++;
                this.onload = finishedLoad;
            }
        });
        if( !totalToLoad ) setColumns();
    }
    else
    {
        setColumns();
    }
    
  }
})(jQuery);

/*
 * jQuery hashchange event - v1.3 - 7/21/2010
 * http://benalman.com/projects/jquery-hashchange-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,e,b){var c="hashchange",h=document,f,g=$.event.special,i=h.documentMode,d="on"+c in e&&(i===b||i>7);function a(j){j=j||location.href;return"#"+j.replace(/^[^#]*#?(.*)$/,"$1")}$.fn[c]=function(j){return j?this.bind(c,j):this.trigger(c)};$.fn[c].delay=50;g[c]=$.extend(g[c],{setup:function(){if(d){return false}$(f.start)},teardown:function(){if(d){return false}$(f.stop)}});f=(function(){var j={},p,m=a(),k=function(q){return q},l=k,o=k;j.start=function(){p||n()};j.stop=function(){p&&clearTimeout(p);p=b};function n(){var r=a(),q=o(m);if(r!==m){l(m=r,q);$(e).trigger(c)}else{if(q!==m){location.href=location.href.replace(/#.*/,"")+q}}p=setTimeout(n,$.fn[c].delay)}$.browser.msie&&!d&&(function(){var q,r;j.start=function(){if(!q){r=$.fn[c].src;r=r&&r+a();q=$('<iframe tabindex="-1" title="empty"/>').hide().one("load",function(){r||l(a());n()}).attr("src",r||"javascript:0").insertAfter("body")[0].contentWindow;h.onpropertychange=function(){try{if(event.propertyName==="title"){q.document.title=h.title}}catch(s){}}}};j.stop=k;o=function(){return a(q.location.href)};l=function(v,s){var u=q.document,t=$.fn[c].domain;if(v!==s){u.title=h.title;u.open();t&&u.write('<script>document.domain="'+t+'"<\/script>');u.close();q.location.hash=v}}})();return j})()})(jQuery,this);

/***********************************************************
    the rest of the items happen after the dom has finshed loading
    ***********************************************************/
$(function () {
    /* equalize the columns on the three column boxes (collections and home page)
    uses matchColumns plugin for jQuery */
    //$(".main  .smallImageComponent").matchColumns({ children: ".details", position: "bottom", restart: 2, imageWait: true });
    $(".secondaryArticles .article .content").matchColumns({ children: ".excerpt", position: "bottom", imageWait: true });
    $(".secondary .publication").matchColumns({ children: ".readMore", position: "top",  imageWait: true });

});



