function LiveGameApp(){
	this.game_id						= 0;
	this.is_live						= 0;
	this.default_comment_per_page		= 20;
	this.default_refreshtime_comments	= 30000;

	this.comment_min_height				= 300;

	this.live_comm_ajax_url				= 'livegame_updates.php';

	this.handle_comment_timeout			= null;
	this.handle_textinfo_timeout		= null;

	this.state_current_page_updates		= 1;
	this.state_current_page_comments	= 1;
}



LiveGameApp.prototype.run_livegame_app = function(data){
	this.setUpConfig(data);
	this.setUpBasicEventsAndVisibility();
	this.restartTimer(true, true);
};

LiveGameApp.prototype.restartTimer = function(update_now, reset_pages){
	clearTimeout(this.handle_comment_timeout);
	if(this.game_id > 0){
		var ms = (update_now)?0:this.default_refreshtime_comments;
		var u_p = (reset_pages)?1:null;
		var c_p = (reset_pages)?1:null;
		this.ajax_timer(ms, u_p, c_p);
	}
}

LiveGameApp.prototype.setUpConfig = function(data){

	if(data==null){
		return;
	}
	var props = Array(
		'game_id', 
		'is_live', 
		'default_comment_per_page', 
		'default_refreshtime_comments', 
		'default_refreshtime_textupdates'
	);

	for(var i = 0, k = props.length; i<k; i++){
		var prop = props[i];
		if(typeof data[prop] != 'undefined'){
			this[prop] = data[prop];
		}
	}

};


LiveGameApp.prototype.ajax_timer = function(comment_refresh_time, u_pagenum, c_pagenum) { //TOFIX!!!!!!
	var that = this;

	if(u_pagenum == null){
		u_pagenum = this.state_current_page_updates;
	}
	this.state_current_page_updates = u_pagenum;

	if(c_pagenum == null){
		c_pagenum = this.state_current_page_comments;
	}

	this.state_current_page_comments = c_pagenum;

	this.handle_comment_timeout = setTimeout(
		function() { 
			that.set_loading_status(true);
			that.postGetData();
			/*
			$.post(
				that.live_comm_ajax_url, 
				{ 
					id		: that.game_id,
					type	: 1 + 2 + 4, // score/gamecomments + game updates + user comments
					pagestep: that.default_comment_per_page,
					c_pagenr: c_pagenum,
					u_pagenr: u_pagenum
				}, 
				function (data) { 
					that.map_data_xml(data);
					var u_1 = that.state_current_page_updates == 1; 
					var c_1 = that.state_current_page_comments == 1;
					if(that.is_live && (u_1 || c_1)){
						that.restartTimer(false, false);
					}else{
						// this.layoutCheckLive(); // done in map_data_xml
					}
					that.set_loading_status(false);
				}, 
				'xml'
			);
			*/
		}, 
		comment_refresh_time
	);
};

LiveGameApp.prototype.map_data_xml = function(data){
	var that = this;

	var was_live = this.is_live;
	var is_live	= parseInt($(data).find('islive').text());
	this.is_live = is_live;

	// alert(this.is_live);

	var was_stopped = (!this.is_live) && (this.is_live != was_live);

	this.layoutCheckLive();

	var c_comment_count_text	= $(data).find('totalcomments_c').text();
	var c_selectorpages 		= $(data).find('selectorpages_c').text();
	var c_page_comments_html	= $(data).find('pagecomments_c').text();
	var c_currentpage			= parseInt($(data).find('page_c').text());

	var errnr				= parseInt($(data).find('error').text());
	var errmsg				= $(data).find('errormsg').text();
	var haserr = errnr > 0;

	this.state_current_page_comments = c_currentpage; // remember state


	// error messages and notes

	if(errmsg){
		$('#message_hole')
			.html(errmsg)
			.css('background', (haserr ?'#FFC0C0':'#80FF80'))  //#C0FFC0
			.css('display', 'block')
			.show();
		if(!haserr){
			$('#message_hole').fadeOut(7000,(
			// $(mbox).slideUp(7000,(
					function(){
						$(this).hide();
					}
				)
			);
		}
	}else{
		$('#message_hole')
			.empty()
			.css('display', 'none'); 
	}

	$('#comment_count_value').html(c_comment_count_text);

	//$('#comment_count_text, #comment_count_value').css('display', 'inline');

	$('#comment_count_text, #comment_count_value').show();

	// $('#comment_count_value').slideUp(3000);

	var selectorpageshtml = '';
	var seteventsfor = Array();

	if(c_selectorpages.length > 0){
		var pages = c_selectorpages.split(',');
		selectorpageshtml = Array();
		var prev = 0;

		for(var i = 0, k = pages.length; i<k; i++){
			var page = pages[i];
			if((parseInt(prev)) != (parseInt(page)-1)) {
				selectorpageshtml[selectorpageshtml.length] = '...'; 
			}
			selectorpageshtml[selectorpageshtml.length]  = '<a href="javascript:void(0);" ' 
					+ ' id="user_comment_page_link_id-' + page + '" '
					+  (parseInt(page) == c_currentpage?' class="selected_page" ':'') 
					+ '>'+page+'</a>';

			seteventsfor[seteventsfor.length] = page;
			prev = page;
		}
		selectorpageshtml = selectorpageshtml.join(' ');
	}

	if(selectorpageshtml == ''){
		$('#comment_pager_inner_pages').hide(); 
	}else{
		$('#comment_pager_inner_pages').show(); 
	}

	$('#comment_pager_inner').html(selectorpageshtml); 

	for(var i = 0, k = seteventsfor.length; i<k; i++){
		var id = seteventsfor[i];
		// var func=new Function('that.goto_ucom_page('+id+');');
		$('#user_comment_page_link_id-' + parseInt(id)).click(
			function() {
				pageid = this.id.split('-'); // alert($('#'+this.id).text());
				that.goto_ucom_page(pageid[1]);
			}
		);
	}

	// $('#comment_pager_inner').html(selector); 


	$('#comment_pager').css('display', 'block'); 
	$('#comment_pager_inner').css('display', 'inline'); 


	var show_auto = c_currentpage == 1 && this.is_live == 1;

	$('#comments_update_button_auto').css('display', (show_auto?'inline':'none')); 
	$('#comments_update_button_manual').css('display', (!show_auto?'inline':'none')); 

	if(c_comment_count_text == 0){	
		$('#no_comments_yet').css('display', 'block'); 
	}else{
		$('#no_comments_yet').css('display', 'none'); 
		$('#comment_data').html(c_page_comments_html); 
	}

	if(this.is_live==1){
		$('#komm_ylekanne').addClass('live_ylekanne_live');
		$('#komm_ylekanne').removeClass('live_ylekanne_stopped');
	}else{
		$('#komm_ylekanne').addClass('live_ylekanne_stopped');
		$('#komm_ylekanne').removeClass('live_ylekanne_live');
	}

	$('#loading_comments').hide();




	// ##########################################


	var u_comment_count_text	= $(data).find('totalcomments_u').text();
	var u_selectorpages 		= $(data).find('selectorpages_u').text();
	var u_page_comments_html	= $(data).find('pagecomments_u').text();
	var u_currentpage			= parseInt($(data).find('page_u').text());


	this.state_current_page_updates = u_currentpage; // remember state


	var selectorpageshtml = '';
	var seteventsfor = Array();

	if(u_selectorpages.length > 0){
		var pages = u_selectorpages.split(',');
		selectorpageshtml = Array();
		var prev = 0;

		for(var i = 0, k = pages.length; i<k; i++){
			var page = pages[i];
			if((parseInt(prev)) != (parseInt(page)-1)) {
				selectorpageshtml[selectorpageshtml.length] = '...'; 
			}
			selectorpageshtml[selectorpageshtml.length]  = '<a href="javascript:void(0);" ' 
					+ ' id="update_page_link_id-' + page + '" '
					+  (parseInt(page) == u_currentpage?' class="selected_page" ':'') 
					+ '>'+page+'</a>';

			seteventsfor[seteventsfor.length] = page;
			prev = page;
		}
		selectorpageshtml = selectorpageshtml.join(' ');
	}

	if(selectorpageshtml == ''){
		$('#update_pager_inner_pages').hide(); 
	}else{
		$('#update_pager_inner_pages').show(); 
	}

	$('#update_pager_inner').html(selectorpageshtml); 


	for(var i = 0, k = seteventsfor.length; i<k; i++){
		var id = seteventsfor[i];
		// var func=new Function('that.goto_update_page('+id+');');
		$('#update_page_link_id-' + parseInt(id)).click(
			function() {
				pageid = this.id.split('-'); // alert($('#'+this.id).text());
				that.goto_update_page(pageid[1]);
			}
		);
	}

	$('#update_pager').css('display', 'block'); 
	$('#update_pager_inner').css('display', 'inline'); 


	var show_auto = u_currentpage == 1 && this.is_live == 1;

	$('#updates_update_button_auto').css('display', (show_auto?'inline':'none')); 
	$('#updates_update_button_manual').css('display', (!show_auto?'inline':'none')); 

	if(u_comment_count_text == 0){	
		$('#no_update_comments_yet').css('display', 'block'); 
	}else{
		$('#no_update_comments_yet').css('display', 'none'); 
		$('#updates_comment_data').html(u_page_comments_html); 
	}

	if(this.is_live==1){
		$('#live_ylekanne').addClass('live_ylekanne_live_u');
		$('#live_ylekanne').removeClass('live_ylekanne_stopped_u');
	}else{
		$('#live_ylekanne').addClass('live_ylekanne_stopped_u');
		$('#live_ylekanne').removeClass('live_ylekanne_live_u');
	}


	// ##########################################

	// auto resize comment frames -- LOOGIKA EBAKORREKTNE
	var old_comments_height = $('#app_center_container2').height();
	var new_comments_height = old_comments_height + ($(document).height() - $('body').height()) - 40; //old_comments_height + 
	// alert(old_comments_height + ' -> '+ new_comments_height);
	if(new_comments_height > this.comment_min_height){
		// alert(new_comments_height);
		$('#live_ylekanne, #komm_ylekanne').css('height', new_comments_height);
	}
};

LiveGameApp.prototype.goto_update_page = function(pagenum){
	this.state_current_page_updates	= pagenum;
	this.restartTimer(true, false);
};

LiveGameApp.prototype.goto_ucom_page = function(pagenum){
	this.state_current_page_comments = pagenum;
	this.restartTimer(true, false);
};


LiveGameApp.prototype.set_loading_status = function(onoff) {
	// $('#comments_loading_image, #updates_loading_image').css('display', (onoff?'inline':'none'));
	el = $('#loading_data');
	if(onoff){
		$(el).stop();
		$(el).css('opacity', 1);
		$(el).show();
	}else{
		// $(el).hide();
		$(el).stop();
		$(el).fadeOut(1000);
		$(el).hide();
	}
};


LiveGameApp.prototype.layoutCheckLive = function(){
	$('#loading_updates, #loading_comments').hide(); // hide always...

	if(this.is_live){
		$('#send_comment_form').show();
		$('#send_comment_stopped').hide();
	}else{
		$('#send_comment_form').hide();
		$('#send_comment_stopped').show();
	}
}

LiveGameApp.prototype.setUpBasicEventsAndVisibility = function() {
	var that = this;

	this.layoutCheckLive();

	$('#comments_update_button_auto img.updatelink, #comments_update_button_manual img.updatelink').click(
		function() {
			that.goto_ucom_page(1);
		}
	);	

	$('#updates_update_button_auto img.updatelink, #updates_update_button_manual img.updatelink').click(
		function() {
			that.goto_update_page(1);
		}
	);	


	//$('#refresh_textinfo').click(
	//	function() {
	//		that.clearTimeout(that.handle_textinfo_timeout);
	//		that.textinfo_timer(0, that.is_live);
	//	}
	//);
	// $('#refresh_comment').click(
	// 	function() {
	// 		clearTimeout(that.handle_comment_timeout);
	// 		ajax_timer(0, 1);
	// 	}
	// );


	$('#kommenteeri').submit(
		function() {
			commentator = $.trim($('#nimi').val());
			comment  = $.trim($('#kommentaar').val());

			$('#message_hole')
				.stop()
				.css('opacity','1.0')
				.hide();
			if (commentator.length == 0 || comment.length == 0) {
				if (commentator.length == 0) {
					$('#nimi').addClass('missing_or_incorrect_value');
				}
				if (comment.length == 0) {
					$('#kommentaar').addClass('missing_or_incorrect_value');
				}
			} else { 
				$('#kommentaar, #nimi').removeClass('missing_or_incorrect_value');
				$('input, #nimi, #kommentaar').attr('disabled', 'disabled');
				$('#kommenteeri').css('opacity', '0.3');
				that.postComment(
					{	
						commentator: commentator,
						comment: comment
					}
				);
/*
				$.post(
					that.live_comm_ajax_url, 
					{ 
						id			: that.game_id, 
						type		: 1 + 2 + 4, // score/gamecomments + game updates + user comments
						pagestep	: that.default_comment_per_page,
						nimi		: commentator, 
						kommentaar	: comment
					}, 
					function(data) { 
						$('input, #kommentaar').removeAttr('disabled');
						$('#kommenteeri').css('opacity', '1.0');
						$('#kommentaar').val('');

						that.map_data_xml(data);
						if(this.is_live){
							that.restartTimer(false, true);
						}
					}, 
					'xml'
				);
*/
			}
			return false;
		}
	);
};


LiveGameApp.prototype.postGetData = function(){
	var that = this;

	postdata = {};
	postdata.id			= this.game_id;
	postdata.type		= 1 + 2 + 4; // score/gamecomments + game updates + user comments
	postdata.pagestep	= this.default_comment_per_page;
	postdata.c_pagenr	= this.state_current_page_comments;
	postdata.u_pagenr	= this.state_current_page_updates;

	$.ajax(
		{
			async : true,
			global : false,
			type : 'POST',
			url : this.live_comm_ajax_url,
			dataType : 'xml',
			data : postdata,
			success : function(data, textStatus) { 
				that.map_data_xml(data);
				var u_1 = that.state_current_page_updates == 1; 
				var c_1 = that.state_current_page_comments == 1;
				if(that.is_live && (u_1 || c_1)){
					that.restartTimer(false, false);
				}else{
					// this.layoutCheckLive(); // done in map_data_xml
				}
				that.set_loading_status(false);
			},
			error : function (XMLHttpRequest, textStatus, errorThrown) {
				that.set_loading_status(false);
				// null, "timeout", "error", "notmodified" and "parsererror".
				// alert('Tekkis viga! ' + textStatus + ' ' + errorThrown)
				//TODO: hide "loading" + ask for restart
				if(that.is_live){
					that.restartTimer(false, true);
				}
			}
			// ,complete : function (XMLHttpRequest, textStatus, errorThrown) {}
		}
	);
};

LiveGameApp.prototype.postComment = function(postdata){
	var that = this;

	postdata.id			= this.game_id;
	postdata.type		= 1 + 2 + 4; // score/gamecomments + game updates + user comments
	postdata.pagestep	= this.default_comment_per_page;
	postdata.nimi		= postdata.commentator;
	postdata.kommentaar	= postdata.comment;
	// postdata.c_pagenr	= this.state_current_page_comments;
	// postdata.u_pagenr	= this.state_current_page_updates;

	$.ajax(
		{
			async : true,
			global : false,
			type : 'POST',
			url : this.live_comm_ajax_url,
			dataType : 'xml',
			data : postdata, 
			success : function(data, textStatus) { 
				that.postCommentReturn();
				that.map_data_xml(data);
				if(that.is_live){
					that.restartTimer(false, true);
				}
			},
			error : function (XMLHttpRequest, textStatus, errorThrown) {
	            that.postCommentReturn();
				if(that.is_live){
					that.restartTimer(false, true);
				}
				// null, "timeout", "error", "notmodified" and "parsererror".
				// alert('Tekkis viga! ' + textStatus + ' ' + errorThrown)
				//TODO: hide "loading" + ask for restart
			}
			// ,complete : function (XMLHttpRequest, textStatus, errorThrown) {}
		}
	);
};

/*
LiveGameApp.prototype.postComment = function(){
	var that = this;
	commentator = $.trim($('#nimi').val());
	comment  = $.trim($('#kommentaar').val());

	$.post(
		that.live_comm_ajax_url, 
		{ 
			id			: that.game_id, 
			type		: 1 + 2 + 4, // score/gamecomments + game updates + user comments
			pagestep	: that.default_comment_per_page,
			nimi		: commentator, 
			kommentaar	: comment
		}, 
		function(data) { 
	        that.postCommentReturn();
			that.map_data_xml(data);
			if(that.is_live){
				that.restartTimer(false, true);
			}
		},
		'xml'
	);
};
*/
LiveGameApp.prototype.postCommentReturn = function(){
	$('input, #kommentaar').removeAttr('disabled');
	$('#kommenteeri').css('opacity', '1.0');
	$('#kommentaar').val('');
};



