/*--Functions--*/

/*
    Adds protection from conflicting JavaScript libraries, like Prototype, that can be included
    by ads.
*/
var $j = jQuery.noConflict();

function escapeChar(text) {
	text.replace('\'','\\\'');
	return text;
}

/*Cookies*/

function getCookie(cookiename) {
	var myexpression = eval('/' + cookiename + '=([^;]*)/');
	myexpression.exec(document.cookie);
	return RegExp.$1 ;
}

function setCookie(name, value, expires) {
	document.cookie = name + '=' + escape(value) + '; path=/' + ((expires == null) ? '' : '; expires=' + expires.toGMTString());
}

function delCookie(name) {
	document.cookie = name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT' +  '; path=/';
}

/*Time*/

function monthConvert(month) {
	return (month * 1) - 1;
}

function hourConvert(hour, ampm) {
	if (ampm.toString() == 'PM') {
		return (hour * 1) + 12;
	}
	else {return hour * 1};
}

function showHourConvert(time) {
	var hour = time.split(':');
	var hourNum = hour[0] * 1;
	if(hourNum > 12) {
		hourMod = hourNum - 12;
		return hourMod + ':' + hour[1] + ' PM';
	}
	else {
		return hourNum + ':' + hour[1] + ' AM';
	}
}

function tvScheduleLink() {
	var today = new Date();
	var day = today.getDate();
	var month = today.getMonth();
	var year = today.getFullYear();
	if(month == 0) {month = 'january';}
	else if(month == 1) {month = 'february';}
	else if(month == 2) {month = 'march';}
	else if(month == 3) {month = 'april';}
	else if(month == 4) {month = 'may';}
	else if(month == 5) {month = 'june';}
	else if(month == 6) {month = 'july';}
	else if(month == 7) {month = 'august';}
	else if(month == 8) {month = 'september';}
	else if(month == 9) {month = 'october';}
	else if(month == 10) {month = 'november';}
	else if(month == 11) {month = 'december';}
	return month + '-' + day + '-' + year;
}

/*STATS*/

function statsGameTime(timetext) {
	var today = new Date();
	var month = today.getMonth();
	var day = today.getDate();
	splitGameTime = [];
	if (timetext.split(' ')[2] !== undefined) {
		splitGameTime['month'] = timetext.split(' ')[2].split('/')[0];
		splitGameTime['day'] = timetext.split(' ')[2].split('/')[1];
	}
	else {
		splitGameTime['month'] = (month * 1) + 1;
		splitGameTime['day'] = day;
	}
	splitGameTime['hour'] = timetext.split(' ')[0].split(':')[0];
	splitGameTime['minute'] = timetext.split(' ')[0].split(':')[1];
	splitGameTime['ampm'] = timetext.split(' ')[1];
}

/*Tune-in Rotator*/

$j(document).ready(function() {
	//Test if variables from Marketing exist, if not, use defaults
	if(typeof tunein_text_1 == 'undefined' || tunein_text_1 == ''){tunein_text_1 = 'TONIGHT 10p ET: NESN Daily';}
	if(typeof tunein_link_1 == 'undefined' || tunein_link_1 == ''){tunein_link_1 = 'http://www.nesn.com/nesn-daily/';}
	if(typeof tunein_text_2 == 'undefined' || tunein_text_2 == ''){tunein_text_2 = 'WEEKDAYS 6-9a ET: Dennis and Callahan';}
	if(typeof tunein_link_2 == 'undefined' || tunein_link_2 == ''){tunein_link_2 = 'http://www.nesn.com/dennis-and-callahan';}
	if(typeof tunein_text_3 == 'undefined' || tunein_text_3 == ''){tunein_text_3 = 'Today on NESN';}
	if(typeof tunein_link_3 == 'undefined' || tunein_link_3 == ''){tunein_link_3 = 'http://www.nesn.com/tv-schedule.html';}
	//Build HTML and append to tune-in div
	var tunein_1 = '<a class="slide" href="' + tunein_link_1 + '" style="top: 0">' + tunein_text_1 + '</a>';
	var tunein_2 = '<a class="slide" href="' + tunein_link_2 + '" style="top: 25px">' + tunein_text_2 + '</a>';
	var tunein_3 = '<a class="slide" href="' + tunein_link_3 + '" style="top: 50px">' + tunein_text_3 + '</a>';
	$j('#tune-in').html(tunein_1 + tunein_2 + tunein_3);
	//Animate tune-in HTML
	setInterval(function() {
		$j('.slide:eq(0)').animate({top: '-25px'}, 500, 'swing', function() {
			$j(this).detach(); 
			$j('#tune-in').append('<a class="slide" href="' + $j(this)[0] + '" style="top: 50px">' + $j(this).html() + '</a>');
		});
		$j('.slide:eq(1)').animate({top: '0px'}, 500, 'swing');
		$j('.slide:eq(2)').animate({top: '25px'}, 500, 'swing');
	}, 5000);
});

/*Scoreboard*/

function scoreboardBuilder(league, i) {
	var linkpre, link_text, link_text_vs, link_text_score, linkpost, i, team, cat_dash, cat_underdash, liner, stats_link, preview_link, liveblog_link;
	if (league == 'mlb') {
		city = 'Boston';
		team = 'Red Sox';
		cat_dash = 'boston-red-sox';
		cat_underdash = 'boston_red_sox';
		link_text = 'NESN Nation';
		preview_link = 'http://www.nesn.com/nesn-nation.html';
	} else if (league == 'nhl') {
		city = 'Boston';
		team = 'Bruins';
		cat_dash = 'boston-bruins';
		cat_underdash = 'boston_bruins';
		link_text = 'NESN Nation';
		preview_link = 'http://www.nesn.com/nesn-nation.html';
	} else if (league == 'nfl') {
		city = 'New England';
		team = 'Patriots';
		cat_dash = 'new-england-patriots';
		cat_underdash = 'new_england_patriots';
		link_text =  team + ' News';
		preview_link = 'http://www.nesn.com/' + cat_dash + '/';
	} else if (league == 'nba') {
		city = 'Boston';
		team = 'Celtics';
		cat_dash = 'boston-celtics';
		cat_underdash = 'boston_celtics';
		link_text =  team + ' News';
		preview_link = 'http://www.nesn.com/' + cat_dash + '/';
	}
	
	liveblog_link = 'http://www.nesn.com/' + cat_dash + '/live-blog.html';

	if (league == 'nfl') {
		league = 'fb';
	}
	if (nesnTeams[i].game_status == 'preview') {
		stats_link = 'http://stats.nesn.com/' + league + '/preview.asp?g=' + nesnTeams[i].game_ID; 
	}
	else if (nesnTeams[i].game_status == 'recap') {
		stats_link = 'http://stats.nesn.com/' + league + '/recap.asp?g=' + nesnTeams[i].game_ID;
		link_text = 'Box Score';
        preview_link = 'http://stats.nesn.com/' + league + '/boxscore.asp?gamecode=' + nesnTeams[i].game_ID;
	}
	else if (nesnTeams[i].game_status == 'boxscore') {
		stats_link = 'http://stats.nesn.com/' + league + '/boxscore.asp?gamecode=' + nesnTeams[i].game_ID;
		link_text = 'Box Score';
        preview_link = 'http://stats.nesn.com/' + league + '/boxscore.asp?gamecode=' + nesnTeams[i].game_ID;
	}
	else if (nesnTeams[i].game_status == '') {
		stats_link = 'http://www.nesn.com/' + cat_dash + '/';
	}
	liner = '<li><ul><li class="first"><a href="http://www.nesn.com/' + cat_dash + '/"><span class="block-30 ' + cat_dash + '-30"></span></a><span><a href="' + stats_link + '" class="teamab">' + nesnTeams[i].away_name_abbr + '</a> <a href="' + stats_link + '" class="score">' + nesnTeams[i].away_score + '</a></span><span><a href="' + stats_link + '" class="teamab">' + nesnTeams[i].home_name_abbr + '</a> <a href="' + stats_link + '" class="score">' + nesnTeams[i].home_score + '</a></span></li><li class="last"><span><a href="' + stats_link + '">' + nesnTeams[i].time_text + '</a></span><span><a href="' + liveblog_link + '" class="first">Live Blog</a><a href="' + preview_link + '" class="last">' + link_text + '</a></span></li></ul></li>';
	$j('.scoreboard').append(liner);
}

function compareNumbers(a, b) {
	return a.gameDate - b.gameDate;
}

function scoreboardAutomator() {
	var g, futureBound, pastBound;
	var curDate = new Date();
	var soxFutureBound = (curDate.valueOf()) + 86400000; //24 hours
	var soxPastBound = (curDate.valueOf()) - 54000000; //15 hours
	var bsFutureBound = (curDate.valueOf()) + 86400000;
	var bsPastBound = (curDate.valueOf()) - 64800000; //18 hours
	var patsFutureBound = (curDate.valueOf()) + 86400000;
	var patsPastBound = (curDate.valueOf()) - 86400000;
	var csFutureBound = (curDate.valueOf()) + 86400000;
	var csPastBound = (curDate.valueOf()) - 64800000;
	
	var gameDetails = [];
	//Build the gameDetails array
	for(var i = 0; i < nesnTeams.length; i++) {
		gameDetails[i] = {
			gameStatus: nesnTeams[i].game_status,
			gameDate: new Date(nesnTeams[i].game_year, nesnTeams[i].game_month - 1, nesnTeams[i].game_day, nesnTeams[i].game_hour, nesnTeams[i].game_minute),
			gameLeague: nesnTeams[i].league,
			gameNumber: nesnTeams[i].game_number
		}
	}
	//Remove games outside boundary
	for(var i = gameDetails.length - 1; i >= 0; i--) {
		var thisGame = gameDetails[i].gameDate.valueOf();
		var thisLeague = gameDetails[i].gameLeague;
		if(thisLeague == 'mlb') {futureBound = soxFutureBound; pastBound = soxPastBound;}
		if(thisLeague == 'nhl') {futureBound = bsFutureBound; pastBound = bsPastBound;}
		if(thisLeague == 'nfl') {futureBound = patsFutureBound; pastBound = patsPastBound;}
		if(thisLeague == 'nba') {futureBound = csFutureBound; pastBound = csPastBound;}
		if(!((thisGame < futureBound) && (thisGame > pastBound))) {
			gameDetails.splice(i, 1);
		}
	}
	//Print scoreboards, accounting for MLB doubleheaders
	for(var i = 0; i < gameDetails.length; i++) {
		if(nesnTeams[1].league == 'mlb') {
			if (gameDetails[i].gameLeague == 'mlb' && gameDetails[i].gameNumber == '1') {g = 0;}
			else if (gameDetails[i].gameLeague == 'mlb' && gameDetails[i].gameNumber == '2') {g = 1;}
			else if (gameDetails[i].gameLeague == 'nhl') {g = 2;}
			else if (gameDetails[i].gameLeague == 'nfl') {g = 3;}
			else if (gameDetails[i].gameLeague == 'nba') {g = 4;}
		} else {
			if (gameDetails[i].gameLeague == 'mlb') {g = 0;}
			else if (gameDetails[i].gameLeague == 'nhl') {g = 1;}
			else if (gameDetails[i].gameLeague == 'nfl') {g = 2;}
			else if (gameDetails[i].gameLeague == 'nba') {g = 3;}
		}
		scoreboardBuilder(gameDetails[i].gameLeague, g);
	}
}

$j(document).ready(function() {
	if($j('body.home')[0]) {
		scoreboardAutomator();
	}
});

/*Lightbox for Video RSS*/

function lightboxLinks(title, video) {
    $j('.video-promo li:last').find('a').click(function() {
        lightboxRSS(title, video);
        return false;
    });
}

// Assign Lightbox functionality
function lightboxRSS(title, video) {
        $j('body').append('<div id="lightbox-background" style="filter:alpha(opacity=0)"></div>');
        $j('body').append('<div id="lightbox-window" style="filter:alpha(opacity=0)"><span class="title">' + title + '<span class="close">Close X</span></span><div id="flashbox"></div></div>');
        $j('#lightbox-background').animate({
            opacity: 0.5
        }, 500);
        $j('#lightbox-window').animate({
            opacity: 1.0
        }, 500);
        $j('.close').click(function() {
            $j('#lightbox-background').remove();
            $j('#lightbox-window object').remove();
            $j('#lightbox-window').remove();
        });
        $j('#lightbox-background').click(function() {
            $j('#lightbox-background').remove();
            $j('#lightbox-window object').remove();
            $j('#lightbox-window').remove();
        });
        $j('#flashbox').flash({
			swf: video,
			width: '640',
			height: '392',
			flashvars: {
				autoStart: 'true'
			}
		});
}

// Write JSON to Page
function blipJSON(data) {
    $j.each(data, function (i, post) {
		var img = 'http://cdn.nesn.com/cat/cat_video_120.jpg';
		if(post['img']) {
			img = post['img'];
		}
		$j('.video-promo').append('<li><a href="http://www.nesn.com/video/" target="_blank"><img src="' + img + '" /></a><a href="http://www.nesn.com/video/">' + post['title'] + '</a></li>');
        lightboxLinks(post['title'], post['url']);
    });
    $j('.video-promo').append('<li class="read-more"><a href="http://www.nesn.com/video/">More Video &raquo;</a></li>');
}

// Get JSON
$j(document).ready(function() {
    if($j('.video-promo')[0]) {
        $j.ajax({
            dataType: 'jsonp',
            jsonpCallback: 'blipJSON',
            url: 'http://proxy.nesn.com/exports/ncomvideo-bliptv.js'
        });
    }
});

/*WordPress JSON*/

function nesnJSON(data) {
	if($j('.photo-promo')[0]) {
		$j.each(data, function (i, post) {
			if(i==0 || i==1) {
				var img = 'http://cdn.nesn.com/cat/cat_photo_gallery_120.jpg';
				if (post['img']) {
					img = post['img'];
				}
				$j('.photo-promo').append('<li><a href="' + post['link'] + '?gamma" target="_blank"><img src="' + img + '" /></a><a href="' + post['link'] + '?gamma">' + post['title'] + '</a></li>');
			}
		});
		$j('.photo-promo').append('<li class="read-more"><a href="http://www.nesn.com/photo-gallery/">More Photos &raquo;</a></li>');
	}
	if($j('.fox-sports')[0]) {
		$j.each(data, function (i, post) {
			if(i==3) {
				var img = 'http://cdn.nesn.com/cat/cat_fox_sports_120.jpg';
				$j('.fox-sports').append('<li><a href="' + post['link'] + '" target="_blank"><img src="' + img + '" /></a><a href="' + post['link'] + '" target="_blank">' + post['title'] + '</a></li>');
			}
		});
	}
	if($j('body .terra-sports')[0]) {
		$j.each(data, function (i, post) {
			if(i==4) {
				var img = 'http://cdn.nesn.com/cat/cat_terra_sports_120.jpg';
				$j('body .terra-sports').append('<li><a href="' + post['link'] + '" target="_blank"><img src="' + img + '" /></a><a href="' + post['link'] + '" target="_blank">' + post['title'] + '</a></li>');
			}
		});
	}
}

$j(document).ready(function() {
    if($j('.photo-promo')[0] || $j('.fox-sports')[0]) {
        $j.ajax({
            dataType: 'jsonp',
            jsonpCallback: 'nesnJSON',
            url: 'http://media.nesn.com/wp-content/themes/carrington-jam-1.3/typepad-templates/nesn-json.js?callback=?nesnJSON'
        });
    }
});

/*OpenSearch*/

$j(document).ready(function(){
	if($j('#addopensearch')[0]) {
		$j('#addopensearch').click(function(){
			window.external.AddSearchProvider('http://www.nesn.com/opensearch.xml');
		});
	}
});

/*WordPress Pagination*/

$j(document).ready(function() {
	if($j('.pagination')[0]) {
		$j('.pagination span').each(function(i){
			if($j(this).parent().get(0).tagName == 'P') {
				$j(this).addClass('current');
			}
		});
	}
});

/*Countdown Clocks*/

$j(document).ready(function() {
	if($j('#gamma #countdown-stanley-cup')[0]) {
		var sCup = $.countdown.UTCDate(-4, 2011, 5, 18, 11);
		function gameTime() {
			$j('#countdown-stanley-cup').empty().append('<a href="http://www.nesn.com/boston-bruins/" id="countdown-stanley-cup">Boston Bruins Live Blog &raquo;</a>');
		}
		$j('#countdown-stanley-cup').countdown({until: sCup, format: 'HMS', onExpiry: gameTime, labels: ['Years','Months','Weeks',' Days, ',' Hours, ',' Mins, ',' Secs'], labels1: ['Year','Month','Week',' Day, ',' Hour, ',' Min, ',' Sec']});
	}
});

/*Sponsor Graphics*/

$j(document).ready(function() {
	if($j('#beta .bostons-greatest-sports-moment')[0]) {
        $j('#beta .bostons-greatest-sports-moment').append('<div class="sponsor"><a href="http://www.nissanusa.com/?ref=nesn" class="external"><img src="http://cdn.nesn.com/img/sponsors/nissan_88x31.png" alt="Nissan" /></a></div>');
    }
	if($j('#beta .nesn-daily')[0]) {
		$j('#beta .nesn-daily').append('<div class="sponsor"><a href="http://www.sunlife.com/?ref=nesn" class="external"><img src="http://cdn.nesn.com/img/sponsors/sunlife_88x31.png" alt="SunLife" /></a></div>');
	}
	if($j('#beta .the-fours-trivia-question-of-the-day')[0]) {
		$j('#beta .the-fours-trivia-question-of-the-day').append('<div class="sponsor"><a href="http://www.thefours.com/?ref=nesn" class="external"><img src="http://cdn.nesn.com/img/sponsors/the_fours_88x31.png" alt="The Four&rsquo;s" /></a></div>');
	}
	if($j('#beta .beth-israel-deaconess-healthy-is')[0]) {
		$j('#beta .beth-israel-deaconess-healthy-is').append('<div class="sponsor"><a href="http://bidmc.org/walking?ref=nesn" class="external"><img src="http://cdn.nesn.com/img/sponsors/bidmc_88x31.png" alt="Beth Israel Deaconess Healthy Is" /></a></div>');
	}
	if($j('#beta .eastern-bank-leading-off')[0]) {
		$j('#beta .eastern-bank-leading-off').append('<div class="sponsor"><a href="http://www.easternbank.com/?ref=nesn" class="external"><img src="http://cdn.nesn.com/img/sponsors/eblo_88x31.png" alt="Eastern Bank Leading Off" /></a></div>');
	}
});

/*Mobile Cookie*/

$j(document).ready(function() {
	if($j('#delete-desktop')[0]) {
		$j('#delete-desktop').click(function() {
			delCookie('desktop');
		});
	}
});

/*External Links*/

$j(document).ready(function() {
	if($j('.external')[0]) {
		$j('.external').click(function() {
			open(this.href);
			return false;
		});
	}
});

/*Table Stripes*/

$j(document).ready(function() {
	if($j('.table-content')[0]) {
		if ($j('.table-content')) {
			$j('.table-content tbody tr:odd').addClass('even');
			$j('.table-content tbody td:first-child').addClass('nesn');
		}
	}
});

/*Link Icons*/

$j(document).ready(function() {
	if($j('#alpha a.video')[0]) {$j('#alpha a.video').append('<span class="block-10 video-10"></span>');}
	if($j('#gamma a.video')[0]) {$j('#gamma a.video').append('<span class="block-10 video-10"></span>');}
	if($j('#alpha a.photo-gallery')[0]) {$j('#alpha a.photo-gallery').append('<span class="block-10 photo-gallery-10"></span>');}
	if($j('#gamma a.photo-gallery')[0]) {$j('#gamma a.photo-gallery').append('<span class="block-10 photo-gallery-10"></span>');}
});

/*Share Strip Icons*/

$j(document).ready(function() {
	if($j('#share-strip')[0]) {
		function hoverIn(app) {
    		function _f() {
        		$j(this).find('span').removeClass(app + '-gray-16').addClass(app + '-gray-16-hover');
    		}
    	return _f;
		}
		function hoverOut(app) {
    		function _f() {
        		$j(this).find('span').removeClass(app + '-gray-16-hover').addClass(app + '-gray-16');
    		}
    	return _f;
		}
		$j('#share-strip a:eq(0)').hover(hoverIn('facebook'), hoverOut('facebook'));
		$j('#share-strip a:eq(1)').hover(hoverIn('twitter'), hoverOut('twitter'));
		$j('#share-strip a:eq(2)').hover(hoverIn('email'), hoverOut('email'));
		$j('#share-strip a:eq(3)').hover(hoverIn('digg'), hoverOut('digg'));
		$j('#share-strip a:eq(4)').hover(hoverIn('delicious'), hoverOut('delicious'));
		$j('#share-strip a:eq(5)').hover(hoverIn('fark'), hoverOut('fark'));
		$j('#share-strip a:eq(6)').hover(hoverIn('buzz'), hoverOut('buzz'));
	}
});

/*JS Photo Gallery*/

$j(document).ready(function() {
	if($j('.photo-gallery-mobile #pages')[0]) {
		$j('#pages p:eq(0)').addClass('current');
		$j('#pages p').bind('click', function(e){
			var pNum = $j('#pages p').size();
			var pThis = $j(this).index();
			if((pNum - 1) == pThis) {
				var nextP = $j('#pages p:eq(0)');
			} else {
				var nextP = $j(this).next();
			}
			$j('#pages p.current').removeClass('current').addClass('push out');
			nextP.addClass('current push in');
		});
	}
});
