var sNextInfoMessage = '';
var tFilterTimer;


$(function() {	
	
		   
	/*
	*	Sets the columns to be sortable, if new columns are added later for whatever reason 
	*	these are also setup.
	*
	*	When update is called within the sortable columns the order in the database is updated
	*	and saved.
	*/
	
	var timer;
	
	/*
	*	Set forms to submit via ajax. 
	*	The form will not refresh the page and instead call the callback function provided.
	*/
	//setAJAXWatchlistForm();
	
	$('.infoBarContent').each(
		function()
		{
			setTimeout('animateInfoBarContent();',4000);	
		}
	);
	
	
	$("#addWatchlistItemForm").livequery(
		function()
		{
			$("#addWatchlistItemForm").ajaxForm(function() { 
				$.get('ajaxUpdateWatchlist.asp?game=' + sConst_GameCode + '&rnd=' + Math.random(),
				  function(data)
				  {
					  $('#watchlistContent').html(data);
					  $('#txtSearch2').val('');
					  $('#Results2').css('visibility','hidden');
				  }
				);
			});
		}
	);
	
	$('.inboxNumber').each(
		function()
		{
			setTimeout("ajaxGetNewInboxMessages()",30000);
		}
	);
	
	$("#chatMessage").each(
		function()
		{
			setTimeout("ajaxGetMessages()",1000);
		}
	);
	
	$("#chatMessage2").each(
		function()
		{
			setTimeout("ajaxGetFeedback()",1000);
		}
	);
	
	$(".positionPortlet").each(
		function()
		{
			setTimeout("ajaxUpdatePosition()",60000);
		}
	);
	
	$("#portfolioSummary").each(
		function()
		{
			setTimeout("ajaxUpdatePortfolioSummary()",10000);
		}
	);
	
	$("#watchlistContent").each(
		function()
		{
			setTimeout("ajaxUpdateWatchlist()",10000);
		}
	);
	
	$("#forumFeedContent").each(
		function()
		{
			setTimeout("ajaxUpdateForumFeed()",10000);
		}
	);
	
	$("#portfolioFull").each(
		function()
		{
			setTimeout("ajaxUpdatePositionFull()",10000);
		}
	);
	
	$("#RealTimeStats").each(
		function()
		{
			setTimeout("ajaxUpdateRealTimeStats()",5000);
		}
	);
	
	$('#counterContainer').each(
		function()
		{
			updateCounter(20);	
		}
	);
	
	$("#ajxTime").each(
		function()
		{
			setTimeout("ajaxGetTime()",1000);
		}
	);
	
	
	$('.portlet .portlet-header').addClass('movableHeader');
	
	$(".column").sortable(
		{ 
			connectWith: '.column',
			update: function() 
					{				
						var temp = $(this).attr('id');
						var order = $(this).sortable('serialize');
						//alert(order);
						$.get('updateorder.asp?'+order+'&col='+ temp + '&action=Main&rnd=' + Math.random(), function(data) {/*alert(data);*/} );
					},
			handle: '.portlet-header',
			placeholder: 'placeholder',
			forcePlaceholderSize: true
		}
	);
	
	$("#GameChanger").change(
		function()
		{
			document.forms["GameChangerForm"].submit();
		}
	);
	
	$("#GameChangerSubmit").remove();
	
	$(".MyGamesColumn").sortable(
		{ 
			connectWith: '.MyGamesColumn',
			update: function() 
					{				
						var temp = $(this).attr('id');
						var order = $(this).sortable('serialize');
						//alert(order);
						$.get('updateorder.asp?'+order+'&col='+ temp + '&action=MyGames&rnd=' + Math.random(), function(data) {/*alert(data);*/} );
					},
			handle: '.portlet-header'
		}
	);
	
	//$(".portlet").find(".portlet-header")
	//				.prepend('<span style="cursor:pointer;margin:4px 5px 0 0;" class="ui-icon ui-icon-plusthick ui-icon-minusthick"></span>');
					
	$(".portlet-header .ui-icon-plusthick").click(
		function()
		{
			$(this).toggleClass("ui-icon-minusthick");
			
			$(this).parents(".portlet:first").find(".portlet-content").toggle();
			
			var bMinimised = 'Y';
			
			if($(this).hasClass("ui-icon-minusthick"))
			{
				bMinimised = 'N';
			}
			
			var sID = $(this).parents(".portlet:first").attr('id');
			
			$.get('ajaxUpdateMinimisedStatus.asp?min=' + bMinimised + '&id=' + sID + '&rnd=' + Math.random(),function(data){});
		}
	);
	
	$('.nonJStooltip').attr('title','');
	$("#FILTERSUBMIT_Refresh").remove();
	$('#filterSubmit').remove();
	
	$("#FILTER_BuySell, #FILTER_TradeType, #FILTER_status").change(
		function()
		{
			document.forms["TransactionFilterForm"].submit();
		}
	);
	
	$(".deleteOpenOrderLink").each(
		function()
		{
			var sURL = $(this).attr('href');
			
			$(this).attr('href','javascript:confirmDeleteOpenOrder("'+sURL+'");');
		}
	);
	
	$("#NumSharesContainer").append("&nbsp;<sub><a class='linkContent' href='#' onClick='MaxNumShares();clearCashAmount();return false;'>Max</a></sub>");
	$("#CashAmountContainer").append("&nbsp;<sub><a class='linkContent' href='#' onClick='MaxCash();clearNumShares();return false;'>Max</a></sub>");
	$("#QUICKNumSharesContainer").append("&nbsp;<sub><a class='linkContent' href='#' onClick='QuickMaxNumShares();clearCashAmount();return false;'>Max</a></sub>");
	$("#QUICKCashAmountContainer").append("&nbsp;<sub><a class='linkContent' href='#' onClick='QuickMaxCash();clearNumShares();return false;'>Max</a></sub>");
});

function animateInfoBarContent()
{
	if($('.infoBarContent').is(":visible") == true)
	{
		$('.infoBarContent').hide("slide", { direction: "up" }, 1000, 
			function()
			{
				if(sNextInfoMessage != '')
				{
					$('.infoBarContent').html(sNextInfoMessage);
				}
				else
				{
					  $.get('ajaxGetNextInfoMessage.asp?game=' + sConst_GameCode + '&rnd=' + Math.random(),
						  function(data)
						  {
							  if(data != '')
							  {
								  sNextInfoMessage = data;
								  $('.infoBarContent').html(sNextInfoMessage);
							  }
							  
							  $('.infoBarContent').show("slide", { direction: "down" }, 1000,
								  function()
								  {
									  setTimeout('animateInfoBarContent();',4000);
									  $.get('ajaxGetNextInfoMessage.asp?game=' + sConst_GameCode + '&rnd=' + Math.random(),
										  function(data)
										  {
											  if(data != '')
											  {
												  sNextInfoMessage = data;
											  }
										  }
									   );
								  }
							 );
						  }
					 );	
					return;
				}
						  
				$('.infoBarContent').show("slide", { direction: "down" }, 1000,
					  function()
					  {
						  setTimeout('animateInfoBarContent();',4000);
						  $.get('ajaxGetNextInfoMessage.asp?game=' + sConst_GameCode + '&rnd=' + Math.random(),
							  function(data)
							  {
								  if(data != '')
								  {
									  sNextInfoMessage = data;
								  }
							  }
						   );
					  }
				 );
			}
		);
	}
	else
	{
		if(sNextInfoMessage != '')
		{
			$('.infoBarContent').html(sNextInfoMessage);
		}
		
		$('.infoBarContent').show("slide", { direction: "down" }, 1000, 
			function()
			{
				setTimeout('animateInfoBarContent();',4000);
				$.get('ajaxGetNextInfoMessage.asp?game=' + sConst_GameCode + '&rnd=' + Math.random(),
					  function(data)
					  {
						  if(data != '')
						  {
							  sNextInfoMessage = data;
						  }
						  animateInfoBarContent();
					  }
				 );	
			}
		);	
	}	
	
	
}

function updateCounter(iNum)
{
	if(iNum >= 0)
	{
		$('#counterContainer').html(iNum);
		setTimeout('updateCounter('+iNum+' - 1);',1000);
	}
	else
	{
		$('#counterContainer:visible').css({"color":"red"});
		updateBlink();	
	}
}

function updateBlink()
{
	if($('#counterContainer').css("visibility") == "hidden")
	{
		$('#counterContainer').css({"visibility":"visible"});
	}
	else
	{
		$('#counterContainer:visible').css({"visibility":"hidden"});
	}
	
	setTimeout('updateBlink();',500);
}

function MaxNumShares()
{
	$("#buy:checked").each(
		function()
		{
			$("#NumSharesBox").val($("#MaxBuySize").html());
		}
	);
	
	$("#sell:checked").each(
		function()
		{
			$("#NumSharesBox").val($("#MaxSellHoldings").html());
		}
	);
}

function MaxCash()
{
	$("#buy:checked").each(
		function()
		{
			$("#cashBox").val($("#MaxBuyCash").html());
		}
	);
	
	$("#sell:checked").each(
		function()
		{
			$("#cashBox").val($("#MaxSellCash").html());
		}
	);
}

function QuickMaxNumShares()
{
	$("#buy:checked").each(
		function()
		{
			$.get('GetMaxVals.asp?game=' + sConst_GameCode + '&ticker='+$('#txtSearch1').val()+'&max=num&type=buy&rnd=' + Math.random(),
				function(data) 
				{
					$("#NumSharesBox").val(data);
				}
			);
		}
	);
	
	$("#sell:checked").each(
		function()
		{
			$.get('GetMaxVals.asp?game=' + sConst_GameCode + '&ticker='+$('#txtSearch1').val()+'&max=num&type=sell&rnd=' + Math.random(),
				function(data) 
				{
					$("#NumSharesBox").val(data);
				}
			);
		}
	);
}

function QuickMaxCash()
{
	$("#buy:checked").each(
		function()
		{
			$.get('GetMaxVals.asp?game=' + sConst_GameCode + '&ticker=' + $('#txtSearch1').val() + '&max=cash&type=buy&rnd=' + Math.random(),
				function(data) 
				{
					$("#cashBox").val(data);
				}
			);
		}
	);
	
	$("#sell:checked").each(
		function()
		{
			$.get('GetMaxVals.asp?game=' + sConst_GameCode + '&ticker=' + $('#txtSearch1').val() + '&max=cash&type=sell&rnd=' + Math.random(),
				function(data) 
				{
					$("#cashBox").val(data);
				}
			);
		}
	);
}

function clearNumShares()
{
	$("#NumSharesBox").val("");	
}

function clearCashAmount()
{
	$("#cashBox").val("");	
}

function confirmDeleteOpenOrder(sURLRedirect)
{
	var r=confirm("Are you sure you want to delete this open order?");
	if (r==true)
	{
		window.location = sURLRedirect
	}
}

function ajaxGetMessages()
{
	$.get('ajaxGetChat.asp?game=' + sConst_GameCode + '&rnd=' + Math.random(),
		function(data) 
		{
			var sChatBoxText = $("#messagePane").html();
			
			if(sChatBoxText != data)
			{
				$("#chatcontent").html(data);
			}
			
			setTimeout("ajaxGetMessages()",1000);
		}
	);
}

function ajaxGetFeedback()
{
	$.get('ajaxGetFeedback.asp?game=' + sConst_GameCode + '&rnd=' + Math.random(),
		function(data) 
		{
			var sFeedbackBoxText = $("#messagePane2").html();
			
			if(sFeedbackBoxText != data)
			{
				$("#messagePane2").html(data);
			}
			
			setTimeout("ajaxGetFeedback()",1000);
		}
	);
}


function ajaxUpdatePosition()
{
	$.get('ajaxUpdatePosition.asp?game=' + sConst_GameCode + '&rnd='+Math.random(),
		function(data) 
		{
			var sPositionTable = $("#positionTable").html();
			
			if(sPositionTable != data)
			{
				$("#positionTable").html(data);
			}
			
			setTimeout("ajaxUpdatePosition()",60000);
		}
	);
}

function ajaxUpdatePortfolioSummary()
{
	$.get('ajaxUpdatePortfolioSummary.asp?game=' + sConst_GameCode + '&rnd=' + Math.random(),
		function(data) 
		{
			var sPortfolioSummary = $("#portfolioSummary").html();
			
			if(sPortfolioSummary != data)
			{
				$("#portfolioSummary").html(data);
				document.title = $("#totalVal").html().replace("&nbsp;","");
			}
			
			setTimeout("ajaxUpdatePortfolioSummary()",10000);
		}
	);
}

function ajaxUpdateWatchlist()
{
	$.get('ajaxUpdateWatchlist.asp?game=' + sConst_GameCode + '&rnd=' + Math.random(),
		function(data) 
		{
			var sWatchlist = $("#watchlistContent").html();
			
			if(sWatchlist != data)
			{
				$("#watchlistContent").html(data);
			}
			
			setTimeout("ajaxUpdateWatchlist()",10000);
		}
	);
}

function ajaxUpdateForumFeed()
{
	$.get('ajaxUpdateForumFeed.asp?game=' + sConst_GameCode + '&rnd=' + Math.random(),
		function(data) 
		{
			var sForumFeed = $("#forumFeedContent").html();
			
			if(sForumFeed != data)
			{
				$("#forumFeedContent").html(data);
			}
			
			setTimeout("ajaxUpdateForumFeed()",10000);
		}
	);
}

function ajaxUpdatePositionFull()
{
	$.get('ajaxUpdatePortfolioFull.asp?game=' + sConst_GameCode + '&rnd=' + Math.random(),
		function(data) 
		{
			var sPortfolioFull = $("#portfolioFull").html();
			
			if(sPortfolioFull != data)
			{
				$("#portfolioFull").html(data);
			}
			
			setTimeout("ajaxUpdatePositionFull()",10000);
		}
	);
}


function ajaxGetTime()
{
	$.get('tools/ajax/getTime.asp?rnd=' + Math.random(),
		function(data) 
		{
			var sTime = $("#ajxTime").html();
			
			if(sTime != data)
			{
				$("#ajxTime").html(data);
			}
			
			setTimeout("ajaxGetTime()",1000);
		}
	);
}

function ajaxPostFeedbackMessage()
{
	var sText = $("#chatMessage2").val();
	$.post('ajaxPostFeedback.asp?game=' + sConst_GameCode  + '&rnd=' + Math.random(),{ text: sText });
	$("#chatMessage2").attr('value',"");
	return false;
}

function ajaxPostMessage()
{
	var sText = $("#chatMessage").val();
	
	$.post('ajaxPostChat.asp?game='+sConst_GameCode,{ text: sText });
	$("#chatMessage").attr('value',"");
	return false;
}

function ChangeLeaderBoardHold(iPosition)
{
	
	$.get('ajaxGetLeaderboard.asp?game=' + sConst_GameCode + '&Position=' + iPosition + '&rnd=' + Math.random(),
		function(data) 
		{
			$("#leaderboradDiv").html(data);
			timer = setTimeout(ChangeLeaderBoardHold(iPosition - 1),100);
		}
	);
	return false;
}

function ChangeLeaderBoardRelease()
{
	clearTimeout(timer);
}


function ChangeLeaderBoard(iPosition)
{
	$.get('ajaxGetLeaderboard.asp?game=' + sConst_GameCode + '&Position=' + iPosition + '&rnd=' + Math.random(),
		function(data) 
		{
			$("#leaderboradDiv").html(data);
		}
	);
	return false;
}

function ChangeArchiveLeaderBoard(iPosition, sArchiveGameCode)
{
	$.get('ajaxGetArchiveLeaderboard.asp?Position=' + iPosition + '&code=' + sArchiveGameCode + '&rnd='+Math.random(),
		function(data) 
		{
			$("#archiveLeaderboardDiv").html(data);
		}
	);
	return false;
}

function ChangeChartTab(iTabNum)
{
	$.get('ajaxChangeGraphTab.asp?game=' + sConst_GameCode + '&tabNum=' + iTabNum + '&rnd=' + Math.random(),
		function(data) 
		{
			$('#chartingContent').html(data);
		}
	);
	return false;	
}

function ajaxUpdateSearchGamesFilter()
{
	$.get('ajaxUpdateFilteredSearchGames.asp?page=1&filtertext=' + $('#searchGamesFilter').val() + '&rnd=' + Math.random(),
		function(data)
		{
			$('#joinGameList').html(data);
		}
	);	
}

function ajaxUpdateRealTimeStats()
{
	$.get('ajaxUpdateRealTimeStats.asp' + '?rnd=' + Math.random(),
		function(data)
		{
			$('#RealTimeStats').html(data);
			setTimeout("ajaxUpdateRealTimeStats()",5000);
		}
	);	
}

function ajaxGetNewInboxMessages()
{
	$.get('ajaxGetNewInboxMessages.asp?rnd=' + Math.random(),
		function(data)
		{	
			var iNumNewMessages = parseInt(data);
			if(iNumNewMessages == 0)
			{
				$('.inboxNumber').css('visibility','hidden');
			}
			else
			{
				$('.inboxNumber').css('visibility','visible');
			}
			
			$('.inboxNumber').html(data);
			
			setTimeout("ajaxGetNewInboxMessages()",30000);
		}
	);	
}



function hideElementID(sElementID)
{
	$('#' + sElementID).hide();
}

function showElementID(sElementID)
{
	$('#' + sElementID).show();
}

function addNewWatchlistItem()
{
	var sAction = $('#addWatchlistItemForm').attr('action');

	if(sAction.indexOf('redirect') == -1)
	{
		sAction = sAction + "&redirect=false"
	}
	
	$('#addWatchlistItemForm').attr('action',sAction);
	//document.addWatchlistItemForm.submit();
}

function setAJAXWatchlistForm()
{
	$('#addWatchlistItemForm').ajaxForm(function() { 
    	$.get('ajaxUpdateWatchlist.asp?game=' + sConst_GameCode + '&rnd=' + Math.random(),
		  function(data)
		  {
			  $('#watchlistContent').html(data);
			  setAJAXWatchlistForm();
		  }
		);
    });
}

function changeResultsPortletPage(iRoundNumber)
{
	$.get('ajaxChangeResultsPortletPage.asp?game=' + sConst_GameCode + '&resultPage=' + iRoundNumber + '&rnd=' + Math.random(),
		function(data)
		{	
			$('#resultsContent').html(data);
		}
	);	
}

function showTime() {
	var currentTime = new Date();
	var hours = currentTime.getHours();
	var minutes = currentTime.getMinutes();
	var seconds = currentTime.getSeconds();
	var sTime = '';
	if (hours < 10){ hours = "0" + hours; }
	if (minutes < 10){ minutes = "0" + minutes; }
	if (seconds < 10){ seconds = "0" + seconds; }
	
	sTime += hours + ":" + minutes + ":" + seconds + " ";
	if(hours > 11){
		sTime += "PM";
	} else {
		sTime += "AM";
	}
	return sTime;
}
