﻿$(document).ready(function () {
    $("body").removeClass("no-js");
    FixSocialWidths();
    LoadPrintStylesheet();
    SetEnterFocus();
    ForceTwitterLinksToOpenInNewWindow();
});

//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";
    });

}

/***
 * 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);


/***********************************************************
    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 });

});



