/*
 * Scoreboard Module for NBA.de 1.03
 * Copyright 2010
 *
 * Author : Nicholas Ortenzio
 * Created : 4/15/2010
 * Last modified : 4/24/2010
 *
 * Requires jQuery, jQuery Tools, CooQuery
 */

(function($){

	$.fn.Scoreboard = function(urls) {

		var init = function() {

			var $this = $(this);
			var currentGameStatus = 3;
			var gsInterval = $this.data("gsInterval");
			
			$("#upcoming").killInterval();

			$.get(urls.scoreboard, function(data) {
				$this.html(data); 

				var ti = parseInt(($.readCookie("scoreboard_tab")==null) ? 1 : $.readCookie("scoreboard_tab"),10);

				$("#scoreboard > ul").tabs("#scoreboard > div", {
					initialIndex : ti,
					onClick : function(event, tabIndex) { $.setCookie("scoreboard_tab", tabIndex, {duration:.02}); }	 
				});

				$("#upcoming").loadInterval({url:urls.slowUpdate, seconds:300, stopOnError:true});
				
				gsInterval = setInterval(function(){	

					$.ajax({url:urls.gameStatus, dataType:'text', success:function(data){
						var gameStatus = $.trim(data);
						if (gameStatus == currentGameStatus) { return; }
						$("#upcoming").killInterval();
						currentGameStatus = gameStatus;
						switch (gameStatus) {
							case "2" : 
								$("#upcoming").loadInterval({url:urls.liveUpdate, seconds:5, stopOnError:false});				
								break;
							default : 
								$("#upcoming").loadInterval({url:urls.slowUpdate, seconds:300, stopOnError:true});
								break;
						}
					}});
				}, 30000);

				$this.data("gsInterval", gsInterval);

			});

		};

		return this.each(init).addClass('module');

  };

})(jQuery);
