/* jQuery Slider */
(function($){$.fn.jCarouselLite=function(o){o=$.extend({btnPrev:null,btnNext:null,btnGo:null,mouseWheel:false,auto:null,speed:200,easing:null,vertical:false,circular:true,visible:3,start:0,scroll:1,beforeStart:null,afterEnd:null},o||{});return this.each(function(){var b=false,animCss=o.vertical?"top":"left",sizeCss=o.vertical?"height":"width";var c=$(this),ul=$("ul",c),tLi=$("li",ul),tl=tLi.size(),v=o.visible;if(o.circular){ul.prepend(tLi.slice(tl-v-1+1).clone()).append(tLi.slice(0,v).clone());o.start+=v}var f=$("li",ul),itemLength=f.size(),curr=o.start;c.css("visibility","visible");f.css({overflow:"hidden",float:o.vertical?"none":"left"});ul.css({margin:"0",padding:"0",position:"relative","list-style-type":"none","z-index":"1"});c.css({overflow:"hidden",position:"relative","z-index":"2",left:"0px"});var g=o.vertical?height(f):width(f);var h=g*itemLength;var j=g*v;f.css({width:f.width(),height:f.height()});ul.css(sizeCss,h+"px").css(animCss,-(curr*g));c.css(sizeCss,j+"px");if(o.btnPrev)$(o.btnPrev).click(function(){return go(curr-o.scroll)});if(o.btnNext)$(o.btnNext).click(function(){return go(curr+o.scroll)});if(o.btnGo)$.each(o.btnGo,function(i,a){$(a).click(function(){return go(o.circular?o.visible+i:i)})});if(o.mouseWheel&&c.mousewheel)c.mousewheel(function(e,d){return d>0?go(curr-o.scroll):go(curr+o.scroll)});if(o.auto)setInterval(function(){go(curr+o.scroll)},o.auto+o.speed);function vis(){return f.slice(curr).slice(0,v)};function go(a){if(!b){if(o.beforeStart)o.beforeStart.call(this,vis());if(o.circular){if(a<=o.start-v-1){ul.css(animCss,-((itemLength-(v*2))*g)+"px");curr=a==o.start-v-1?itemLength-(v*2)-1:itemLength-(v*2)-o.scroll}else if(a>=itemLength-v+1){ul.css(animCss,-((v)*g)+"px");curr=a==itemLength-v+1?v+1:v+o.scroll}else curr=a}else{if(a<0||a>itemLength-v)return;else curr=a}b=true;ul.animate(animCss=="left"?{left:-(curr*g)}:{top:-(curr*g)},o.speed,o.easing,function(){if(o.afterEnd)o.afterEnd.call(this,vis());b=false});if(!o.circular){$(o.btnPrev+","+o.btnNext).removeClass("disabled");$((curr-o.scroll<0&&o.btnPrev)||(curr+o.scroll>itemLength-v&&o.btnNext)||[]).addClass("disabled")}}return false}})};function css(a,b){return parseInt($.css(a[0],b))||0};function width(a){return a[0].offsetWidth+css(a,'marginLeft')+css(a,'marginRight')};function height(a){return a[0].offsetHeight+css(a,'marginTop')+css(a,'marginBottom')}})(jQuery);

/* jQuery Easing */
//commented out because easing plugin is in default globals.inc, and was causing conflict with such in other widgets
/*jQuery.easing = {
	easein: function(x, t, b, c, d) {
		return c*(t/=d)*t + b; // in
	},
	easeinout: function(x, t, b, c, d) {
		if (t < d/2) return 2*c*t*t/(d*d) + b;
		var ts = t - d/2;
		return -2*c*ts*ts/(d*d) + 2*c*ts/d + c/2 + b;		
	},
	easeout: function(x, t, b, c, d) {
		return -c*t*t/(d*d) + 2*c*t/d + b;
	},
	linear: function(x, t, b, c, d) {
		return c*t/d + b; //linear
	}
};*/

/* Accordion */
$(document).ready(function(){
    $('.accordion .children').hide();
    $('.accordion .head').click(function() {
        var idParent = '#' + $(this).parent().parent().parent().attr('id');
        $(idParent + ' .children').slideUp('slow');
        if (!$(this).hasClass('on')) {
            $(idParent + ' .head').removeClass('on');
            $(this).addClass('on');
            $(idParent + ' .' + $(this).attr('title')).slideDown('slow');
       }else{
            $(idParent + ' .head').removeClass('on');
        }
    });
});

/* Tabs */
$(document).ready(function(){
    $('.tabbox .tabcontent').hide();
    $('.tabbox .tabcontent-01').show();
    $('.tabbox .tab-01').addClass('on');
    $('.tab a').click(function() {
        var idParent = '#' + $(this).parent().parent().parent().attr('id');
        $(idParent + ' .tab').removeClass('on');
        $(this).parent().addClass('on');
        $(idParent + ' .tabcontent').hide();
        $(idParent + ' ' + $(this).attr('title')).show();
    });
});

var isMenuAnimating = false;
/* Shows Drop Down */
$(document).ready(function(){
    var pxHeight = $('#GlobalShowsNav').height();
    function showNav() {
        $('#playerFrame').css('visibility','hidden');
        $('#GlobalHeaderNav_Shows a').addClass('on');
        $('#GlobalShowsNav').show();
		$('select#lstRegion').hide();
    }
    function hideNav() {
        $('#GlobalHeaderNav_Shows a').removeClass('on');
        $('#GlobalShowsNav').stop().hide();
        $('#playerFrame').css('visibility','visible');
		$('select#lstRegion').show();
    }
    $('#GlobalShowsNav .tab a').click(function() {
        pxHeight = $('#GlobalShowsNav ' + $(this).attr('title')).height()+125;
        $('#GlobalShowsNav').stop().height(pxHeight);
    });
    $('#GlobalHeaderNav_Shows a').click(function() {
			if (!isMenuAnimating){
				isMenuAnimating = true;
				setTimeout("isMenuAnimating=false",1000); // prevents double-clicking
				if ($('#GlobalShowsNav').css('display') == 'none') {
					$('#GlobalShowsNav').css('left', (($(window).width() - 959) / 2) + 'px');
					showNav();
				}else{
					hideNav();
				}
			}
    });
    $('#GlobalShowsNavClose a').click(hideNav);
});

/* Search Boxes */
$(document).ready(function(){
    var stbInstructions = new Array;
    $('input.SearchTextBox').each(function() {
        stbInstructions[$(this).attr('id')] = $(this).val();
    });
    $('input.SearchTextBox').focus(function() {
        if ($(this).val() == stbInstructions[$(this).attr('id')]) {
            $(this).val('');
        }
    });
    $('input.SearchTextBox').blur(function() {
        if (!$(this).val()) {
            $(this).val(stbInstructions[$(this).attr('id')]);
        }
    });
});

/* Footer Slider */
$(document).ready(function(){
    $("#GFooterSliderWrapper #GFooterSliderWindow").jCarouselLite({
        btnNext: "#GFooterSliderWrapper .ScrollBlogNext",
        btnPrev: "#GFooterSliderWrapper .ScrollBlogPrevious",
        speed: 1500,
        easing: "easeInOutQuad",
        visible: 4,
        scroll: 4
    });
});

/* Canada Network Redirect */
$(document).ready(function(){
    $('#CanadaNetworkContainer select').change(function() {
        document.location = $(this).val();
    });
});

/* IE7 Bug Fix (margin bottom issue when float left) */
var detectAgent = navigator.userAgent.toLowerCase();
if (detectAgent.indexOf('msie') > -1) {
    var arVersion = navigator.appVersion.split("MSIE");
    var version = parseFloat(arVersion[1]);
    if (version == 7) {
        $(document).ready(function(){
            $('div').each(function() {
                if ($(this).css('float') == 'left' && $(this).css('margin-bottom') != '0px') {
                    $(this).css('padding-bottom',$(this).css('margin-bottom'));
                }
            });
        });
    }
}

/* jQuery.scrollTo */
;(function( $ ){
	
	var $scrollTo = $.scrollTo = function( target, duration, settings ){
		$(window).scrollTo( target, duration, settings );
	};

	$scrollTo.defaults = {
		axis:'xy',
		duration: parseFloat($.fn.jquery) >= 1.3 ? 0 : 1
	};

	// Returns the element that needs to be animated to scroll the window.
	// Kept for backwards compatibility (specially for localScroll & serialScroll)
	$scrollTo.window = function( scope ){
		return $(window).scrollable();
	};

	// Hack, hack, hack... stay away!
	// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
	$.fn.scrollable = function(){
		return this.map(function(){
			var elem = this,
				isWin = !elem.nodeName || $.inArray( elem.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;

				if( !isWin )
					return elem;

			var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem;
			
			return $.browser.safari || doc.compatMode == 'BackCompat' ?
				doc.body : 
				doc.documentElement;
		});
	};

	$.fn.scrollTo = function( target, duration, settings ){
		if( typeof duration == 'object' ){
			settings = duration;
			duration = 0;
		}
		if( typeof settings == 'function' )
			settings = { onAfter:settings };
			
		if( target == 'max' )
			target = 9e9;
			
		settings = $.extend( {}, $scrollTo.defaults, settings );
		// Speed is still recognized for backwards compatibility
		duration = duration || settings.speed || settings.duration;
		// Make sure the settings are given right
		settings.queue = settings.queue && settings.axis.length > 1;
		
		if( settings.queue )
			// Let's keep the overall duration
			duration /= 2;
		settings.offset = both( settings.offset );
		settings.over = both( settings.over );

		return this.scrollable().each(function(){
			var elem = this,
				$elem = $(elem),
				targ = target, toff, attr = {},
				win = $elem.is('html,body');

			switch( typeof targ ){
				// A number will pass the regex
				case 'number':
				case 'string':
					if( /^([+-]=)?\d+(\.\d+)?(px)?$/.test(targ) ){
						targ = both( targ );
						// We are done
						break;
					}
					// Relative selector, no break!
					targ = $(targ,this);
				case 'object':
					// DOMElement / jQuery
					if( targ.is || targ.style )
						// Get the real position of the target 
						toff = (targ = $(targ)).offset();
			}
			$.each( settings.axis.split(''), function( i, axis ){
				var Pos	= axis == 'x' ? 'Left' : 'Top',
					pos = Pos.toLowerCase(),
					key = 'scroll' + Pos,
					old = elem[key],
					Dim = axis == 'x' ? 'Width' : 'Height';

				if( toff ){// jQuery / DOMElement
					attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );

					// If it's a dom element, reduce the margin
					if( settings.margin ){
						attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
						attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
					}
					
					attr[key] += settings.offset[pos] || 0;
					
					if( settings.over[pos] )
						// Scroll to a fraction of its width/height
						attr[key] += targ[Dim.toLowerCase()]() * settings.over[pos];
				}else
					attr[key] = targ[pos];

				// Number or 'number'
				if( /^\d+$/.test(attr[key]) )
					// Check the limits
					attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max(Dim) );

				// Queueing axes
				if( !i && settings.queue ){
					// Don't waste time animating, if there's no need.
					if( old != attr[key] )
						// Intermediate animation
						animate( settings.onAfterFirst );
					// Don't animate this axis again in the next iteration.
					delete attr[key];
				}
			});

			animate( settings.onAfter );			

			function animate( callback ){
				$elem.animate( attr, duration, settings.easing, callback && function(){
					callback.call(this, target, settings);
				});
			};

			// Max scrolling position, works on quirks mode
			// It only fails (not too badly) on IE, quirks mode.
			function max( Dim ){
				var scroll = 'scroll'+Dim;
				
				if( !win )
					return elem[scroll];
				
				var size = 'client' + Dim,
					html = elem.ownerDocument.documentElement,
					body = elem.ownerDocument.body;

				return Math.max( html[scroll], body[scroll] ) 
					 - Math.min( html[size]  , body[size]   );
					
			};

		}).end();
	};

	function both( val ){
		return typeof val == 'object' ? val : { top:val, left:val };
	};

})( jQuery );
/* Check links against redirect xml */
function removeLinks(target) {
	$.ajax({
		type: "GET",
		url: "/_data/Shows.xml",
		dataType: "xml",
		success: function(data){
			var validShows = new Array();
			$(data).find("id").each(function(){
				validShows.push($(this).text())
			});
			$(target).each(function(){
				var showValid = false;
				var text = $(this).text();
				var redirObj = breakupRedirect($(this).attr('href'));
				var show = redirObj.show;
				for(i=0;i<validShows.length;i++){
					if(show.toLowerCase() == validShows[i].toLowerCase()){
						showValid = true;
					}
				}
				if(!showValid){
					$(this).parent().text(text).addClass("linkRemoved");
					$(this).remove();
				} 
			});
			doSpecialCases(target);
		}
	});
}
function doSpecialCases(target) {
	var returnMe = true;
	var callSign = readCookie("CallSign");
	$.ajax({
		type: "GET",
		url: "/_data/SpecialCases.xml",
		dataType: "xml",
		success: function(data){
			var specialCases = new Array();
			$(data).find("id").each(function(){
				specialCases.push($(this).text())
				//alert($(this).text());
			});
			$(target).each(function(){
				var redirObj = breakupRedirect($(this).attr('href'));
				for(i=0;i<specialCases.length;i++){
					if(redirObj.show.toLowerCase() == specialCases[i].toLowerCase()){
					//alert(specialCases[i]);
					$(this).attr("href", redirObj.loc + "?" + redirObj.root + "/" + redirObj.show + callSign + "/" + redirObj.type);
					}
				}
			});
			
		},
		error: function(data){
			returnMe = false;
		}
	});
	return returnMe;
}
function breakupRedirect(url){
	// http://www.globaltv.com/scripts/redirect.aspx?shows/90210/url - Example URL
	// loc?root/show/type - Example Sections
	// loc?params - Example Sections
	var loc = url.split("?")[0];
	var params = url.split("?")[1];
	var root = params.split("/")[0];
	var show = params.split("/")[1];
	var type = params.split("/")[2];
	var returnMe = new Object();
	returnMe.url = url;
	returnMe.loc = loc;
	returnMe.params = params;
	returnMe.root = root;
	returnMe.show = show;
	returnMe.type = type;
	return returnMe;
}
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

