// JavaScript Document that handles all main scripts (and jQuery) for main www.tpt.org site


$(document).ready(function() {
						   
	// This is for the fixed top-nav bar
	refreshTopNavCurrentShow();

						   
	// This is for the slider beneath the top nav
	$('#coda-slider-1').codaSlider({
		crossLinking: false,
		autoSlide: true,
		autoSlideHoverPause: true,
		autoSlideInterval: 15000,
		autoSlideStopWhenClicked: true,
		dynamicArrows: false,
		dynamicTabs: true,
		dynamicTabsPosition: "bottom",
		panelTitleSelector: "p.count"
	});	

	
	// These functions are for the drop-down mega menus
	function megaHoverOver(){
		$(this).find(".sub").stop().fadeTo('fast', 1).show();
			
		// Calculate width of all ul's
		(function($) { 
			jQuery.fn.calcSubWidth = function() {
				rowWidth = 0;
				// Calculate row
				$(this).find("ul").each(function() {					
					rowWidth += $(this).width(); 
				});	
			};
		})(jQuery); 
		
		if ( $(this).find(".row").length > 0 ) { //If row exists...
			var biggestRow = 0;	
			// Calculate each row
			$(this).find(".row").each(function() {							   
				$(this).calcSubWidth();
				// Find biggest row
				if(rowWidth > biggestRow) {
					biggestRow = rowWidth;
				}
			});
			// Set width
			$(this).find(".sub").css({'width':biggestRow});
			$(this).find(".row:last").css({'margin':'0'});
			
		} else { //If row does not exist...
			$(this).calcSubWidth();
			// Set Width
			$(this).find(".sub").css({'width': rowWidth});
		}
	}
	
	function megaHoverOut(){ 
	  $(this).find(".sub").stop().fadeTo('fast', 0, function() {
		  $(this).hide(); 
	  });
	}

	var config = {    
		 sensitivity: 2,		// number	= sensitivity threshold (must be 1 or higher)    
		 interval: 100,			// number	= milliseconds for onMouseOver polling interval    
		 over: megaHoverOver,	// function	= onMouseOver callback (REQUIRED)    
		 timeout: 500,			// number	= milliseconds delay before onMouseOut    
		 out: megaHoverOut		// function	= onMouseOut callback (REQUIRED)    
	};

	$("ul#topnav li .sub").css({'opacity':'0'});
	$("ul#topnav li").hoverIntent(config);
	

	
	
	
	
	// Handles the mouseover sounds on top-nav primary button links
	/*
	$("#topNav #topnav li .sound").mouseover(function() {
		$("#player_div").empty();
		$("#player_div").prepend(insertPlayer());
	});
	*/




	// Enables jqueryui tabs; works, but without the tabs' history support
	//	$('.tabs').tabs();
	
	// For tabs' history support
//	$('.tabs').tabs({ select: function(event, ui){ window.location = ui.tab.href; } });


	
	$('.tabs').tabs({ select: function(event, ui){ window.location = ui.tab.href; } });    
	$('.tabs').tabs({ fx: { height: 'toggle', opacity: 'toggle', duration: 'fast' } });


	if ($(".tabs").length != 0) {
		$(".tabs").bind("tabsselect",function(event,ui) {
			_gaq.push(['_trackPageview', window.location + '#' + ui.tab.innerHTML]);
		});
	}




	// For the bottom scroller area
	//	auto: 10000,
	$("div#bottomBox .bottomScroller").jCarouselLite({
		speed: 1000,
		btnNext: ".next",
		btnPrev: ".prev"
	});
	
	
//	To round (most) of the div corners
//	$('.cornered').corner();
//	$('.blogCat').corner("round 5px");
	
	
	// For the tooltips
	$('.tooltip').bt({
	  titleSelector: "attr('title')",
	  positions: ['top', 'right', 'bottom'],
	  fill: '#F4F4F4',
	  strokeStyle: '#666666', 
	  spikeLength: 10,
	  spikeGirth: 10,
	  width: 300,
	  overlap: 10,
	  centerPointY: 1,
	  cornerRadius: 5, 
	  cssStyles: {
		fontFamily: '"Lucida Grande",Helvetica,Arial,Verdana,sans-serif', 
		fontSize: '10px',
		padding: '10px 14px'
	  },
	  shadow: true,
	  shadowColor: 'rgba(0,0,0,.5)',
	  shadowBlur: 8,
	  shadowOffsetX: 4,
	  shadowOffsetY: 4
	});
	
	
	// Applies text "hint" to any text input box that has a title set, for any page on the site
	$('input[title!=""]').hint();
//	$('input[title!=""]').addClass('globalInputStyle');	// to "grey" the text in the textboxes

	
	
	// This is for the "Primetime QuickView" for the Schedules "overview" module as well as the scheduleMenu app
	/* Do not enable this code- seems to cause all sorts of odd issues for the site- breaks series details tabs, header scroller on Schedules page..
	Shadowbox.init({
		overlayColor:		"#fff",
		overlayOpacity:		0.7,
		onOpen:				scrollBackground,
		onClose:			scrollBackground 
	});
	*/


	// Takes care of jumping back to the top of the left content div
	$(".backToTop").live("click", function() {
		$("#bodyContent-left h1").removeClass('highlighted');
		$(window).scrollTo('#topNav', 800);
	});

	
	// Takes care of jumping back to the specific "letters" areas of the video OnDemand resultset
	$("div#a2z span.letter").live("click", function() {
		$("#bodyContent-left h1").removeClass('highlighted');
		var jumpDestination = $(this).attr('letter');
		var jumpDestId = '#' + jumpDestination;
		$(window).scrollTo(jumpDestId, 800);
		$(jumpDestId).addClass('highlighted');
	});


	// Handles the internal scrolling of the mini-schedule in the top-nav menu
	$("#menuSchedule .prevNext").live("click", function(){
		var timestamp = $(this).attr('ts');
		$('#menuLoader').fadeIn();
		$.get("includes/topNav/menuSchedule.php", { t: timestamp },
		 function(data) {
			$('#menuScheduleInner').html(data);
			$('#menuLoader').fadeOut();
		 }
		);
	});
	
	// Handles resetting the calendar to the current time in the top-nav menu
	$("#menuSchedule .current").live("click", function(){
		$('#menuLoader').fadeIn('slow');
		$.get("includes/topNav/menuSchedule.php",
		 function(data) {
			$('#menuScheduleInner').html(data);
			$('#menuLoader').fadeOut();
		 }
		);
	});
	

	// Handles submitting the OnDemand search form
	$('#onDemandMenuSearchForm input').keypress(function(e) {
		searchStr = $(this).attr('value');
		if (e.keyCode == 13) {
			if (searchStr != "") {
				var url = "?a=onDemand#search:" + searchStr;    
				$(location).attr('href', url);
				
				var fullUrl = document.location.href;
				if (fullUrl.match('a=onDemand')) {
					window.location.reload(true);
				}
			}
			return false;
		//	window.location.hash='search:' + searchStr;
		//	issueSearchResults(searchStr);
		}
	});


	$('#fixedNav').animate({'opacity':'0'}, 0, function() {
//	$('#fixedNav').fadeTo("slow", 0, function() {
		$(this).css("visibility", "hidden")
	  });

	$(window).scroll(function() {
		var scrollTop = $(window).scrollTop();
		if(scrollTop >= 160)
			$('#fixedNav').stop().css('visibility', 'visible').animate({'opacity':'1'}, 400);
		//	$('#fixedNav').stop().slideUp('slow');
		else
			$('#fixedNav').stop().animate({'opacity':'0'}, 400, function() {
				$(this).css('visibility', 'hidden')
			});
		//	$('#fixedNav').stop().slideDown('slow');
	});
	
	refreshMenuSchedule();

/*
	adOffsetTop = $('#bodyContent-right').offset().top;
	adOffsetBottom = $('#bottomBox').offset().bottom;
	$(window).scroll(function() {
		scrollPos = $(window).scrollTop();
		if (scrollPos + 20 > adOffsetTop) {
			$('#bodyContent-right').css({ top: (scrollPos - adOffsetTop + 20) + 'px' });
		} else if (scrollPos - 260 < adOffsetBottom) {
			$('#bodyContent-right').css({ bottom: (scrollPos + adOffsetBottom + 260) + 'px' });
		} else {
			$('#bodyContent-right').css({ top: '0' });
		}
	});
*/


// sidebar ads to be fixed on scroll	http://www.skiutah.com/@@/cssjs/site.js
/*
  var sidebar_ads = $("#bodyContent-right");
  if (sidebar_ads.length) {
    var top_of_first_ad = parseInt($("#bodyContent-right").offset().top);
    var top_of_footer = parseInt($("#bottomBox").offset().top);
    var sidebar_ads_height = 0;
    sidebar_ads.each(function(){
      sidebar_ads_height += $(this).innerHeight();
    });
    $(window).scroll(function(e) {
      top_of_footer = parseInt($("#bottomBox").offset().top);
      var y = parseInt($(this).scrollTop());
      var t = parseInt(y-top_of_first_ad);
      if ((y > top_of_first_ad) && (top_of_first_ad+sidebar_ads_height+t < top_of_footer)) {
        sidebar_ads.each(function(){
          $(this).animate({top:t+"px"}, {duration:100, queue:false});
        });
      } else if (y < top_of_first_ad) {
        sidebar_ads.each(function(){
          $(this).animate({top:"0px"}, {duration:100, queue:false});
        });
      }
    });
  }
*/


});


// Keeps the menu schedule showing the current schedule every n minutes
function refreshMenuSchedule() {
	$.get('includes/topNav/menuSchedule.php', function(data){
		$('#menuScheduleInner').html(data);
	});
	var to = setTimeout('refreshMenuSchedule()', (1000 * 60 * 15)); // Every n mins
}


//	Handles dropdown menu "jumping" to new pages w/o having to hit a submit button
function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}


/*	Prevents the spawning webpage from scrolling once the shadowbox has been called	*/
/*	http://shadowbox-js.com/forum.html#nabble-td4465606|a5074848	*/
/*
function scrollBackground() {
	var objHTML = document.getElementById("htmlBox")
	if (objHTML.style.overflow == "hidden") {
		objHTML.style.overflow = "auto"
	} else {
		objHTML.style.overflow = "hidden"
	}
}
*/


						
function refreshTopNavCurrentShow() {
	$('div#fixedNav div#navContainer div#navContent div.whatsOnWidget span').hide();
	
	if (typeof refreshTopNavCurrentShow.counter == 'undefined') {
	//	Variable has not yet been created... perform the initilization
		refreshTopNavCurrentShow.counter = 0;
	} else {
		++refreshTopNavCurrentShow.counter;
	}
	
	var count = Number(refreshTopNavCurrentShow.counter);

	$.get('slideinNav/getData.php', { channelId : count },
//	$.get('slideinNav/getCurrentShow.php', { channelId : count },
	 function(data) {
		$('div#fixedNav div#navContainer div#navContent div.whatsOnWidget span').html(data).fadeIn();
	//	$('div#fixedNav div#navContainer div#navContent div.whatsOnWidget span').html(data).slideUp(1300).delay(800).fadeIn(400);
	});
	var to = setTimeout('refreshTopNavCurrentShow()', (1000 * 10 * 1)); // Every n mins
}


