/**
* ieVersion is set to the return result
* of and annonymous function that detects
* if browser ie and which version.
* Thus, to detect IE:
*  if (ieVersion) {}
* And to detect the version:
* ieVersion === 6 // IE6
* ieVersion > 7 // IE8, IE9 ...
* ieVersion < 9 // Anything less than IE9
*/
var ieVersion = (function(){
	var undef,
		v = 3,
		div = document.createElement('div'),
		all = div.getElementsByTagName('i');

	while (
		div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
		all[0]
	);

	return v > 4 ? v : undef;

}());



/**
* For easing
*/

jQuery.easing.easeInOutQuad = function (x, t, b, c, d) {
	if ((t/=d/2) < 1) return c/2*t*t + b;
	return -c/2 * ((--t)*(t-2) - 1) + b;
};





/**
* A patch for the HTML 5 Placeholder attribute found
* in the search input
*/
function testPlaceholder() {
     var i = document.createElement('input');
     return 'placeholder' in i;
}


function insertPlaceholder(el) {
     var hasPlaceholder = testPlaceholder();
     if (hasPlaceholder) {
          return;
     } else {
          $(el).each(function() {
               var helpTxt = $(this).attr("placeholder");
   
               $(this).val(helpTxt);
   
               $(this).blur(function () {
                    if($(this).val() == '') { $(this).val(helpTxt) }
               });
               $(this).focus(function() {
                    if($(this).val() == helpTxt) { $(this).val("") }
               });
          });
     }
}




/**
* Setting up the Billboard scroll 
* that is found on the homepage.
*/
	
function BillboardScroll() {
	if($('#billboard-slides').length) {
	if (ieVersion < 9 ) {
		this.displayFx = 'none'
	} else {
		this.displayFx = 'fade'
	}
	this.carousel = $('#billboard-slides'),
	this.slideCount = $('#billboard-slides > li').length,
	this.addControls = function() {
		$('<div id="pager" class="clearfix" aria-controls="carousel role="toolbar" role="button"></div>').appendTo($('#billboard'));
	},
	this.cycleBillboard = function() {
		var displayFx = this.displayFx;
		this.carousel.cycle({
	        	fx:     displayFx, 
	    		speed:  'slow', 
	    		timeout: 6000,
	    		
	    		pager: '#pager'
	    	}) 
	},
	this.cycleControls = function(){
		$('#pager a').attr('role','button').attr('aria-controls','carousel').each(function(index){
        	$(this).text($(this).text()).attr('title', $(this).text()).attr('tabindex',index+1);
        });
    	$('#options a').click(function(){
        	$('#features > ul').cycle('pause');
    	});
    },
	this.init = function() {
		if($('#billboard-slides').length) {
			this.addControls();
			this.cycleBillboard();
			this.cycleControls();
		}
	},
	this.init();
	}
}



/**
* Setting up the Tabbed navigation.
Please use this structure to set up tabs:
     <div class='tabbed'>
          <div class='content-piece'>
               <h2 class='tab'>Tab Title<h2>
               Content
          </div>
          <div class='content-piece'>
               <h2 class='tab'>Tab Title<h2>
               Content
          </div>
          <div class='content-piece'>
               <h2 class='tab'>Tab Title<h2>
               Content
          </div>
     </div>
Any title element can be used as long as it has a 'tab' class.
*/
function TabbedNav(id) {
     this.tabContent = $(id),

     this.hideBuild =  function(){
          this.tabContent.addClass('visuallyhidden');
     },
     this.buildTabsContainer = function(){
          this.tabContent.prepend('<ul class="tabs clearfix"></ul>');
     },
     this.buildTabs = function(){
     	$tabContent1 = this.tabContent;
     	$tabContent1.children('.content-piece').each(function(index){
		if (index !== 0) {
		   $(this).addClass('visuallyhidden');    
		}
		var $tabTitle = $(this).children('.tab');
		var tabId = 'tab-'+ (index + 1);
		var tabText = $tabTitle.text();
		$tabTitle.addClass('visuallyhidden');
		$tabContent1.children('.tabs').append('<li><a id="' + tabId + '" href="#">' + tabText + '</a></li>');
		$tabContent1.children('.tabs').find('#tab-1').parent().addClass('active');
		});
     },
     this.tabFunctionality = function(){
     	$tabContent2 = this.tabContent;
		$tabContent2.children('.tabs').find('a').click(function(event){
			event.preventDefault();
			var $this = $(this);
			$this.parent().siblings().removeClass('active').end().addClass('active');
			var id = $this.attr("id");
			var index = id.split('-').pop();
			$tabContent2.children('.content-piece').addClass('visuallyhidden');
			$tabContent2.children('#content-' + index).removeClass('visuallyhidden');
		})
 
     },
     this.showBuild =  function(){
          this.tabContent.removeClass('visuallyhidden');
     },
     this.init = function(){
          if($('.tabbed .content-piece').length) {
               this.hideBuild();
               this.buildTabsContainer();
               this.buildTabs();
               this.tabFunctionality();
               this.showBuild();
          }
     }
     this.init();
}

/**
* Aplhabetical tabs - similar to the precending function
*/

function AlphaDisplay() {
     this.alphaDisplay = $('.alpha-display'),

     this.hideAlphaDisplay =  function(){
          this.alphaDisplay.addClass('visuallyhidden');
     },
     this.buildAlphaDisplay = function(){
          this.alphaDisplay.prepend('<ul class="alpha-display-controls clearfix"></ul>');
     },
     this.buildAlphaDisplayControls = function(){
     	$alphaDisplay = this.alphaDisplay;
     	$alphaDisplay.children('.alpha-content-piece').each(function(index){
			if (index !== 0) {
		   		$(this).addClass('visuallyhidden');    
			}
			var alphaContentId = 'alpa-content-'+ (index + 1);
			var titleId = 'alpa-contol-'+ (index + 1);
			var $title = $(this).children('.alpha-title');
			var titleText = $title.text();
			$(this).attr('id', alphaContentId )
			$title.attr('id', titleId );
			$title .addClass('visuallyhidden');
			$('.alpha-display-controls').append('<li><a id="' + titleId + '" href="#">' + titleText + '</a></li>');
			$('.alpha-display-controls').find('#alpa-contol-1').parent().addClass('active');
		});
     },
     this.alphaDisplayFunctionality = function(){
     	$alphaDisplay = this.alphaDisplay;
		$alphaDisplay.children('.alpha-display-controls').find('a').click(function(event){
			event.preventDefault();
			var $this = $(this);
			var id = $this.attr("id");
			var index = id.split('-').pop();
			$this.parent().siblings().removeClass('active').end().addClass('active');
			$('.alpha-content-piece').addClass('visuallyhidden');
			$('#alpa-content-' + index).removeClass('visuallyhidden');
		})
 
     },
     this.showAlphaDisplay =  function(){
          this.alphaDisplay.removeClass('visuallyhidden');
     },
     this.init = function(){
          if($('.tabbed .content-piece').length) {
               this.hideAlphaDisplay();
               this.buildAlphaDisplay();
               this.buildAlphaDisplayControls();
               this.alphaDisplayFunctionality();
               this.showAlphaDisplay();
          }
     }
     this.init();
}



/*This jquery plug-in allows a list - see gallery page - to have it rows wrapped in a div, so that layout is maintained even with variable height list items.*/

/* jQuery split a list into multiple rows or columns
* version 3.0 (02/10/2010)
* developed by David Zhou, Matt Billings, David Durst, and Chuck Harmston
* take an unordered list and split it into multiple divs.
* you can float the divs so it looks like multiple columns/lists.
* 
* usage: 
*    $(".dropdown ul").splitList(3);
*    $(".dropdown ul").splitList(3, { wrapClass: "div_class_name" });
*    $(".dropdown ul").splitList(3, { splitInto: "div_class_name" });
* 
* If option splitInto is set to 'cols' (as it is by default), it will
* split into the specified number of columns. Otherwise, it will split
* into rows, with the specified number of <li>s per row.
* 
*/

$.fn.splitList = function(n, options){
	settings = $.extend({
		wrapClass: false,
		splitInto: 'cols'
	}, options);
	return this.each(function(){
		var intoCols = (settings['splitInto'] == 'cols');
		$lis = jQuery(this).find("> li");		
		$inc = intoCols ? parseInt(($lis.length/n) + ($lis.length % n > 0 )) : n;
		var w = '<div' + (settings['wrapClass'] ? ' class="' + settings['wrapClass'] + '"' : '' ) + '></div>';
		for(var i=0; i<(intoCols ? n : Math.ceil($lis.length/n)); i++)
			$lis.slice($inc*i, $inc*(i+1)).wrapAll(w);
	});
};



/**
* Article image scroller
*/
function articleImagePager() {
	if( $('#article-images').find('li').length > 1 ){
		$('#article-images ul')
			.addClass('multiple')
			.before( '<a class="prev ir" href="#">Previous</a> <a class="next ir" href="#">Next</a>' )
			.cycle({ 
				fx: 'scrollHorz', 
				speed: 200, 
				timeout: 0, 
				next: '#article-images .next', 
				prev: '#article-images .prev'
				
		});
	}
};



/**
* Refine search toggle
*/
function refineFieldsToggle() {
	var $refineFields = $('.sortby');
	$refineFields.addClass('refine-hidden');
	$('#sort h3').after('<a id="refine-toggle" class="ir" href="#">Reveal form selects</a>');
	$('#refine-toggle').toggle(function(event) {
		$refineFields.removeClass('refine-hidden');	
	}, function() {
		$refineFields.addClass('refine-hidden');
	});
};



/**
* Job Search toggle
*/
function searchJobsToggle() {
	var $jobSearch = $('.search-list');
	$jobSearch.addClass('closed');
	$jobSearch.find('h3').wrapInner('<a href="#" />').toggle(function() {
		$(this).parent().removeClass('closed');
	}, function() {
		$(this).parent().addClass('closed');		
	});
};


/**
* If 2 divs in the .two-col div it will lay them out as two columns. 
*/

function twoColList() {
	if ($('.two-col>div').length == 2) {
		$('.two-col>div').addClass('col-item').filter(':even').addClass('left-col-item');
	}
}

/**
* Simple function that adds the double right
* brackets to the links with the .more class
* A condition uses the ieVersion object to test
* and only run function if ie6 and ie7 return
* true.
*/
function rightBrackets(element){
     if(ieVersion < 8){
          $(element).each(function(){
               var $this = $(this);
               $this.html($this.text() + '&nbsp;&raquo;');
          });
     }    
}

function singleRightBrackets(element){
     if(ieVersion < 8){
          $(element).each(function(){
               var $this = $(this);
               $this.html($this.text() + '&nbsp;&gt;');
          });
     }    
}

function leftBrackets(element){
     if(ieVersion < 8){
		$(element).each(function(){
			var $this = $(this);
			$this.html('&laquo;&nbsp;' + $this.text());
		});
     }    
}




/**
* IE6, IE7, IE8 Patches for first of type and last child selector
*/
function ieSixSevenEightEnhance() {
	if(ieVersion < 9){
		$(".columns-list ul:first").addClass("first-of-type");
		$(".results-list li:last-child").addClass("last-child");
		$(".btn-rounded").wrapInner('<span />');
	}
}



/**
* IE6 Patches for first-child selector
*/
function ieSixEnhance() {
	if(ieVersion === 6){	
		$( "#header-nav #nav li:first-child").addClass("first-child");
		$( "#header-nav #nav li.open li ul li:first-child").addClass("first-child");
		$( ".image-list .columns .row:first-child").addClass("first-child");
		$( ".image-list .columns .row li:first-child").addClass("first-child");
		$( ".row-list li:first-child").addClass("first-child");
		$( ".mag-action-boxes li:first-child").addClass("first-child");
		$( ".event-callout li:first-child").addClass("first-child");
		$( ".pagination li:first-child").addClass("first-child");
		$( "form fieldset:first-child").addClass("first-child");
		$( "form input:checkbox").addClass("checkbox");
	}
}



/**
* jQuery on-dom load that loads various functions and
* creates new objects from constructors.
*/
 
$(document).ready(function() {
	var billboard = new BillboardScroll();
	var tabbedNav = new TabbedNav('.tabbed');
	var alphaDisplay = new AlphaDisplay();
	
	$("ul.columns").splitList(2, {
	  'splitInto': 'rows'
	}).children('div').addClass('clearfix row');
	
	rightBrackets('.more-content');
	rightBrackets('#header-nav #nav li li a');
	rightBrackets('.alpha-content-piece li a');
	rightBrackets('.mag-action-boxes li h2 a');
	rightBrackets('.article-source a');
	rightBrackets('.pagination-next');
	rightBrackets('.sub-related-list li a');
	rightBrackets('.ruled-list li a');
	rightBrackets('#footer-utility a');
	
	singleRightBrackets('.btn-rounded');
	singleRightBrackets('#billboard .content a');
	
	leftBrackets('.breadcrumb a');
	leftBrackets('.pagination-previous');
	
	insertPlaceholder('#scoop-signup-input');
	insertPlaceholder('#site-search-input');
	
	articleImagePager();
	refineFieldsToggle();
	searchJobsToggle();
	twoColList();
	
	ieSixSevenEightEnhance();
	ieSixEnhance();
}); 

