/**
 * LiveScore Core Class
 *
 * @author Pascal Opitz
 */
var LiveScore = new function() {
	this.NS = 'LiveScore';
	var _drFunctions = [];
	
	/**
	 * takes functions to be executed when DOM is ready
	 * 
	 * @param func function
	 */
	var _register = function(func) {
		_drFunctions = $(_drFunctions).add(func);
	}
	this.register = _register;

	$(document).ready(function() {
			$('body').addClass('js');
		
			$(_drFunctions).each(function() {
				this.call();
			});
		}
	);
	

	/**
	 * returns hash
	 */
	var _hash = function() {
		var d = new Date();
		return d.valueOf() + '--' + Math.random();
	}
	
	this.hash = _hash;
}


/**
 * Handles the Game infos for football and rugby 
 * 
 * @author Pascal Opitz
 */
LiveScore.AjaxInfo = new function() {
	this.NS = 'LiveScore.AjaxInfo';
	var _transition_blocked = false;
	var _prefix = 'Hide ';
	
	var _showInfo = function(link, tr) {
		$(document).trigger('AjaxInfo_showStart');
		
		var _callBack = function(response) {
			// removed scrolling
			//$(window).scrollTo(tr, 700);
			_transition_blocked = false;
			link.text(_prefix + link.text());
			link.addClass('expanded');
			$(document).trigger('AjaxInfo_animationComplete');
		}

		_transition_blocked = true;
		tr.next().show();
		tr.next().find('div.game-info').slideDown('normal', _callBack);
	}
	
	var _hideInfo = function(tr) {
		$(document).trigger('AjaxInfo_hideStart');

		var _callBack = function(response) {
			var link = tr.parent().prev('tr').find('td.action a[class!=stats-link]');
			link.text(link.text().replace(_prefix, ''));
			link.removeClass('expanded');
			tr.remove();
			$(document).trigger('AjaxInfo_hideComplete');
		}
		
		tr.find('div.game-info').slideUp('fast', _callBack);
	}
	
	var _loadInfo = function(link, tr) {
		LiveScore.Notification.show('AjaxInfo.loadStart');
		
		var _callBack = function(response) {
			$(response).insertAfter(tr);
			tr.next().find('div.game-info').hide();
			_showInfo(link, tr);
			$(document).trigger('AjaxInfo_loadComplete', link);
			LiveScore.Notification.hide();
		}
		
//		$.get(link.attr('href'), {'ajax': true, 'hash': LiveScore.hash()}, _callBack, 'html');
		$.get(link.attr('href'), {'ajax': true}, _callBack, 'html');

	}

	/**
	 * Show one info, hide all others
	 */
	var _triggerInfo = function() {
		var _link = $(this);
		var _tr = $(_link.parents('tr')[0]);
		
		if(!_transition_blocked) {
			if(_tr.next().find('td.game-info-container').length == 0) {
				_loadInfo(_link, _tr);
			}

			$.each($('td.game-info-container'), function() {
				_hideInfo($(this));
			});
		}
		return false
	}
	
	/**
	 * This is based on event delegation, otherwise we'd have to re-append 
	 * the handlers every time the AJAX markup is updated
	 */
	var _isDelegate = function (e) { 
		var _tr = $(e.target).parents('tr.details')[0];
		var _link = false;
		var _a_target = $(e.target).parents('a.stats-link');
		
		if(_tr && !_a_target.length) {
			_link = $(_tr).find('td.action a[class!=stats-link]')[0];
		}
		
		return _link;
    }

	var _clickDelegation = function(e) {
		if(_link = _isDelegate(e)) {
			_triggerInfo.call(_link);
			e.preventDefault(); 
			return false;			
		}
	}
	
	var _init = function() {
		$('div#liveupdate-content').bind('click', _clickDelegation);
	}

	LiveScore.register(_init);
}


/**
 * Functionality for form on top of the page
 * 
 * @author Pascal Opitz
 */
LiveScore.DataControls = new function() {
	this.NS = 'LiveScore.DataControls';
	var _dateFormat = 'D d M y';
	var _self = this;
	var _one_day = 1000*60*60*24;
	this.game_details_id = false;
	var _datePrev = false;
	var _dateNext = false;	

	/**
	 * This function returns GMT instead of local time
	 * Needed for the Datepicker to work with GMT
	 */
	var _getGMTDate = function() {
		return new Date(Date.parse(new Date().toGMTString().replace('GMT', '')));
	}

	/**
	 * Sets game ID when info is shown for single game
	 */
	var _setGameDetailsId = function(e, data) {
		var _loc = $(data).attr('href');
		var _reg = /\?game_id\=([\d]+)/i;
		var _matches = _reg.exec(_loc);
		
		if(_matches.length > 1) {
			_self.game_details_id = _matches[1];
		}
	}
	
	/**
	 * Unsets game ID when info is hidden for single game
	 */
	var _unsetGameDetailsId = function() {
		_self.game_details_id = false;
	}
	
	/**
	 * Submit the form via _sendFormAction
	 */
	var _submitForm = function() {
		var _params = $('form.data-controls').serialize();
		window.location.href = '/main/sport?' + _params;
	}
	
	/**
	 * Serializes form and ajax loads response
	 */
	var _sendFormAction = function(_callBack) {
		var _action = $('form.data-controls').attr('action');
		var _params = $('form.data-controls').serialize();
		_params += '&ajax=true';
		
		if(_self.game_details_id) {
			_params += ('&game_details_id=' + _self.game_details_id);
		}

		//_params += ('&hash=' + LiveScore.hash());

		$.get(_action, _params, _callBack, 'text');
	}
	this.sendFormAction = _sendFormAction;
	
	var _calculateDate = function() {
		$('#date-options').datepicker("hide", 'fast');
		_submitForm();
	}
	
	var _prevDate = function() {
		_setDate('prev');
		return false;
	}
	
	var _nextDate = function() {
		_setDate('next');
		return false;
	}

	/**
	 * This calculates the date when the arrows are clicked
	 */
	var _setDate = function(type) {

		$('form.data-controls input[name=pn]').val(type);
		_submitForm();
		return false;
	}
	
	
	/**
	 * Init function attaches date picker and other event handlers
	 */
	var _init = function() {
		var _options = {
			'dateFormat': _dateFormat,
			'currentDateObj' : _getGMTDate,
			'showOtherMonths': true,
		    'showOn': "both", 
		    'buttonImage': "/images/calendar_icon.gif", 
		    'buttonImageOnly': true 
		}
		
		$('#date-options').datepicker(_options);		
		$('form.data-controls').find('select').bind('change', _submitForm);
		$('form.data-controls').find('input[type=text]').bind('change', _calculateDate);
		$('form.data-controls').find('input[name=date_prev]').bind('click', _prevDate);
		$('form.data-controls').find('input[name=date_next]').bind('click', _nextDate);
		$(document).bind('AjaxInfo_loadComplete', _setGameDetailsId);
		$(document).bind('AjaxInfo_hideStart', _unsetGameDetailsId);
	}

	LiveScore.register(_init);
}


/**
 * Live update to refresh page content
 * 
 * @author Pascal Opitz
 */
LiveScore.LiveUpdate = new function() {
	this.NS = 'LiveScore.LiveUpdate';
	var _refreshTimer = false;
	var _refreshTimeout = 30000;
	var _timer = null;

	var _initTimer = function() {
		_timer = window.setTimeout(_refresh, _refreshTimeout);
	}

	var _loadblockStart = function() {
		_initTimer();
	}

	var _loadblockRemove = function() {
		_stopTimer();
	}

	var _stopTimer = function() {
		if(_timer) {
			window.clearTimeout(_timer);
		}
	}

	var _refresh = function() {
		LiveScore.Notification.show('LiveUpdate_refreshStart');

		var _callBack = function(response) {
			$(document).trigger('LiveUpdate_refreshComplete');
			LiveScore.Notification.hide();
			$('#liveupdate-content').html(response);
		}

		LiveScore.DataControls.sendFormAction(_callBack);
	}
	
	/**
	 * Timer needs to be stopped when ajax content is loaded, and resumed after
	 */
	var _init = function() {
		$(document).bind('LiveUpdate_refreshComplete', _initTimer);
		$(document).bind('AjaxInfo_showStart', _loadblockStart);
		$(document).bind('AjaxInfo_animationComplete', _loadblockRemove);
		$(document).bind('DataControls_refreshStart', _loadblockStart);
		$(document).bind('DataControls_refreshComplete', _loadblockRemove);
		_initTimer();
	}
	
	LiveScore.register(_init);
}


/**
 * Simple notification class
 * 
 * @author Pascal Opitz
 */
LiveScore.Notification = new function() {
	this.NS = 'LiveScore.Notification';

	this.show = function(message) {
		//$('.system-notification-container').text(message).show();
		$('.system-notification-container').text('Loading...').show();
	}
	
	this.hide = function() {
		var _do = function(){
			$('.system-notification-container').hide();
		}
		
		window.setTimeout(_do, 800);
	}
	
	var _init = function() {
		$('body').append('<div class="system-notification-container"></div>');
		$('.system-notification-container').hide();
	}

	LiveScore.register(_init);
}
