/*-------------------------------------------*\
                 DYNAMIC LEADS
\*-------------------------------------------*/
var currentTab=1;		//Keeps track of the current tab for rotating.
var dlRotate;			//Stores the interval for tab switching so it can be stopped.
var dlRunning = false;	//Keeps track of whether or not the auto scroll is running.
var dlNumTabs;			//Counts the number of tabs once the DOM is ready.
var firstLoad = true;	//Modifies the Toggle function on the first page load.
var dlFade = false;	//Keeps track of fading well it is occuring.
var RotateTime = 7000; //Delay time so rotation on the page occurs @ the same time

function dlToggle() { //Starts/stops the auto switching
	if(dlRunning) {
		$("a#dlToggle").css("background-position","-26px 0");
		clearInterval(dlRotate);
		dlRunning = false;
	} else {
		$("a#dlToggle").css("background-position","-13px 0");
		firstLoad?firstLoad=false:dlCycle("next");
		dlRotate = setInterval('dlCycle("'+'next'+'")', RotateTime);
		dlRunning = true;
	}
}

function dlCycle(direction) { //Goes to next or previous tab
	if(direction == "next") {
		dlSwitch(currentTab>=dlNumTabs?1:currentTab+1);
	} else {
		dlSwitch(currentTab==1?dlNumTabs:currentTab-1);
	}
}

function dlSwitch(tabNum) { //Goes to the requested tab
	if(!dlFade || $.browser.msie) {
		dlFade = true;
		if($.browser.msie) { //Due to the overlay on the image IE can't fade right. I'm as suprised as you are...
			$(".tabContainer").eq(currentTab-1).hide();
			$(".tabContainer").eq(tabNum-1).show();
		} else {
			$(".tabContainer").eq(currentTab-1).fadeOut(200,function(){
				$(".tabContainer").eq(tabNum-1).fadeIn(200,function(){dlFade = false;});
			});
		}
		var nextArticle = (tabNum==dlNumTabs?0:tabNum)
				$(".dlFooter").html(tabNum+" of "+dlNumTabs+"<span style='padding-left:25px;'>Next</span> article: "+$(".tabContainer h2 a").eq(nextArticle).html());
		currentTab=parseInt(tabNum);
	}
}

var isCTRL = false;
var isFocus = false;
function arrowSwitch(Event) {
	if(Event==null) Event=event; //IE doesn't pass the event!
	if(Event.keyCode == 37 && isCTRL) { //left 37
		if(dlRunning) dlToggle();
		dlCycle("previous");
	} else if(Event.keyCode == 39 && isCTRL) { //right 39
		if(dlRunning) dlToggle();
		dlCycle("next");
	} else if(Event.keyCode == 17) {
		isCTRL = true;
	}
	
	if(Event.keyCode == 9 && !isFocus) { //outlines are turned off for firefox until the user hits tab
		$("a").addClass("withFocus");
		isFocus = true;
	}
	
}

function arrowCancel(Event) {
	if(Event==null) Event=event; //IE doesn't pass the event!
	if(Event.keyCode == 17) {
		isCTRL = false;
	}
}

/*-------------------------------------------*\
                 TAB SWITCH'N
\*-------------------------------------------*/
function tabSwitch(tab,tabGroup) {
	$('.'+tabGroup+' li.active').removeClass("active");
	$('.'+tabGroup+' li').eq(tab-1).addClass("active");
	$('.tabsContent.'+tabGroup+'.active').removeClass("active");
	$('.tabsContent.'+tabGroup).eq(tab-1).addClass("active");
}

/*-------------------------------------------*\
                 SCOREBOARD
\*-------------------------------------------*/
var scoreXML; //stores all the scoreboard xml after the ajax call
var scoreAutoRefresh = false; //if a game is in progress the scoreboard will automatically refresh every 5 minutes

function getScoreboardXML() {
	var ajaxTime = new Date().getTime(); //unique number based on time to prevent IE cachine the ajax call
	$.ajax({
		type: "GET",
		url: "/Includes/xml/currentscores.xml?time="+ajaxTime,
		dataType: "xml",
		success: function(xml) {
			scoreXML = xml;
			printScore(); //prints the scoreboard
		}
	});
}

//Cycles a parents children elements either forwards or backwards
function cycleList(parent,direction) {
	var listOrder = $(parent).children();
	if(direction == "next") {
		$(listOrder[0]).insertAfter(listOrder[listOrder.length-1]);
	} else if(direction == "prev") {
		$(listOrder[listOrder.length-1]).insertBefore(listOrder[0]);
	}

}

function slide(direction,scrollBox,btnClass,boxSize,speed) {
	$(btnClass).unbind("click").css({cursor: "default"}); //Removes the scrolling function from the links until the animation is done
	$(scrollBox).animate({left:(direction == "next"?boxSize*(-2):0)},speed,
		function(){
			$(scrollBox).css({ left:boxSize*(-1)+"px"});			
			cycleList(scrollBox,direction);
			$(btnClass).bind("click", function(){ //binds the function back to the appropriate buttons
				slide($(this).attr("rel"),scrollBox,btnClass,boxSize,speed);
				return false;
			}).css({cursor: "pointer"});
		}
	);
}

//parses the xml
function getScore() {
	var scores = Array;
	$('scores games game',scoreXML).each(function(i) {
		thisthis = $(this);
		var homeTeam = thisthis.children("home");
		var awayTeam = thisthis.children("visitor");
		scores[i] = { 
			"day":thisthis.attr("date"),
			"time":thisthis.attr("gametime"),
			"phase":thisthis.attr("phase"),
			"hteam":homeTeam.attr("team"),
			"vteam":awayTeam.attr("team"),
			"hscore":homeTeam.attr("score"),
			"vscore":awayTeam.attr("score"),
                        "gamekey":thisthis.attr("gamekey")
		};
	});
	return scores;
}

function printScore() {
	var scores = Array;
	var time;
	var howMany = 0;
	var week = $('scores games',scoreXML).eq(0).attr("week");
	scores = getScore();
	var html = "<ul>";
	scoreAutoRefresh = false;
	for (key in scores) {
		if(scores[key].phase == "f") {
			time = '<span class="final">Final</span>';
		} else if(scores[key].phase == "pregame" || scores[key].phase == "p") {
			time = "<span>" + scores[key].day + " " + scores[key].time + "</span>";
		} else {
			time = "<span>" + scores[key].time + "</span>";
			scoreAutoRefresh = true;
		}
		html = html + '<li><div class="innerScroll" onMouseOver="this.style.color=\'#990000\';this.style.cursor=\'pointer\';" onMouseOut="this.style.color=\'#2c2a2a\';" onmousedown="JavaScript:window.open(\'/Games/'+scores[key].gamekey+'.html\', \'_self\')"><dl><dt>'+ scores[key].hteam +'</dt><dd>'+ scores[key].hscore +'</dd></dl><dl><dt>'+ scores[key].vteam +'</dt><dd>'+ scores[key].vscore +'</dd></dl>' + time + '</div></li>';
		howMany++;
	}
	
	$("#scrollingBox").html(html);
	cycleList("#scrollingBox ul","prev");
	
	if($.browser.msie)
		$("div#scrollingBox").show();
	else
		$("div#scrollingBox").fadeIn(500);
	
	$("#scoreBoard h1").html("Week " + week).show();
	//$("#scoreBoard h1").html("Super Bowl XLII").show();
	if(howMany>14) $(".btn_slide").show();
	if(scoreAutoRefresh) setTimeout("refreshScores();",300000);
}

function refreshScores() {
	if($.browser.msie) {
		$("div#scrollingBox").hide();
		getScoreboardXML();
	} else {
		$("div#scrollingBox").fadeOut(500, function(){
			getScoreboardXML();
		});
	}
}

/*-------------------------------------------*\
            E-MAIL TO A FRIEND
\*-------------------------------------------*/
function sendit() {
newwin = window.open('','','top=150,left=150,width=320,height=200, resizable=yes');
msg1="Please enter the destination email address:"; 
msg2="Please enter your email address:"; 
gridimage="http://www.canoe.ca/CanoeHomepageImages/grid.gif";
canoenet="http://www.canoe.ca/CanoeGlobalnav/canoe_net05.gif";
formact="http://cgi.canoe.ca/htbin/mailers/sendurl";
url=location.href;
if (!newwin.opener) newwin.opener = self;
with (newwin.document)
{
open();
write('<html><head><title>Send this story to a friend</title></head>');
write('<body text=white bgcolor="#cc3333" onLoad="document.form.receiver.focus()" topmargin=0 marginheight=0 leftmargin=0 marginwidth=0>');
write('<table width=100% cellpadding=1 cellspacing=0 border=0><tr bgcolor=black><td width=100% colspan=3><img src='+ canoenet + '></td></tr>');
write('<tr><td colspan=3 width=100% background=' + gridimage + '><br></td></tr>');
write('<tr><td width=10>  </td><td><font size=2><form name=form action=' + formact + '>' + msg1 + '<br>');
write('<b>TO: </b><input type=text name="receiver" size=30 maxlength=100>');
write('<br><br>'+ msg2 + '<br>');
write('<b>FROM: </b><input type=text name="sender" size=30 maxlength=100>');
write('<input type=hidden name="pageurl" value=' + url + '><br>');
write('<p><input type=submit value="submit">');
write('</form></font></td><td width=10>  </td></tr></table>');
write('</body>');
write('</html>');
close();
}
}

/*-------------------------------------------*\
               ROTATE NFL RUSH
\*-------------------------------------------*/
var timecounter = 0;
var timeout_counter = true;
function stop_autoRotate()
{timeout_counter = false;}
function autoRotate()
{
	if (timecounter == 0 && timeout_counter) 
             {timecounter = timecounter+1;tabSwitch('1','tabs2');}
	else if (timecounter == 1 && timeout_counter)
             {timecounter = timecounter+1;tabSwitch('2','tabs2');}
	else if (timecounter == 2 && timeout_counter)
             {timecounter = timecounter+1;tabSwitch('3','tabs2');}
	else if (timecounter >= 3 && timeout_counter)
             {timecounter = 0;tabSwitch('4','tabs2');}
        
        if (timeout_counter)setTimeout('autoRotate()',RotateTime);
}