var backgroundChanger;
var backgroundChanger;
var nextImg = 0;
var currImg = 0;
var slideShowTimeout;
var rmShowTimeout;

var mvtotimeofday;
var totimeofdayTimeout;
var ttodLock = false;

$(document).ready(function(){
	msie7 = false;
	unsupported = false;
        if(window.location == 'http://www.premiersports.tv/' || window.location == 'http://www.premiersports.tv/index/') {
            $('#content').hide();
            $('a[title="Homepage"]').parent().addClass('on');
        }
        $('.closeSech').hide();
        $('.closeSech').css('right', 'auto');
        
        
	if ($.browser.msie) {
		version = $.browser.version.substr(0,1);
		if (version < 7) {
			unsupported = true;
		}
		else if (version < 8) {
			msie7 = true;
		}
	}

	if (unsupported) {
            alert("Due to a known IE6 transparent images rendering issue, if you are viewing in Internet Explorer this site is best viewed in IE7 or above or any other up to date browser.");
        }
//		// show warning "ie6 and below are not supported"
//		$('noscript').css('display','none');
//		alert('Internet Explorer 6 and below are not supported.\n Please use other modern web browsers.\n\n @Designer: It is needed to create a special page for this warning.');
//	}
	//else {
		$('#wrapper').css('display','block');
		$('noscript').css('display','none');

		Cufon.replace('#signup', {fontFamily: 'MyriadProCond'});
		Cufon.replace('.topmenu a, #live li a, #live li, #game h1, #game h2, #game p, #botmenu, #submenu, #game .descr, #category p, #minischedlinks a', {fontFamily: 'MyriadProSemiboldCond'});
		if (!msie7) {
			Cufon.replace('#minischedule ul li span, #minischedule .title', {fontFamily: 'MyriadProSemiboldCond'});
		}
		Cufon.replace('#leftcol .cms, #rightcol .cms2, #contents, #minischedule .descr, h1, h2, h3, h4, h5, h6, #fixed-content p, #fixed-content li, #fixed-content a, .tabbed-nav a, .fixtures tr th, .fixtures tr td', {fontFamily: 'MyriadProSemiboldCond'});
		
                
                
		Cufon.now();

		setContHeight();

		$(window).resize(function() {
			setContHeight();
		});


		if (typeof twCont !== "undefined" && twCont) {
			twInterval = setInterval(checkTwHeight, 200);
		}
	//}

	$('#minischedlinks a').click(function(){
		if (!$(this).hasClass('active')) {
			$('#minischedlinks a').removeClass('active');
			$(this).addClass('active');
			if (!$(this).hasClass('div')) {
				$('#minischedule ul').fadeIn();
				$('#minischedule div.title').fadeIn();
				$('#minischedule div.descr').fadeOut();
			}
			else {
				$('#minischedule div.descr').fadeIn();
				$('#minischedule ul').fadeOut();
				$('#minischedule div.title').fadeOut();
			}
		}
		return false;
	});


        tvSchedule();
                
	liveEvents();

	clickSubMenu();

	closeWin();

	
	
	showRegForm();
	
	
	$('.topmenu > li > a').click(function() {
		if($(this).attr('title') == 'Homepage') {
                    closeContent();
                    $('#tvschedule').fadeOut('fast');
		    $('a[title="TV Schedule"]').parent().removeClass('active');
                    
		}
                
            $('.topmenu > li').removeClass('on');
            $(this).parent().addClass('on');
            return false;
	});
        
        setAjax();
        
        
                
        $('.closeSech').click(function(){
		$('#tvschedule').fadeOut('fast');
		$('a[title="TV Schedule"]').parent().removeClass('active');
		$('#tvscheduleload').fadeOut('fast');
                $('#content').fadeOut('fast');
                $('.closeSech').fadeOut('fast');
                $('.topmenu li').removeClass('on');
		return false;
	});
        
        backgroundChanger = new Array();
        
        $.ajax({
        type: "GET",
	url: "/sys/live-events.xml/",
	dataType: "xml",
	success: function(xml) {
            var winwidth = $(window).width();
            $('#flashbgin').append('<div id="datesouter" style="position: absolute; color: #fff; left: 330px; width:'+(winwidth-330)+'px; top: 2px; overflow: hidden; font-size: 14px; font-weight: bold;"><div style="position: relative; height: 16px;"><div style="position: absolute; width:100000px; left: 0px;" id="flashbglog"></div></div></div>');
            $('#flashbglog').append('<span style="width: 65px; display: block; float: left;">LIVE EVENTS &nbsp;</span>');
            $(xml).find('pic').each(function(){
                var obj = {
                    image: $(this).find('image').text(),
                    title: $(this).find('title').text(),
                    league: $(this).find('league').text(),
                    date: $(this).find('date').text(),
                    time: $(this).find('time').text(),
                    intro: $(this).find('intro').text()
                };
                
                $('#flashbglog').append('<span id="topslide-'+backgroundChanger.length+'" style="cursor: pointer; width: 90px; display: block; float: left;">'+obj.date+'&nbsp;&nbsp;&gt;&gt;&nbsp;</span>');
                $('#topslide-'+backgroundChanger.length).click(function() { 
                    clearTimeout(slideShowTimeout);
                    currImg = $(this).attr('id').replace(/topslide-/, '');
                    rmTime();
                    changeImage();
                } );
                backgroundChanger.push(obj);
            });
            $('#flashbg').append('<div style="height: 92px; width: 100%;"></div>');
            Cufon.replace('#flashbglog', {fontFamily: 'MyriadProSemiboldCond'});
            changeImage();
            //changeImage(1);
	}
        });
        
	/*
    if($("#dragTV").length > 0)  {    


   } else {
      //Load Old TV Schedule
        showMoreInfo();
	tvScheduleRefresh();
   }
	*/
	
	$('a[title=Twitter]').click(function() { 
		window.open( "http://twitter.com/premiersportstv","_blank");
	});
	$('a[title=Facebook]').click(function() { 
		window.open( "http://www.facebook.com/premiersports.tv","_blank");
	});
	
	
});


function closeContent() {
    $('#content').fadeOut();
    $('.closeSech').fadeOut();
    $('.topmenu > li > ul li').removeClass('on');
	
}


function changeImage() {
    obj = backgroundChanger[currImg];
    
    zindex = 12;
    if($('#flashbg img').length == 0) {zindex = 13;}
    //Add Image
    $('#flashbg').append('<img src="'+obj.image+'" style="z-index:'+zindex+';" />');
    //Add Text
    var winwidth = $(window).width();
    $('#flashbgincont').append('<div id="headertextwrap" style="color: #FFFFFF; overflow: hidden; width:'+(winwidth-330)+'px; height: 70px; position:absolute; top: 21px; margin-left: 10px; font-size: 32px; line-height: 19px;"><div style="width: 8000px;"><span style="font-size: 42px;">'+obj.title+'</span> '+obj.league+' '+obj.time+'<br /><span style="color: #F5C730; font-size: 16px;" class="header-bottom">'+obj.intro+'</span></div></div>');
    $('#flashbgincont div:last').hide();
    Cufon.replace('#flashbgincont', {fontFamily: 'MyriadProSemiboldCond'});
    
    $("#flashbg img:last").hide();
    $("#flashbg img:last").load(function() { 
        //Change Top Dates
        $('#flashbglog span').css('color', '#FFFFFF');
        $('#topslide-'+currImg).css('color', '#F5C730');
        Cufon.replace('#flashbglog span', {fontFamily: 'MyriadProSemiboldCond'});
        var swidth = 90;
        var fadeTime = 3000;
        lto = ((-swidth*currImg) != 0) ? (-swidth*currImg)-65+swidth : 0;
        $('#flashbglog').animate({'left': lto+'px'}, fadeTime);
        
        $(this).fadeIn(fadeTime);
        $(this).fullBg();
        
        
        if($('#flashbg img').length > 1) {
            $('#flashbg img:first').fadeOut(fadeTime, function() {rmTime();});
            /*
            $('#flashbgincont div:first').fadeOut(1500, function() {
                $('#flashbgincont div:last').fadeIn(1500);
                });
            */
           $('#flashbgincont div:first').hide();
           $('#flashbgincont div:last').show();
        } else {
            $('#flashbgincont div:last').fadeIn(fadeTime);
        }
        currImg++;
        if(currImg >= backgroundChanger.length) {
            currImg = 0;
        }
        slideShowTimeout = setTimeout(function() {
            changeImage();
        }, slideShowTimeoutSeconds);
    });
    
}

function rmTime() {
    $('#flashbgincont div:first').remove();
    $('#flashbg img:first').remove();
    $('#flashbg img:first').css('z-index', 13);
}

function setAjax() {
        closetvSchedule();
        $('.topmenu > li > ul li a, .tabbed-nav a').each(function(aindex) {
            var element = $(this);
            if(element.attr('rel') != 'ajaxcall') {
                element.attr('rel', 'ajaxcall');
                $(this).click(function() { 
                    closeBut();
                    $('#content').fadeIn('fast');
                    var link = $(this).attr('href');
                    if($(this).parent().parent().parent().parent().hasClass('topmenu')) {$('.topmenu > li > ul li').removeClass('on');}
                    $(this).parent().addClass('on');
                    callPage(link);
                    return false;
                });
           }
        });
}


function callPage(link) {
    //<div id="content"><div id="content-border"><div id="content-wrap"></div></div></div>
    $.ajax({
            url: 'sys/ajax/ajax-general/',
            type: 'GET',
            data: 'urlf='+link,
            success: function(content) {
                    $('.closeSech').fadeIn('fast');
                    $('.closeSech').css('left', 1054);
                    $('.closeSech').css('top', 136);
                    
                    $('#content-wrap').html(content);
                    Cufon.replace('h1, h2, h3, #fixed-content p, #fixed-content li, #fixed-content a, .tabbed-nav a, .fixtures tr th, .fixtures tr td', {fontFamily: 'MyriadProSemiboldCond'});
                    setAjax();
                    /*
                    if (!$('#showcontent').hasClass('opened')) {
                            $('#showcontent').fadeIn('fast');
                            $('#showcontent').addClass('opened');
                    }
                    */
            }
    });
}

function showRegForm () {
	
	$('#signup a').click(function(){
		$.ajax({
			url: 'sys/ajax/subscription-form/',
			type: 'GET',
			success: function(content) {
				closeContent();
				closetvSchedule();
				$('#showcontentin').html(content);
				
				if (!$('#showcontent').hasClass('opened')) {
					$('#showcontent').fadeIn('fast');
					$('#showcontent').addClass('opened');
				}
				$('.pause a').trigger('click');
			}
		});
		return false;
	});
}

function closetvSchedule() {
   var parentEl = $('a[title="TV Schedule"]').parent();
    $('#tvschedule').fadeOut('fast');
	$('#tvscheduleload').fadeOut('fast');
   parentEl.removeClass('active');
	
}

function tvSchedule () {
	$('a[title="TV Schedule"]').click(function(){
            closeContent();
		
            //tvScheduleRefresh();
            $('.closeSech').fadeIn('fast');
            $('.closeSech').css('left', 1184);
            $('.closeSech').css('top', 134);
            
            if($('#tvschedule').length > 0) {
		parentEl = $(this).parent();
		if (!parentEl.hasClass('active')) {
			if ($('#showcontent').hasClass('opened')) {
				$('#showcontent').fadeOut('fast');
				$('#showcontent').removeClass('opened');
			}
			$('#tvschedule').fadeIn('fast');
			parentEl.addClass('active');
			
			var d = new Date();
			    var dl = new Date(d.getFullYear(),(d.getMonth()),d.getDate(),0,0,0);
			    
			    //Calculate Start Time
			    var startLeft = d.getTime();
			    //Zero it against todays stamp
			    startLeft = ((startLeft-dl.getTime()));
			    //Start time, per unit time, times total width
			    startLeft = (((startLeft/(60*60*24*7*1000))*(160*7*24)));
			    
			    $('#dragTV').stop().animate({'scrollLeft': startLeft}, 2000);
			    //$('#dragTV').scrollLeft( startLeft);
			
		}
		else {
			$('#tvschedule').fadeOut('fast');
			parentEl.removeClass('active');
		}
	} else {
		$('#tvscheduleload').fadeIn('fast');
		loadTVSchedule2();
	}
		return false;
	});
}

function tvScheduleRefresh() {
	$('#tvschedule ul.quart li').click(function(){
		if (!$(this).hasClass('full')) {
			tvScheduleDoRefresh(this);
		}
		return false;
	});
	$('#tvschedule ul.week li span').click(function(){
		tvScheduleDoRefresh(this);
		return false;
	});
	$('#tvschedule span.aleft').click(function(){
		if (!$(this).hasClass('nonact')) {
			tvScheduleDoRefresh(this);
		}
		return false;
	});
	$('#tvschedule span.aright').click(function(){
		if (!$(this).hasClass('nonact')) {
			tvScheduleDoRefresh(this);
		}
		return false;
	});

        
        
}

function tvScheduleDoRefresh(el) {
	sdata = 'time='+$(el).attr('rel')+'&pos='+$(el).attr('rev');
	$('#tvscheduleload').fadeIn('fast');
	$('#tvschedule').addClass('tvremove');
	$('#tvschedule .hour, #tvschedule .sched').fadeOut('fast');
	$.ajax({
		url: 'sys/ajax/tv-schedule/',
		type: 'GET',
		data: sdata,
		success: function(html) {
			
			$('#wrapper').prepend(html);
			$('#tvscheduleload, .tvremove').fadeOut('slow').remove();
			Cufon.replace('#tvschedule p', {fontFamily: 'MyriadProSemiboldCond'});
			Cufon.replace('#tvschedule ul li span', {fontFamily: 'MyriadProSemiboldCond'});
			Cufon.replace('#tvschedule ul li p', {fontFamily: 'MyriadProSemiboldCond'});
			Cufon.replace('#tvschedule ul li a', {fontFamily: 'MyriadProSemiboldCond'});
			$('#tvschedule').css('display','block');
			
			tvScheduleRefresh();
			showMoreInfo();
		}
	});
}

function liveEvents () {
	$('#live li a').click(function(){
		if ($('body').attr('id')!='mainpage') {
			sdata = 'id='+$(this).attr('rel')+'&p=1';
		}
		else {
			sdata = 'id='+$(this).attr('rel');
		}
		$.ajax({
			url: 'sys/ajax/live-events/',
			type: 'GET',
			data: sdata,
			success: function(html) {
				$('#live').remove();
				$('#game').remove();
				$('#wrapper').prepend(html);
				Cufon('#live li a', {fontFamily: 'MyriadProSemibold', hover: true});
				Cufon.replace('#live li', {fontFamily: 'MyriadProSemibold'});
				Cufon.replace('#game h1', {fontFamily: 'MyriadProCond'});
				Cufon.replace('#game h2', {fontFamily: 'MyriadProSemiboldCond'});
				Cufon.replace('#game p', {fontFamily: 'MyriadProSemiboldCond'});
				Cufon.replace('#game .descr', {fontFamily: 'MyriadProSemiboldCond'});
				liveEvents();
			}
		});
		return false;
	});
}

function showMoreInfo () {
	$('#tvschedule ul.sched a.more').click(function(){
		
				
		var trel = 'title'+$(this).attr('rel');
		var drel = 'descr'+$(this).attr('rel');
		var title = $('.moreinfo[rel="'+trel+'"]').text();
		var descr = $('.moreinfo[rel="'+drel+'"]').text();

		var txt = '<h1>'+title+'</h1>'+'<p>'+descr+'</p>';
		$('#showcontentin').empty();
		$('#showcontentin').html(txt);

		if (!$('#showcontent').hasClass('opened')) {
			$('#showcontent').fadeIn('fast');
			$('#showcontent').addClass('opened');
		}

		Cufon.replace('#showcontentin h1', {fontFamily: 'MyriadProSemiboldCond'});
		Cufon.replace('#showcontentin h2', {fontFamily: 'MyriadProSemiboldCond'});
		Cufon.replace('#showcontentin h3', {fontFamily: 'MyriadProSemiboldCond'});
		Cufon.replace('#showcontentin h5', {fontFamily: 'MyriadProSemiboldCond'});
		Cufon.replace('#showcontentin h6', {fontFamily: 'MyriadProSemiboldCond'});
		Cufon.replace('#showcontentin p', {fontFamily: 'MyriadProSemiboldCond'});
		Cufon.replace('#showcontentin li', {fontFamily: 'MyriadProSemiboldCond'});
		Cufon.replace('#showcontentin a', {fontFamily: 'MyriadProSemiboldCond'});
		
		
		return false;
	});
}

function clickSubMenu () {
	$('#submenu li a, a[title="FAQ"]').click(function(){
		loadBox($(this).attr('rel'));
                
		return false;
	});
}

function loadBox(rel) {
	$.ajax({
			url: 'sys/ajax/show-content/',
			type: 'GET',
			data: 'id='+rel,
			success: function(result) {
				$('#showcontentin').html(result);
				Cufon.replace('#showcontentin h1', {fontFamily: 'MyriadProSemiboldCond'});
				Cufon.replace('#showcontentin h2', {fontFamily: 'MyriadProSemiboldCond'});
				Cufon.replace('#showcontentin h3', {fontFamily: 'MyriadProSemiboldCond'});
				Cufon.replace('#showcontentin h5', {fontFamily: 'MyriadProSemiboldCond'});
				Cufon.replace('#showcontentin h6', {fontFamily: 'MyriadProSemiboldCond'});
				Cufon.replace('#showcontentin p', {fontFamily: 'MyriadProSemiboldCond'});
				Cufon.replace('#showcontentin li', {fontFamily: 'MyriadProSemiboldCond'});
				Cufon.replace('#showcontentin a', {fontFamily: 'MyriadProSemiboldCond'});
				
				
				
				  $(document).ready(function() {
					$("#accordion").accordion({active: false});
					$("#accordion").accordion({collapsible: true});
				  });
				  

				closeContent();
			}
		});
		if ($('#botmenu a[rel="tvschedule"]').parent().hasClass('active')) {
			$('#tvschedule').fadeOut('fast');
			$('#botmenu a[rel="tvschedule"]').parent().removeClass('active');
		}
		if (!$('#showcontent').hasClass('opened')) {
			$('#showcontent').fadeIn('fast');
			$('#showcontent').addClass('opened');
		}
}

function closeWin () {
	$('#wrapper').click(function(event){
		if ($('#showcontent').hasClass('opened')) {
			if (!$(event.target).closest('#showcontent').length) {
				$('.play a').trigger('click');
				$('#showcontent').fadeOut('fast');
				$('#showcontent').removeClass('opened');
			};
		}
		if ($('#botmenu a[rel="tvschedule"]').parent().hasClass('active')) {
			if (!$(event.target).closest('#tvschedule').length) {
				$('#tvschedule').fadeOut('fast');
				$('#botmenu a[rel="tvschedule"]').parent().removeClass('active');
			};
		}
                //closeContent();
	});
	$('#closebut').click(function(){
		closeBut();
	});
}

function closeBut() {
    if ($('#showcontent').hasClass('opened')) {
	    $('.play a').trigger('click');
			$('#showcontent').fadeOut('fast');
			$('#showcontent').removeClass('opened');
		}
}

function checkTwHeight () {
	if ($('#rightcol .twtr-bd').height() > 0) {
		setContHeight()
		clearInterval(twInterval);
	}
}

function setContHeight() {
	bh = $(document).height()-$('body').offset().top;

	// deleted on 09.05.11
	/*

	cnth = bh - 169;
	$('#content').height(cnth);

	cmsh = bh - 532;
	$('#leftcol .cms').height(cmsh);
	$('#rightcol .cms').height(cmsh);
	$('#rightcol .twtr-widget').height(cmsh);

	*/
	
	sch =  bh - 280;
	//$('#showcontent').height(sch);
	schin = sch - 80;
	//$('#showcontentin').height(schin);
}


(function($) {
  $.fn.fullBg = function(){
    var bgImg = $(this);		
 
    function resizeImg() {
      var imgwidth = bgImg.width();
      var imgheight = bgImg.height();
 
      var winwidth = $(window).width();
      var winheight = $(window).height();
 
      var widthratio = winwidth / imgwidth;
      var heightratio = winheight / imgheight;
 
      var widthdiff = heightratio * imgwidth;
      var heightdiff = widthratio * imgheight;
 
      if(heightdiff>winheight) {
        bgImg.css({
          width: winwidth+'px',
          height: heightdiff+'px'
        });
      } else {
        bgImg.css({
          width: widthdiff+'px',
          height: winheight+'px'
        });		
      }
    } 
    resizeImg();
    $(window).resize(function() {
      resizeImg();
      var winwidth = $(window).width();
      $('#datesouter').css('width', (winwidth-330));
      $('#headertextwrap').css('width', (winwidth-330));
    }); 
  };
})(jQuery)

