var HPScoreboard = {
	load : function(data) {

		var games = data.games;
		
		if (games.length == 0) { return; }

		$("#hp-scoreboard-games .today.games .first").removeClass("first");

		for (var i=0, num_games = games.length; i < num_games; i++) {

			var game = games[i];

			var $hp_scoreboard_game = $("#hp-scoreboard-games .today.games #hp-scoreboard-game-" + game.game_id);

			if ($hp_scoreboard_game.length == 0) { continue; }
			

			// Save current game status in case we need to move this game when it goes live
			var old_game_status = 1;
			
			if ($hp_scoreboard_game.hasClass("live")) {
				old_game_status = 2;
			} else if ($hp_scoreboard_game.hasClass("final")) {
				old_game_status = 3;
			}
			
			
			// if game status has changed, move game to correct position
			if (game.game_status != old_game_status && games.length > 1) {

				if ($("#hp-scoreboard-games .today.games .game:eq(" + i + ")").attr("id") != $hp_scoreboard_game.attr("id")) {					
					if (games[i + 1] != null) {
						$hp_scoreboard_game.insertBefore("#hp-scoreboard-games .today.games .game:eq(" + i + ")");
					} else {
						$hp_scoreboard_game.appendTo("#hp-scoreboard-games .today.games");
					}
				}

			}
			

			// Set game status class for game
			$hp_scoreboard_game.removeClass("pre live final pre_has_broadcasters live_has_broadcasters final_has_broadcasters");

			var new_class = "pre";

			if (game.game_status == 2) {
				new_class = "live";
			} else if (game.game_status == 3) {
				new_class = "final";
			} else {
				new_class = "pre";
			}
			
			if (game.has_broadcasters) { new_class = new_class + "_has_broadcasters " + new_class; }
			
			$hp_scoreboard_game.addClass(new_class);
			

			// Set status text
			$(".status_text", $hp_scoreboard_game).html(game.status_text);


			// Set visiting score if score span exists, if not, create span, then update
			$visiting_score = $(".scoring ." + game.visiting_team.teamcode + " .score", $hp_scoreboard_game);
			if ($visiting_score.length == 0 && game.game_status > 1) { 
				$visiting_team = $(".scoring ." + game.visiting_team.teamcode, $hp_scoreboard_game);	

				$visiting_score = $("<span class='score'></span>");
				$visiting_score.appendTo($visiting_team);
			}

			if (game.game_status > 1) {
				$visiting_score.html((game.visiting_team.score ? game.visiting_team.score : 0));

				if (game.visiting_team.score > game.home_team.score) {
					$visiting_score.addClass("winning");
				} else {
					$visiting_score.removeClass("winning");
				}
			}
			

			// Set home score if score span exists, if not, create span, then update
			$home_score = $(".scoring ." + game.home_team.teamcode + " .score", $hp_scoreboard_game);
			if ($home_score.length == 0 && game.game_status > 1) { 
				$home_team = $(".scoring ." + game.home_team.teamcode, $hp_scoreboard_game);	

				$home_score = $("<span class='score'></span>");
				$home_score.appendTo($home_team);
			}

			if (game.game_status > 1) {
				$home_score.html((game.home_team.score ? game.home_team.score : 0));

				if (game.home_team.score > game.visiting_team.score) {
					$home_score.addClass("winning");
				} else {
					$home_score.removeClass("winning");
				}
			}
			

			// Set links
			var new_links = "";
			for(var j=0, num_links = game.links.length; j < num_links; j++) {
				new_links += ["<a href='", game.links[j][2], "' class='", game.links[j][0], "'>", game.links[j][1], "</a> "].join("");
			}

			$(".links", $hp_scoreboard_game).html(new_links);

			$hp_scoreboard_game = null;
			$visiting_score = null;
			$visiting_team = null;
			$home_score = null;
			$home_team = null;
		}
		
		$("#hp-scoreboard-games .today.games .game:eq(0)").addClass("first");
	}
};

(function($) {

	var gameDayStatus = 1;

	var loadGameDayStatusInterval = null;
	var loadGamesInterval = null;
	
	var latestSettings = null;
	
	$(function() {
		if ($("#hp-scoreboard-games .today.games").length > 0) { 
			setInterval(function() {

				$.ajax({ 
					url : "/stats/transform?xml=http://www.nba.de/stats/feeds/league/gameDayStatus.xhtml&xsl=http://www.nba.de/xsl/status.xsl",
					dataType : "text",
					success: function(data) {
						var oldGameDayStatus = gameDayStatus;

						gameDayStatus = data;

						if (oldGameDayStatus != gameDayStatus) {

							clearTimeout(loadGamesInterval);
							loadGames(latestSettings);
						}

					}
				});

			}, 20000);
		}
	});

	function loadGames(settings) {
		if (!settings) { return; }

		if ($("#hp-scoreboard-games .today.games").length > 0) { 

			var url = "/stats/transform?xml=http://www.nba.de/stats/feeds/league/miniScoreBoard.xhtml?" + settings.tz + "%26locale%3D" + settings.locale + "&xsl=http://www.nba.de/xsl/1.2/hpscoreboard_today_json.xsl";
			
			if (gameDayStatus == 2) {
				url = "/stats/transform?xml=http://www.nba.de/stats/feeds/league/liveMiniScoreBoard.xhtml?" + settings.tz + "%26locale%3D" + settings.locale + "&xsl=http://www.nba.de/xsl/1.2/hpscoreboard_today_json.xsl&q=" + (new Date()).getTime();
			}

			$.ajax({ 
				url : url,
				dataType : "script",
				complete : function(request, status) {
					if (gameDayStatus == 2) {
						if (status != "error") {
							loadGamesInterval = setTimeout(function() { loadGames(settings); }, 60000);
						} else { 
							loadGamesInterval = setTimeout(function() { loadGames(settings); }, 60000);
						}
					} else {
						loadGamesInterval = setTimeout(function() { loadGames(settings); }, 1800000);
					}
				}
			});

		}
	}
	
	$.fn.hpscoreboard = function(options) {
	
		// Set Settings
		var settings = $.extend({
			"locale" : "de",
			"tz" : escape("tz=GMT-5&dst=1"),
			"showPrevious" : false
		}, options);

		
		return this.each(function() {
		
			$this = $(this);
			$this.data('locale', settings.locale);
			$this.data('tz', settings.tz);

			if (settings.showPrevious) {
        var prevurl = "/stats/transform?xml=http://www.nba.de/stats/feeds/league/miniScoreBoard.xhtml?" + settings.tz + "%26locale%3D" + settings.locale + "&xsl=http://www.nba.de/xsl/1.2/hpscoreboard_previous.xsl .games";
        $this.find("#hp-scoreboard-games").load(prevurl, function(resp){
          $('#hp-scoreboard').nbaScroller();
        });
			} else {
				$this.find("#hp-scoreboard-games").load("/stats/transform?xml=http://www.nba.de/stats/feeds/league/miniScoreBoard.xhtml?" + settings.tz + "%26locale%3D" + settings.locale + "&xsl=http://www.nba.de/xsl/1.2/hpscoreboard.xsl .games");
				$this.find('.previous.button').addClass('get-yesterday').click(function(){
					var loadprevious = $(this).hasClass('disabled') && $(this).hasClass('get-yesterday');
					if (loadprevious) {
						$("#hp-scoreboard").hpscoreboard({locale:settings.locale, tz:settings.tz, showPrevious:true});
						$(this).removeClass('get-yesterday');
					}
				});
			}

			clearTimeout(loadGamesInterval);
			latestSettings = settings;
			loadGames(settings);

			if ($this.data("is_hpscoreboard")) { return; }


			$(".game", $this).live("mouseenter", function(event) {
				$game = $(this);

				$(".links", $game).slideDown('fast', function() { $game.addClass("show_links"); });				

			});

			$(".game", $this).live("mouseleave", function(event) {
				$game = $(this);

				$(".links", $game).slideUp('fast', function() { $game.removeClass("show_links"); });
			});

			$this.data("is_hpscoreboard", true);
		});
	};
	
})(jQuery);

