(function( $ ){

	function LiveGames(_options) {
		this.options = {
			"countdownRate" : 500,
			"refreshRate" : 15000,
			"cycleRate" : 6000,
			"cycleSpeed" : 500

		};

		if (_options) {
			$.extend(this.options, _options);
		}

		this._create();
	}

	LiveGames.prototype = {

		_create: function() {
			this.loopActive = false;

			this.refreshActive = true;
			this.updateActive = true;

			this.games = [];
			this.cdList = {};

			var self = this;

			this.h_tpl = $('#headerLivegamesTemplate');
			this.h_cont = $('#headerLivegames');

			this.h_forecast = $('#headerLiveForecastTemplate');

			this.lg_tpl = $('#gameTemplate');
			this.lg_cont = $('#gameContainer');

			this._gameCheckLoop();

			if (this.lg_tpl) {
				this._countdownLoop();
			}

			this._cycleLoop();

/*
			this.e_next.bind('click', function(event) {
				return self._nextEvent(event, this);
			});
*/
		},

		_cycleLoop : function() {
			var self = this;
			self._cycleRun();
			setTimeout(function() { self._cycleLoop(); }, this.options.cycleRate);
		},

		_cycleRun : function() {
			if (this.refreshActive || this.updateActive) {
				return;
			}

			var activeItems = this.h_cont.find('.active');
			if (activeItems.length < 2) return;

			var ni = activeItems.eq(0);
			var h = ni.height();

			var self = this;
			this.h_cont.animate({'bottom':  h}, this.options.cycleSpeed, 'linear', function() {
				self.h_cont.append(ni).animate({'bottom': 0}, self.options.cycleSpeed, 'linear');
			});

//			this.h_cont.prepend(ni).css('bottom', h + 'px').animate({'top': 0}, this.options.cycleSpeed);

		},

		_gameCheckLoop : function() {

			this.updateActive = true;

			var self = this;

			$.get(this.options.ajaxURL, {r: Math.random()} , function(d) { self._gameCheckCallback(d); }, 'json');
		},

		_gameCheckCallback : function(gameData) {
			var self = this;

			if (gameData.nextCheck) {
				setTimeout(function() { self._gameCheckLoop(); }, gameData.nextCheck);
			}

			this.h_cont.empty();
			this.lg_cont.empty();

			var gameList = gameData.gameList;
			this.games = [];
			this.cdList = {};

			var s = false;

			this.h_forecast.hide();

			if (gameList && gameList.length) {
				var l = gameList.length;
				for (var i = 0; i < l; ++i) {
					var gameInfo = gameList[i];

					if (this._addGame(gameInfo)) {
						s = true;
					}
				}
				$('#noGames').hide();
			} else {
				$('#noGames').show();
			}

			if (s) {
				this._startRefreshLoop();
			} else {
				if (gameData.nextGame) {
					this.h_forecast.show();

					this.h_forecast.find('.liveLink a').attr('href', gameData.nextGame.link);

					this.h_forecast.find('div.liveboxImgA img').attr('src', gameData.nextGame.slogoA);
					this.h_forecast.find('div.liveboxImgB img').attr('src', gameData.nextGame.slogoB);

					this.h_forecast.find('div.liveboxDate').text(gameData.nextGame.dateString);
//					this.h_forecast.find('div.liveboxTVLogo img').attr('src', gameData.nextGame.tvlogo1); 

					this.h_forecast.find('div.liveboxTitleA').text(gameData.nextGame.nameA);
					this.h_forecast.find('div.liveboxTitleB').text(gameData.nextGame.nameB);
				}
			}


			this.updateActive = false;
		},

		_startRefreshLoop : function() {
			if (this.loopActive) {
				return;
			}
			this.loopActive = true;

			this._refreshLoop();
		},

		_gameFind : function (gamesId) {
			var l = this.games.length;
			for (var i = 0; i < l; ++i) {
				if (this.games[i] == gamesId) {
					return i;
				}
			}
			return -1;
		},

		_addGame : function(gameInfo) {
			this._createLGElement(gameInfo);
			this._updateGElement(gameInfo);

			if (gameInfo.live < 2) {
				this._addCountdown(gameInfo.gamesId, gameInfo.cd);
			}

			if (gameInfo.live > 2) {
				return false;
			}

			this._createHElement(gameInfo);

			var gamesId = gameInfo.gamesId;

			if (gameInfo.delay == 0) {
				if (this._gameFind(gamesId) == -1) {
					this.games.push(gamesId);
				}
				return true;
			}

			var self = this;
			setTimeout(function() {
				if (self._gameFind(gamesId) == -1) {
					self.games.push(gamesId);
				}
				self._startRefreshLoop();
			}, gameInfo.delay);

			return false;
		},

		_createHElement : function(gameInfo) {
			var elemId = 'headerLivegames_' + gameInfo.gamesId;

			var gameEl = $('#' + elemId);
		
			if (gameEl.length) return;

			if (!this.h_tpl.length) return;

			var element = this.h_tpl.clone().attr('id', elemId);

			element.find('.liveLink a').attr('href', gameInfo.link);

			element.find('div.liveboxImgA img').attr('src', gameInfo.slogoA);
			element.find('div.liveboxImgB img').attr('src', gameInfo.slogoB);

			element.find('div.liveboxTitleA').text(gameInfo.nameA);
			element.find('div.liveboxTitleB').text(gameInfo.nameB);

//			team1.find('a').attr('href', gameInfo.linkA);
//			team2.find('a').attr('href', gameInfo.linkB);

			this.h_cont.append(element);

			element.show();

			this._updateHElement(gameInfo);

		},

		_createLGElement : function(gameInfo) {
			var elemId = 'game_' + gameInfo.gamesId;

			var gameEl = $('#' + elemId);
		
			if (gameEl.length) return;

			if (!this.lg_tpl.length) return;

			var element = this.lg_tpl.clone().attr('id', elemId);

			element.find('.livelink a').attr('href', gameInfo.link);

			var team1 = element.find('.game_team1');
			team1.find('span').text(gameInfo.nameA);
			team1.find('a').attr('href', gameInfo.linkA);
			team1.find('img').attr('src', gameInfo.logoA);

			var team2 = element.find('.game_team2');
			team2.find('span').text(gameInfo.nameB);
			team2.find('a').attr('href', gameInfo.linkB);
			team2.find('img').attr('src', gameInfo.logoB);

			element.show();
			this.lg_cont.append(element);

			this._updateLGElement(gameInfo);
		},

		_refreshLoop : function() {
			if (!this.games.length) {
				this.loopActive = false;
				return;
			}

			this.refreshActive = true;

			var gamesId = this.games.join(',');

			var self = this;
			$.get(this.options.ajaxURL, {"games": gamesId, "r": Math.random()}, function(d) { self._refreshResult(d); }, 'json');
		},

		_refreshResult : function(data) {
			var chat = false;

			this.h_cont.find('.liveHdBox').removeClass('active');

			for (var id in data) {
				var gameInfo = data[id];

				this._updateGElement(gameInfo);
				this._updateHElement(gameInfo);
				this._updateLGElement(gameInfo);

				if (gameInfo.live == 1 || gameInfo.live == 2) {
					chat = true;
				} else {
					var i = this._gameFind(parseInt(gameInfo.gamesId));
		
					if (i != -1) {
						this.games.splice(i,1);
					}
				}
			}

			var c = $('#chatOn');
			if (c.length && c.liveChat) {
				if (chat) {
					c.liveChat('enable');
				} else {
					c.liveChat('disable');
				}
			}

			this.refreshActive = false;

			var activeItems = this.h_cont.find('.active');
			if (activeItems.length) {
				this.h_forecast.hide();

				var h = activeItems.eq(0).height();
				this.h_cont.css('height', (h * activeItems.length) + 'px');
			}

			var self = this;
			setTimeout(function() { self._refreshLoop(); }, this.options.refreshRate);
		},

		_updateGElement : function(data) {
			var table = document.getElementById('gameScore_' + data.gamesId);
			if (!table) return;

			while (table.rows.length > 1) {
				table.deleteRow(1);
			}

			var c = data.history.length;

			for (var i = 0; i < c; i++) {
				var item = data.history[i];
				var row = table.insertRow(-1);

				row.insertCell(0).innerHTML = item.set;
				row.insertCell(1).innerHTML = item.hours + ':' + item.minutes;
				row.insertCell(2).innerHTML = item.pointsA + ':' + item.pointsB;
				row.insertCell(3).innerHTML = item.resA + ':' + item.resB;
			}
		},

		_updateLGElement : function(gameInfo) {

			var elemId = 'game_' + gameInfo.gamesId;
			var element = $('#' + elemId);

			if (!element.length) return;

			var table = element.find('table.livematch').get(0);

			while (table.rows.length > 1) {
				table.deleteRow(1);
			}
		
			var c = gameInfo.history.length;
			for (var i = 0; i < c; i++) {
				var item = gameInfo.history[i];
				var row = table.insertRow(-1);
				row.insertCell(0).innerHTML = item.set;
				row.insertCell(1).innerHTML = item.hours + ':' + item.minutes;
				row.insertCell(2).innerHTML = item.pointsA + ':' + item.pointsB;
				row.insertCell(3).innerHTML = item.resA + ':' + item.resB;
			}
	
			var setIconA = element.find('.game_score1');
			var setIconB = element.find('.game_score2');

			var setsA = gameInfo.history[c-1].resA;
			var setsB = gameInfo.history[c-1].resB;

			setIconA.text(setsA);
			setIconB.text(setsB);

			setIconA.removeClass('scorewinner').removeClass('scoreloser');
			setIconB.removeClass('scorewinner').removeClass('scoreloser');

			if (setsA == 3) {
				setIconA.addClass('scorewinner');
				setIconB.addClass('scoreloser');
			} else if (setsB == 3) {
				setIconB.addClass('scorewinner');
				setIconA.addClass('scoreloser');
			}

			var cd = element.find('.livecountdown');
			var cdt = element.find('.countdownname');
	
			if (gameInfo.live < 2) {
				$(table).hide();
				cd.show();
				cdt.show();
			} else {
				$(table).show();
				cd.hide();
				cdt.hide();
			}
		},

		_updateHElement : function(gameInfo) {
			var elemId = 'headerLivegames_' + gameInfo.gamesId;

			var gameEl = $('#' + elemId);
		
			if (!gameEl.length) return;

			if (gameInfo.live != 2) {
				gameEl.hide();
				return;
			}

			gameEl.show();
			gameEl.addClass('active');

			var setItem = gameEl.find('.liveboxSet');

			setItem.removeClass('current');

			var c = gameInfo.history.length;

			if (c > 1) {
				setItem.eq(c-2).addClass('current');
			}

			gameEl.find('.liveboxSets').find('img').attr('src', this.options.imagePath + '/common/liveSet0.png');

//			var setsA = gameInfo.history[c-1].resA;
//			var setsB = gameInfo.history[c-1].resB;
//			gameEl.find('.gameScore').text(setsA + ':' + setsB);
//			gameEl.find('.gameSet').text(Math.max(1, c-1));

			var i = 0;
			for (; i < c-1; i++) {
				var item = gameInfo.history[i];

				if (item.win) {
					setItem.eq(i).find('img').eq(item.win - 1).attr('src', this.options.imagePath + '/common/liveSet1.png');
				}

				setItem.eq(i).find('span').html('<br />'+item.pointsA+'<br />'+item.pointsB+'<br />');
			}
			for (; i < setItem.length; i++) {
				setItem.eq(i).find('span').html('<br />-<br />-<br />');
			}

		},


		_addCountdown : function(id, seconds) {
			if (this.cdList[id]) {
				return;
			}

			var cd = {};

			var now = new Date;
			cd.end = now.getTime() + seconds * 1000;

			this.cdList[id] = cd;
		},

		_countdownLoop : function() {
		
			var now = new Date;
			var cdDate = new Date;
		
		//	var tz = now.getTimezoneOffset() * 60 * 1000;

			for (i in this.cdList) {
				if (!this.cdList[i]) continue;

				var remain = this.cdList[i].end - now.getTime();
				var str = 'Loading';

				if (remain >= 0) {
					cdDate.setTime(remain);
			
					var h = cdDate.getUTCHours();
					var m = cdDate.getUTCMinutes();
					var s = cdDate.getUTCSeconds();
			
					if (m < 10) m = '0' + m;
					if (s < 10) s = '0' + s;
			
					str = h + ':' + m + ':' + s;
				}
		
				$('#game_' + i).find('.livecountdown').html(str);
			}

			var self = this;
			setTimeout(function() { self._countdownLoop(); }, this.options.countdownRate);

		}
	};


	$.liveGames = function(_options) {
		new LiveGames(_options);
	};

})( jQuery );

