// JavaScript Document
var	GamesPlayedCookieName		=	"GamesPlayed";
var	CookieName_SessionID		=	"TLC";
var	CookieName_UniqueID			=	"BDUniq";
var	CookieName_AffiliateID		=	"AffiliateID";

var	stgAv 			= 	0;
var	DoneLoginCall	=	false;

	$(document).ready(function(){

	  stgAv = readCookie("stgAv");
	  if (stgAv != 1) {
		stgAv = 0;
	  }
	  
      var options = {
        timeNotation: '24h',
        am_pm: true,
		utc: true,
        fontFamily: 'Arial, Verdana',
        fontSize: '13px',
        foreground: '#fff',
        background: 'transparent'
      }
      $('.jclock').jclock(options);
	  // alert("Doc Ready");
    });

//	There is a bug in IE which causes a javascript error when a flash movie is unloaded. This fixes that

if ( ( navigator.userAgent.toLowerCase().indexOf('msie') != -1 ) && ( navigator.userAgent.toLowerCase().indexOf( 'opera' ) == -1 ) )
{
	window.attachEvent( 'onunload', function()
		{
			window['__flash__removeCallback'] = function ( instance, name )
			{ 
				try
				{ 
					if ( instance )
					{ 
						instance[name] = null ; 
					} 
				}
				catch ( flashEx )
				{

				} 
			} ;
		}
	) ;
}

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

function	AlertMilliSeconds(TextString)
{
	var d 			= new Date();
	var msec 		= d.getMilliseconds();
	var sec 		= d.getSeconds();
	return TextString + " " + sec + " " + msec + "|";	
}
function StringAlphaNumeric(TheString)
{
	TheString	=	TheString.toLowerCase();
	for (var i=0;i<TheString.length;i++) {
		var ThisChar	=	TheString.substr(i,1);
		if (("abcdefghijklmnopqrstuvwxyz0123456789").indexOf(ThisChar) < 0) {
			return false;
		}
	}
	
	return true;
}

function ShowFooterComment(Comment,Append)	//	Show a comment at the bottom of the page (staging only)
{
	if (Append == undefined) {
		Append = false;
	}
	else {
		Comment = Comment;
	}
	
	if (Append) {
		Comment	=	$('.ShowFooterComments').text() + " " + Comment;
	}
	$('.ShowFooterComments').text(Comment);
	return;
}

function 	CountGoogleGame()
{
	var	Staging 	=	parseInt($('.StagingStatus').text());
	if (Staging == 1) {
		return;
	}
	pageTracker._trackPageview('/PlayAnyGameCount');
}

function 	CountGoogleFirstGame()
{
	var	Staging 	=	parseInt($('.StagingStatus').text());
	if (Staging == 1) {
		return;
	}
	pageTracker._trackPageview('/PlayFirstGameCount');
}

function 	CountGoogleEmail()
{
	var	Staging 	=	parseInt($('.StagingStatus').text());
	if (Staging == 1) {
		return;
	}
	pageTracker._trackPageview('/LeaveEmail');
}

function 	CountGoogleRegister()
{
	var	Staging 	=	parseInt($('.StagingStatus').text());
	if (Staging == 1) {
		return;
	}
	pageTracker._trackPageview('/RegisterAccount');
}

function IncreaseGameCount()
{
	var GamesPlayed	=	ReadGameCount();
	if (GamesPlayed == 0) {
		CountGoogleFirstGame()
	}
	CountGoogleGame();
	GamesPlayed++;
	setCookie(GamesPlayedCookieName,GamesPlayed);
	
	DisplayFooterInfo();
}

function ReadGameCount(PassForceGameCount)
{
	
	var	GamesPlayed			=	0;
	try {
		if(PassForceGameCount==null)	{
			PassForceGameCount = 0;
		}
		ForceGameCount	=	parseInt(PassForceGameCount);
		GamesPlayed		=	ForceGameCount;
	}
	catch (err) {
		ForceGameCount	= 	0;
	}
	
	//	Figure out how many times we have been here
		
	if (ForceGameCount == 0) {
		var	CookieValue	=	readCookie(GamesPlayedCookieName);
		if (IsNumeric(CookieValue) == false) {
			GamesPlayed	=	0;
		}
		else {
			GamesPlayed	=	parseInt(CookieValue);
		}
	}
	
	return GamesPlayed;

}

function IsNumeric(strString)
   //  check for valid numeric strings	
   {
   var strValidChars = "0123456789";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
   }

function newWindow(myImage,myWidth,myHeight) {
	myHeight += 54;
	myWidth += 26;
	TheImgWin = window.open(myImage,'image','height='+myHeight+',width='+myWidth+',toolbar=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no');
	TheImgWin.focus();
}

function JSONCallApiCall(WebServer,WebService,ParamString,CallBack)
{
	var	TheURL		=	"/API/server/json/json_wrapper.php?";
	TheURL			+=	"WebService=" 	+ WebService + "&";
	TheURL			+=	"WebServer=" 	+ WebServer + "&";
	TheURL			+=	ParamString;

	TheURL		=	TheURL + "jsoncallback=?";		
	$.getJSON(TheURL, CallBack);	
}


function	ValidEmail(EmailAddress)
{
	FirstDot	=	EmailAddress.indexOf(".");
	if (FirstDot < 0) {
		return false;
	}
	
	FirstAt	=	EmailAddress.indexOf("@");
	if (FirstAt < 0) {
		return false;
	}
	
	LastAt	=	EmailAddress.lastIndexOf("@");
	if (LastAt != FirstAt) {
		return false;
	}
	
	return true;
	
}

function LoginUser(TargetURL,Staging)
{
	
	if (Staging == 0) {
		return true;
	}
	
	var	LoginString		=	$("input[name=LoginString]").val().trim();
	var	Password		=	$("input[name=Password]").val().trim();

	var	ParamString			=	"";
	ParamString				+=	"LoginString="			+ 	LoginString		+ "&";
	ParamString				+=	"Password=" 			+ 	Password + "&";
	BrainDashApiCall		("user/UserServer.php","user.login",ParamString,function(json_data){
			Status		=	json_data['Status'];
			if (Status == "ERROR") {
				alert ("Error");
				return;
			}
			else {
				var	UserSessionID	=	json_data['UserSessionID'];
				var	UniqueID		=	json_data['UniqueID'];
				var	AffiliateID		=	json_data['AffiliateID'];
				JSLogin(UniqueID,UserSessionID,AffiliateID,TargetURL)				
			}
	});
	
}

function ShowButton(Stake,field_id_yes,field_id_no)
{

	var	UserSessionID	=	$('#playcash_user_sessionID').text();
	var	LoginURL		=	$('#playcash_LoginURL').text();
	var	DepositURL		=	$('#playcash_DepositURL').html();

	var UserBalance		=	0;
	try {
		UserBalance		=	parseInt($('#playcash_totalbalance').text());
	}
	catch (Exception) {}
	
	//	If the user session id is not set, you can't play
	
	if (UserSessionID.length == 0) {

		$('#' + field_id_no).html(LoginURL);
		$('#' + field_id_yes).hide();
		$('.' + field_id_yes).hide();
		$('#' + field_id_no).show();		
		
		$('#facebox #' + field_id_no).html(LoginURL);
		$('#facebox #' + field_id_yes).hide();
		$('#facebox .' + field_id_yes).hide();
		$('#facebox #' + field_id_no).show();		
				
	}	
	else {
	
		//	You haven't got enough money....
		
		if (UserBalance < Stake) {		
			$('#' + field_id_no).html(DepositURL);
			$('#' + field_id_yes).hide();
			$('#' + field_id_no).show();		
			
			$('#facebox #' + field_id_no).html(DepositURL);
			$('#facebox #' + field_id_yes).hide();
			$('#facebox #' + field_id_no).show();		
		}
		else {
			
			$('#' + field_id_yes).show();
			$('#' + field_id_no).hide();		
			$('.' + field_id_no).hide();		

			$('#facebox #' + field_id_yes).show();
			$('#facebox #' + field_id_no).hide();		
			$('#facebox .' + field_id_no).hide();		
		}
	}

	return;
	
}

function CountGoogleRegistrationConversion(Staging)
{	
	if ((Staging != undefined) && (Staging == 1)) {
			return;
	}
	
	var image = new Image(1,1);
	image.src = "http://www.googleadservices.com/pagead/conversion/1053179974/?value=1.31&amp;label=rHgjCOCBSRDGgJn2Aw&amp;guid=ON&amp;script=0";
	return;
}


function CountGoogleEmailConversion()
{	
	var image = new Image(1,1);
	image.src = "http://www.googleadservices.com/pagead/conversion/1053179974/?value=0.25&amp;label=O841CI7MZRDGgJn2Aw&amp;guid=ON&amp;script=0";
	return;
}

function UpdateEmailAddress(EmailAddress)
{
	var	WebServiceURL	= "/API/server/user/UserServer.php";
	var RPCName			= "user.create_user_record";		
	var	Parameters		= new Object;
	var UserUniqueID	= readCookie("BDUniq");;
	var DoCall			= false;
	
	if (UserUniqueID.length > 0) {
		DoCall			= true;
		Parameters.UserUniqueID = UserUniqueID;
	}
	
	if (EmailAddress.length > 0) {
		Parameters.EmailAddress = EmailAddress;
	}


	if (DoCall == true) {
		GetSimpleRPCData(DoneUpdateEmailAddress,WebServiceURL,RPCName,Parameters);
	}

}



function	DoneUpdateEmailAddress()
{
	//	Count Google Conversion
	
	_uacct = 'UA-4972639-3';
	urchinTracker("/0895253434/goal");

	//	Update the User Data
	
	GetUserData();
	return;
}

function GetRandomQuote()
{
	var	WebServiceURL		= "/API/server/quote/QuoteServer.php";
	var RPCName				= "quote.get_random_quote";		
	var	Parameters			= new Object;
	Parameters.QuoteLength 	= 40;
	
	GetSimpleRPCData(ShowFamousQuote,WebServiceURL,RPCName,Parameters);
}

function GetFaceBoxFieldByID(FieldName)
{
    var    ReturnValue  = "";

	// alert("Field: " + FieldName);
	
	if ( $('#facebox').length ) {
        ReturnValue    =    $('#facebox #'+FieldName).val();
		// alert("1: " + ReturnValue);
	}
	
	if (!ReturnValue) {
  		ReturnValue	= $('#'+FieldName).val();
		// alert("2: " + ReturnValue);
	}
	
	return ReturnValue;
	/*
    try {
        if (ReturnValue.length > 0) {
            return ReturnValue;
        }   
    }
    catch (err) {}
   
  	ReturnValue	= $('#'+FieldName).val();

	if (ReturnValue == undefined) {
		return "";
	}
	
	return ReturnValue;
	*/
}

function ShowFamousQuote(xml,result)
{
	
	NextQuote	=	$("scalar[id='Quote']",xml).text();
	NextAuthor	=	" " + $("scalar[id='AuthorURL']",xml).text() + " ";
	
	$('.divQuoteText').html("&quot;" + NextQuote + "&quot;?");
	$('.divAuthorName').html(NextAuthor);
	setTimeout("GetRandomQuote()", 30000);
	
}

/* Until we actually do something with the data, not a lot of point in calling it! */
/*
$(document).ready(function(){
	setTimeout("GetUserData()", 30000);
});
*/

function GetUserData()
{
	var	WebServiceURL	= "/API/server/user/UserServer.php";
	var RPCName			= "user.publicuserinfo";		
	var	Parameters		= new Object;
	var	UserSessionID	= readCookie("TLC");
	var UserUniqueID	= readCookie("BDUniq");;
	var DoCall			= false;
	
	if (UserSessionID.length > 0) {
		DoCall			= true;
		Parameters.UserSessionID = UserSessionID;
	}
	
	if (UserUniqueID.length > 0) {
		DoCall			= true;
		Parameters.UserUniqueID = UserUniqueID;
	}
	
	Parameters.IgnoreKickApps	= 1;
	Parameters.CountSessions	= 0;
	
	if (DoCall == true) {
		GetSimpleRPCData(ShowUserData,WebServiceURL,RPCName,Parameters);
	}
}

/*

The ShowUserData routine is called when we receive the PublicUserInfo 
call back. It is used to update every "changable" field in on the site
When you have finished processing it, the "setTimeout" forks of another 
request in 30 seconds

*/

function ShowUserData(xml,result)
{
	//	Check the content of the new and old user box
	
	OldText	=	$(".userboxtext").text();
	
	/*
	NewText	=	"MyNewText";
	if (OldText != NewText) {
		$(".userboxtext").fadeOut();
		$(".userboxtext").text(NewText);
		$(".userboxtext").fadeIn();		
	}
	*/
	
	setTimeout("GetUserData()", 60000);
}

/*
function setExpiryCookie(name,value,ExpiryMinutes) {	
	document.cookie =
  			name + "=" + value + ";expires=0";
}
*/

function RevealQuote(AnswerOn)
{	

	switch (AnswerOn) {
		
		case (1):	$('.revealQuoteAuthor').hide();
					$('.divQuoteAuthor').animate({ opacity: "show" }, "slow");
					break;
		 
	}

}

function GetFaceBoxField(FieldName)
{
	var faceboxField = "";
	
	if ( $('#facebox').length ) {
		faceboxField = "#facebox #" + FieldName;		
		$('#StatusLine').text("#facebox #" + FieldName);      
	}
	else {
		faceboxField = "#" + FieldName;
		$('#StatusLine').text("#" + FieldName);      
	}
	
	//setTimeout("CheckFaceBox('FieldID')", 5000);
	return faceboxField;
}

/*

This function adds a paramater to a URL. If necessary
it sticks it before the e.g. #FLASHGAME anchor. It's
used in e.g. mini_tournament.js to add the URL for the game
to play.

*/

function	AddGETParameter(InputURL,Parameter)
{
	InputURL = InputURL.trim();
	var	AnchorPos	=	InputURL.indexOf('#');
	var	AnchorText	=	"";
	
	if (AnchorPos >= 0) {
		AnchorText	=	InputURL.substr(AnchorPos);
		InputURL	=	InputURL.substr(0,AnchorPos);
	}
	
	if (InputURL.indexOf("?") < 0) {
		InputURL 	+= "?";
	}
	else {
		var	LastPos			=	InputURL.length - 1;
		var	LastChar		=	"";
		if (LastPos > 0) {
			LastChar	=	InputURL.substr(LastPos,1);	
		}
		if (LastChar != "&") {
			InputURL +=	"&";
		}
	}

	InputURL	+=	Parameter + AnchorText;
	return	InputURL;
	

}
