$(document).ready(function(){
	initPopups();
	scrollBar();
	initPage();
	initTabs();
	showMore();
	trueFalse();
	
	$('a[href^="http://"], a[href^="/developing-champions/videos/"]').attr("target", "_blank");
	
	
	//	FACEBOOK POPUPS
	
	$('.facebook-box, .share-link').each(function () {
		// options
	    var distance = 25;
	    var time = 250;
	    var hideDelay = 500;

	    var hideDelayTimer = null;

	    // tracker
	    var beingShown = false;
	    var shown = false;

	    var trigger = $('.facebook', this);
	    var popup = $('.popup', this).css('opacity', 0);
	
		var likeURL = $(this).find("a.facebook").attr("href");
	
	    // set the mouseover and mouseout on both element
	    $([trigger.get(0), popup.get(0)]).mouseover(function () {
		
			if($(this).hasClass('learn-more'))  {
				leftPos = 42;
			} else {
				leftPos = -9;
			}
	
			var iframeSrc = 'http://www.facebook.com/plugins/like.php?href='+likeURL+'&amp;layout=button_count&amp;show_faces=false&amp;width=80&amp;action=like&amp;font=trebuchet+ms&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:80px; height:21px;" allowTransparency="true" '
			var iFrame = '<iframe src="' + iframeSrc + '></iframe>'
			
	      // stops the hide event if we move from the trigger to the popup element
	      if (hideDelayTimer) clearTimeout(hideDelayTimer);

	      // don't trigger the animation again if we're being shown, or already visible
	      if (beingShown || shown) {
	        return;
	      } else {
	        beingShown = true;

			
	        // reset position of popup box
	        popup.css({
	          bottom: 11,
	          left:leftPos,
	          display: 'block' // brings the popup back in to view
	        })

	        // (we're using chaining on the popup) now animate it's opacity and position
	        .animate({
	          top: '-=' + distance + 'px',
	          opacity: 1
	        }, time, 'swing', function() {
	          // once the animation is complete, set the tracker variables
	          beingShown = false;
	          shown = true;
				$(this).find('.like').html(iFrame);
	
	        });
	      }
	    }).mouseout(function () {
	      // reset the timer if we get fired again - avoids double animations
	      if (hideDelayTimer) clearTimeout(hideDelayTimer);

	      // store the timer so that it can be cleared in the mouseover if required
	      hideDelayTimer = setTimeout(function () {
			hideDelayTimer = null;
	        popup.animate({
	         // top: '-=' + distance + 'px',
	          opacity: 0
	        }, time, 'swing', function () {
	          // once the animate is complete, set the tracker variables
	          shown = false;
	          // hide the popup entirely after the effect (opacity alone doesn't do the job)
	            popup.css('display', 'none');
				popup.css('top', '-60px');
				$(this).children('.like iframe').detach('iframe');
				
	        });
	      }, hideDelay);
	    });
	  });

	//  HOMEPAGE SLIDESHOW
	
	if($('#slideParent').length >= 1){
		$('#slideshow').cycle({
			speed:  'fast', 
		    timeout: 0, 
		    next:   '#next', 
		    prev:   '#prev'
		});
		
		if($('#slideParent .slide').length <= 1) {
			$('#slideParent .buttons').hide();
		}
		
		function onAfter(curr,next,opts) {
			var currBG = $("#pics a").eq(opts.currSlide).attr('rel').split(",");
			var bgimg;

			if(currBG[1]){
				bgimg = "#" + currBG[0] + " url(" + currBG[1] + ") center top no-repeat";
			} else {
				bgimg = "#" + currBG[0];
			}

			$('.education').css('background', bgimg);
			$("#pics a").eq(opts.currSlide).css('background-color', "transparent");
		}
		
		$('#pics').cycle({
			activePagerClass: 'active', 
			speed: 'fast',
			timeout: 0,
			pager : '.swicher',
			pagerAnchorBuilder: function(idx, slide) { 
		        return '.swicher li:eq(' + idx + ') a'; 
		    },
			after: onAfter
		});
	}
	
	// SPLIT COL TEXT
	
	if($('.mini_verse div > p').length >= 1){
		$('.mini_verse div > p').widtherize({'width': 393});
	}
	
	// SURFACES GALLERY - HOMEPAGE
	
	if($('.surfaces-gallery ul li a').length >=1){
		$('.surfaces-gallery ul li a').fancybox({
			'centerOnScroll': true
		});
	}
	
	// COLUMNIZE TEXTS
	
	if($(".surfaceHolder").length >= 1){
		$('#splitColumns').columnize({ columns: 2 });
	}
	
	if($('.block').length >= 1){
		$('.block').columnize({ columns: 2 });
	}
	
	// PRIMARY NAV SUBNAV HOVER THINGY
	
	if($("#subnav").hasClass("active")){
		function makeActive(){ $("#subnav").fadeOut();}
		function makeInactive(){ $("#subnav").fadeIn();}
		var config = {
			over: makeActive,
			timeout: 300,
			out: makeInactive
		}
		$("#nav").hoverIntent(config)
	}
	
	// YOUTUBE THUMBNAIL GENERATOR
	
	if($(".image-holder a.thumb").length >= 1){
		$(".image-holder a.thumb").each(function(i){
			var thisURL = $(this).attr('href');
			$(this).append('<img src="'+$.jYoutube(thisURL, "small")+'" alt = "" />');
		});
	}
	
	// Replace pagination
	
	if($("#pressPagination").length >= 1){
		var pager = $("#pressPagination").hide().clone().insertAfter($("#main .search-form")).show();
	}
	

			
});
// END DOCREADY

// SHOWMORE ON DRILL PAGES

function showMore()
{
	$(".toggleClose .more").click(function(){
		$(".chempions, .slide-box").toggleClass("toggleOpen", 300);
			return false
		});
}

// TRU-FALSE

function trueFalse()
{
	if($('.choice-list')){
		$(".choice-list a").click(function(){
			var parentElem = $(this).closest("div.true-false")
			var answer = $(this).parent().attr("class");
			var corrAns = $(this).closest("ul").attr("class").split(" ");
			if(answer === corrAns[1]){
				parentElem.addClass("corect-box");
				parentElem.find('.answerContainer img:nth-child(1n)').show();
				parentElem.find('.answerContainer img:nth-child(2n)').hide();
			} else {
				parentElem.addClass("incorect-box");
				parentElem.find('.answerContainer img:nth-child(1n)').hide();
				parentElem.find('.answerContainer img:nth-child(2n)').show();
			}
			parentElem.find('.choiceContainer').hide();
			parentElem.find('.answerContainer').show();
			return false;
		})
	}
}


// FIXED SCROLL - HP ONLY

function scrollBar(){
	var bar = $('.bar');
	var fixedClass = 'fixed-bar';
	var barTop = bar.offset().top - 38;
	
	if($('.notfixed-bar').length >= 1) return false;
	
	if ($(this).scrollTop() >= barTop) bar.addClass(fixedClass);
	if ($(this).scrollTop() < barTop) bar.removeClass(fixedClass);
	$(window).scroll(function(){
		if ($(this).scrollTop() >= barTop) {
			bar.addClass(fixedClass) 
			$("#gradWrapper").fadeIn('fast');
		};
		if ($(this).scrollTop() < barTop) {
			bar.removeClass(fixedClass);
			$("#gradWrapper").fadeOut('fast');
		} 
	});
}

// POPUP AND PRIM NAV FUNCTIONS

function initPopups()
{
	initPopup({
		openEvent:'click'
	});
	initPopup({
		popupHolderClass:'popup-hover',
		linkTag:'li'
	});
}
if (window.addEventListener)
	window.addEventListener("load", initPopups, false);
else if (window.attachEvent)
	window.attachEvent("onload", initPopups);
	
function initPopup(_popup) {
	if (!_popup.popupHolderTag) _popup.popupHolderTag = 'div';
	if (!_popup.popupTag) _popup.popupTag = 'div';
	if (!_popup.popupHolderClass) _popup.popupHolderClass = 'popup-holder';
	if (!_popup.popupClass) _popup.popupClass = 'popup';
	if (!_popup.linkOpenClass) _popup.linkOpenClass = 'open';
	if (!_popup.linkTag) _popup.linkTag = 'li';
	if (!_popup.linkCloseClass) _popup.linkCloseClass = 'close';
	if (!_popup.openClass) _popup.openClass = 'active';
	if (!_popup.openEvent) _popup.openEvent = 'hover';
	
	var timer = [];	
	var _popupHolderTag = document.getElementsByTagName(_popup.popupHolderTag);
	if (_popupHolderTag) {
		for (var i=0; i<_popupHolderTag.length; i++) {
			if (_popupHolderTag[i].className.indexOf(_popup.popupHolderClass) != -1) {
				var _popupLink = _popupHolderTag[i].getElementsByTagName(_popup.linkTag);
				for (var j=0; j<_popupLink.length; j++) {
					_popupLink[j].parent = _popupHolderTag[i];
					if (_popupLink[j].className.indexOf(_popup.linkOpenClass) != -1) {
						if (_popup.openEvent == 'click') {
							_popupLink[j].onclick = function(){
								if (this.parent.className.indexOf(_popup.openClass) != -1) {
									this.parent.className = this.parent.className.replace(_popup.openClass,'');
								} else {
									this.parent.className += ' '+_popup.openClass;
								}
								return false;
							}
						} else {
							var _popupTag = _popupHolderTag[i].getElementsByTagName(_popup.popupTag);
							for (var k=0; k<_popupTag.length; k++) {
								if (_popupTag[k].className.indexOf(_popup.popupClass) != -1) {
									_popupTag[k].parent = _popupHolderTag[i];
									_popupTag[k].onmouseover = function(){
										if (timer[j]) clearTimeout(timer[j]);
										if (this.parent.className.indexOf(_popup.openClass) == -1) {
											this.parent.className += ' '+_popup.openClass;
										}
									}
									_popupTag[k].onmouseout = function(){
										var _this = this;
										timer[j] = setTimeout(function(){
											_this.parent.className = _this.parent.className.replace(_popup.openClass,'');
										},2);
									}	
								}
							}
							_popupLink[j].onmouseover = function(){
								if (timer[j]) clearTimeout(timer[j]);
								if (this.parent.className.indexOf(_popup.openClass) == -1) {
									this.parent.className += ' '+_popup.openClass;
								}
							}
							_popupLink[j].onmouseout = function(){
								var _this = this;
								timer[j] = setTimeout(function(){
									_this.parent.className = _this.parent.className.replace(_popup.openClass,'');
								},2);
							}
						}
					} else if (_popupLink[j].className.indexOf(_popup.linkCloseClass) != -1) {
						_popupLink[j].onclick = function(){
							if (this.parent.className.indexOf(_popup.openClass) != -1) {
								this.parent.className = this.parent.className.replace(_popup.openClass,'');
							} else {
								this.parent.className += ' '+_popup.openClass;
							}
							return false;
						}
					}
				}
			}		
		}
	}
}

// CLEAR FORM FIELDS ON PAGE LOAD

function initPage()
{
	clearFormFields({
		clearInputs: true,
		clearTextareas: true,
		passwordFieldText: true,
		addClassFocus: "focus",
		filterClass: "default"
	});
}

function clearFormFields(o)
{
	if (o.clearInputs == null) o.clearInputs = true;
	if (o.clearTextareas == null) o.clearTextareas = true;
	if (o.passwordFieldText == null) o.passwordFieldText = false;
	if (o.addClassFocus == null) o.addClassFocus = false;
	if (!o.filterClass) o.filterClass = "default";
	if(o.clearInputs) {
		var inputs = document.getElementsByTagName("input");
		for (var i = 0; i < inputs.length; i++ ) {
			if((inputs[i].type == "text" || inputs[i].type == "password") && inputs[i].className.indexOf(o.filterClass)) {
				inputs[i].valueHtml = inputs[i].value;
				inputs[i].onfocus = function ()	{
					if(this.valueHtml == this.value) this.value = "";
					if(this.fake) {
						inputsSwap(this, this.previousSibling);
						this.previousSibling.focus();
					}
					if(o.addClassFocus && !this.fake) {
						this.className += " " + o.addClassFocus;
						this.parentNode.className += " parent-" + o.addClassFocus;
					}
				}
				inputs[i].onblur = function () {
					if(this.value == "") {
						this.value = this.valueHtml;
						if(o.passwordFieldText && this.type == "password") inputsSwap(this, this.nextSibling);
					}
					if(o.addClassFocus) {
						this.className = this.className.replace(o.addClassFocus, "");
						this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
					}
				}
				if(o.passwordFieldText && inputs[i].type == "password") {
					var fakeInput = document.createElement("input");
					fakeInput.type = "text";
					fakeInput.value = inputs[i].value;
					fakeInput.className = inputs[i].className;
					fakeInput.fake = true;
					inputs[i].parentNode.insertBefore(fakeInput, inputs[i].nextSibling);
					inputsSwap(inputs[i], null);
				}
			}
		}
	}
	if(o.clearTextareas) {
		var textareas = document.getElementsByTagName("textarea");
		for(var i=0; i<textareas.length; i++) {
			if(textareas[i].className.indexOf(o.filterClass)) {
				textareas[i].valueHtml = textareas[i].value;
				textareas[i].onfocus = function() {
					if(this.value == this.valueHtml) this.value = "";
					if(o.addClassFocus) {
						this.className += " " + o.addClassFocus;
						this.parentNode.className += " parent-" + o.addClassFocus;
					}
				}
				textareas[i].onblur = function() {
					if(this.value == "") this.value = this.valueHtml;
					if(o.addClassFocus) {
						this.className = this.className.replace(o.addClassFocus, "");
						this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
					}
				}
			}
		}
	}
	function inputsSwap(el, el2) {
		if(el) el.style.display = "none";
		if(el2) el2.style.display = "inline";
	}
}
if (window.addEventListener)
	window.addEventListener("load", initPage, false);
else if (window.attachEvent)
	window.attachEvent("onload", initPage);

// TABS
	
function initTabs()
{
	var sets = document.getElementsByTagName("ul");
	for (var i = 0; i < sets.length; i++)
	{
		if (sets[i].className.indexOf("tabset") != -1)
		{
			var tabs = [];
			var links = sets[i].getElementsByTagName("a");
			for (var j = 0; j < links.length; j++)
			{
				if (links[j].className.indexOf("tab") != -1)
				{
					tabs.push(links[j]);
					links[j].tabs = tabs;
					var c = document.getElementById(links[j].href.substr(links[j].href.indexOf("#") + 1));

					//reset all tabs on start
					if (c) if (links[j].className.indexOf("active") != -1) c.style.display = "block";
					else c.style.display = "none";

					links[j].onclick = function ()
					{
						var c = document.getElementById(this.href.substr(this.href.indexOf("#") + 1));
						if (c)
						{
							//reset all tabs before change
							for (var i = 0; i < this.tabs.length; i++)
							{
								var tab = document.getElementById(this.tabs[i].href.substr(this.tabs[i].href.indexOf("#") + 1));
								if (tab)
								{
									tab.style.display = "none";
								}
								this.tabs[i].className = this.tabs[i].className.replace("active", "");
							}
							this.className += " active";
							c.style.display = "block";
							return false;
						}
					}
				}
			}
		}
	}
}

if (window.addEventListener)
	window.addEventListener("load", initTabs, false);
else if (window.attachEvent && !window.opera)
	window.attachEvent("onload", initTabs);


//TRU-FALSE TEXT RESIZER

function resizer() {
    this.resize = function(element, size) {
        this.init(element);
        element.css('font-size', this.growTo(size) + 'px');
        this.tester.remove();
    }

    this.init = function(element) {
        $('#resizeroo').remove();
        this.tester = element.clone();
        this.tester.css('display', 'none');
        this.tester.css('position', 'absolute');
        this.tester.css('height', 'auto');
        this.tester.css('width', 'auto');
        $('body').append(this.tester);
        this.size = 1;
        this.tester.css('font-size', this.size + 'px');
    }

    this.emitWidth = function() {
        //console.log(this.tester.width());
    }


    this.grow = function() {
        this.size++;
        this.setSize();
    }

    this.setSize = function(size) {
        this.size = size;
        this.tester.css('font-size', this.size + 'px');
    }

    this.growTo = function(limit) {
        lower = 1;
        upper = limit-1;

        // do binary search going midway to determine 
        // the best size
        while( lower < upper ) {
            midpoint = Math.ceil((upper+lower)/2);
            this.setSize(midpoint);

            if( Math.abs(limit - this.tester.width()) <= 1) {
                // close enough
                break
            }

            if(this.tester.width() >= limit) {
                upper = this.size-1;
            }
            else {
                lower = this.size+1;
            }       
        }

        while(this.tester.width() > limit) {
            this.setSize(this.size-1);
        }

        return(this.size);

    }
}

function popup(url, width, height) 
{
	 var left   = (screen.width  - width)/2;
	 var top    = (screen.height - height)/2;
	 var params = 'width='+width+', height='+height;
	 params += ', top='+top+', left='+left;
	 params += ', directories=no';
	 params += ', location=no';
	 params += ', menubar=no';
	 params += ', resizable=no';
	 params += ', scrollbars=no';
	 params += ', status=no';
	 params += ', toolbar=no';
	 newwin=window.open(url,'windowname5', params);
	 if (window.focus) {newwin.focus()}
	 return false;
}
(function( $ ){
  $.fn.widtherize = function( options ) {  
      return this.each(function() {       
          var settings = {
              'width' : 500
          };      
          if ( options ) { 
              $.extend( settings, options );
          }
          r = new resizer();
          r.resize($(this), settings.width);
      });
  };
})( jQuery );
