/**
 * @param {Object} tableVal		jQuery table element to use for the list
 * @param {Object} options		Object containing options (url,updateInterval,syncTime,debug)
 */
var BingoSessionList = function(tableVal,options)
{
	var url = "";
	var updateInterval = 10;
	var syncTime = 20;
	var debug = false;
	var locale = "";
	var demoMode = false;
	var showTestButton = false;
	
	if (options.showTestButton)
		showTestButton = options.showTestButton;
	
	if (options.locale)
		locale = options.locale;
	
	if (options.url)
		url = options.url;
	
	if (options.updateInterval)	
		updateInterval = options.updateInterval;
	
	if (options.syncTime)
		syncTime = options.syncTime;
	
	if (options.debug)
		debug = options.debug;
	
	if (options.demoMode)
		demoMode = options.demoMode;
	
	var firstFetch = true;
	var roomData = [];
	var roomMap = [];
	var updateCycle = 0;	
	var timer = null;
	
	var UPDATE_TIME = 1;
	var UPDATE_INCREMENTAL = 2;
	var UPDATE_FULL = 3;	
	
	var table = tableVal;
	
	var getCellValue = function(cellVal)
	{
		var cell = cellVal;
		
		if (!(cell instanceof jQuery))
			cell = $(cellVal);
						
		var data = cell.data("rawvalue");
		if (data == null)
			data = cell.text();

		return data+"";
	}
		
	table.tablesorter(
	{
		textExtraction: getCellValue,
		widgets: ["zebra"],
		widgetZebra: {css: ["","a"]},
		//debug: true,
		headers:{
			0:{sorter:"digit"},
			1:{},
			2:{},
			3:{sorter:"digit"},
			4:{sorter:"digit"},
			5:{sorter:"digit"},
			6:{sorter:"digit"},
			7:{sorter:"digit"},
			8:{sorter:"digit"},
			9:{sorter:false}
		},
		cssAsc: "sortasc",
		cssDesc: "sortdesc"
	});

	firstFetch = true;
	
	this.start = function()
	{
		fetchGames();
		setInterval(updateTime,1000);
	}
			
	var fetchGames = function()
	{
		$.getJSON(url,onDataFetched);
	}
	
	var onDataFetched = function(data)
	{
		roomData = [];
		roomMap = [];

		if (data.items.length == 0)
		{
			//console.log("no games");
			return;
		}
		
		$.each(data.items,parseSessionData);
		table.trigger("update");

		if (firstFetch)
		{
			firstFetch = false;			
			table.trigger("sorton",[ [[8,1]] ]);
		}
		else
		{
			//table.trigger("sort");
		}
	}

	var parseSessionData = function(index, item)
	{
		roomData.push(item);
		roomMap[item.sessionId] = item;
		
		var sessionId = item.sessionId;
		
		var row = $("#"+table.attr("id")+"-session-" + sessionId);
		
		if (row.length > 0)
			updateRow(row, item, UPDATE_FULL);
		else
			createRow(item);
	}
		
	var updateTime = function()
	{
		updateCycle++;
		
		if (updateCycle == updateInterval)
		{
			updateCycle = 0;
			fetchGames();
		}
		else
		{
			$.each(roomData,function(index,item)
			{
				if (item.timeLeft > 0)
				{				
					item.timeLeft--;
					updateRow($("#"+table.attr("id")+"-session-"+item.sessionId),item,UPDATE_TIME);
				}
			});
		}
	}

	var secToTime = function(secs)	
	{
		if (secs < 0)
			return " - ";
		
		var mins = Math.floor(secs / 60);
		var newSecs = secs - (mins * 60);
		if (newSecs < 10)
			newSecs = "0"+newSecs;
			
		return mins + ":" + newSecs;
	}
	
	var onPlayButtonClick = function(sessionId,test)
	{
		if (demoMode)
		{
			window.location = "/register";
			return;	
		}
		
		var item = roomMap[sessionId];
		var url = "/flash/games/index.php?gsid="+sessionId+"&gtype=bingo&newwindow=false&lang="+locale+"&v2=true&ext=true&size=hd";
		
		if (test)
			url = "/flash/gamestest/index.php?gsid="+sessionId+"&gtype=bingo&newwindow=false&lang="+locale+"&v2=true&ext=true&size=hd";

		if (item.timeLeft > syncTime)
		{
			joinGame(url, 'bingo' + sessionId, WTYPE_MAXIMIZED);
			//alert("play button clicked for "+item.name+", time left is: "+item.timeLeft);
		}
		else
		{
			//alert(item.name + " is disabled, time left is: " + item.timeLeft);
		}
		
	}
	
	var updateRow = function(row, item, updateType)
	{
		if (row.find("a.playbutton").length == 0)
		{
			row.find(".play").append('<a class="button playbutton" href="#"><span>'+playText+'</span></a>');
			row.find("a.playbutton").click(function(){ onPlayButtonClick(item.sessionId); return false;});
		}

		if (showTestButton == true)
		{
			if (row.find("a.testbutton").length == 0)
			{
				row.find(".play").append('<a class="button testbutton" href="#"><span>Test</span></a>');
				row.find("a.testbutton").click(function(){ onPlayButtonClick(item.sessionId,true); return false;});
			}
		}
		
		if (updateType >= UPDATE_TIME)
		{
			row.find(".timeleft").html(secToTime(item.timeLeft)).data("rawvalue",item.timeLeft);
						
			if (item.timeLeft < syncTime)
			{
				if(!row.hasClass("disabled"))
				{
					row.addClass("disabled");
					//row.find("a.button").hide("slow");
				}
			}
			else if (row.hasClass("disabled"))
			{
				row.removeClass("disabled");
				row.find("a.playbutton").show("slow");
			}
		}
		
		if (updateType >= UPDATE_INCREMENTAL)
		{
			row.find(".pot").html(item.formatted.jackpot).data("rawvalue",item.base.jackpot.toFixed(2));
			//row.find(".pot").append("("+item.base.jackpot.toFixed(2)+" USD)");
			
			if(item.progJackpot)
				row.find(".progjackpot").html(item.formatted.progJackpot).data("rawvalue",item.base.progJackpot.toFixed(2));
			else
				row.find(".progjackpot").html(" - ").data("rawvalue",0);

			if (!item.numSessionPlayers || item.numSessionPlayers == 0)
				row.find(".players").html(" - ").data("rawvalue",0);
		        else if (item.cmlist.length > 0)
                //row.find(".players").html(item.numSessionPlayers + " <img src='/images/common/cm-logo.png' alt='cm'/> ").data("rawvalue",item.numSessionPlayers);
		row.find(".players").html(item.numSessionPlayers + " <span class='cm'><a class='cmlink'><img class='cmimg' src='/images/common/cm-logo.png' alt='cm'/><span class='cmpopup'><img src='/viewprofilepic.php?size=small&alias="+item.cmlist[0].name+"'/>"+item.cmlist[0].name+"</span></a></span> ").data("rawvalue",item.numSessionPlayers);
			else
				row.find(".players").html(item.numSessionPlayers).data("rawvalue",item.numSessionPlayers);
		}
		
		if (updateType >= UPDATE_FULL)
		{			
			if (item.style != row.data("styleclass"))
			{
				row.removeClass("style-"+row.data("styleclass"));

				if (item.style != null && item.style != "")
				{
					row.find(".style").html('<img class="flag" src="/images/flags/flag_'+item.style+'.gif"/>').data("rawvalue",item.style);
					row.addClass("style-"+item.style);
				}
				else
				{
					row.find(".style").html('-').data("rawvalue","");
				}
				
				row.data("styleclass",item.style);
			}
			
			row.find(".name").html(item.name);
			row.find(".cardprice").html(item.formatted.cardPrice).data("rawvalue",item.base.cardPrice.toFixed(2));
			row.find(".proghighcall").html(item.pjHighCall);

			var gameTypeString = item.gameType;
			if (item.gameType == "euro")
				gameTypeString = "90";
			else if (item.gameType == "variant")
				gameTypeString = "75v";
			else if (item.gameType == "classic")
				gameTypeString = "75";
				
			row.find(".type").html(gameTypeString);
		}			
	}
	
	var createRow = function(item)
	{
		var sessionId = item.sessionId;
		var body = table.find("tbody");
		
		var row = $(
		"<tr id=\""+table.attr("id")+"-session-"+sessionId+"\">"
		+"<td class=\"timeleft\"></td>"
		+ "<td class=\"style\"></td>"
		+ "<td class=\"name\"></td>"
		+ "<td class=\"type\"></td>"
		+ "<td class=\"cardprice\"></td>"
		+ "<td class=\"pot\"></td>"
		+ "<td class=\"progjackpot\"></td>"
		+ "<td class=\"proghighcall\"></td>"
		+ "<td class=\"players\"></td>"
		+ "<td class=\"play\"></td>"
		+ "</tr>");

		body.append(row);
		row.addClass("disabled");
		
		if (debug)
		{
			row.find("td").click(function(){
				alert(getCellValue(this));
			});
		}
		
		updateRow(row,item,UPDATE_FULL);
	}
}
