/*
 * Purpose:	Provide the main engine behind "Firstrun" and "Sign In".
 *
 * CVS: $Id: actions.js,v 1.3.16.1.4.1 2007/05/23 23:28:39 stanb Exp $
 *
 * This file is a part of the Real Networks software library.
 * Copyright (C) 2001 Real Networks, Inc.
 * All rights reserved.
 *
 */

/* Initialize global variables */
var brokenPageId = "";
var NETSTATUS = -1;
var LOADSTATUS = -1;
var STATUS = -1;

var prevPages = new Array();
var prevLength = 0;

/** Initialize main data arry, this will hold all of
  * the form data as it it collected.
  * Initialize and set the error flag.
  */
var data = new Array();
var plyrObj = parent.window.external;

var threads = new Array();
function startThread( action, time2start )
{
	threads[threads.length] = setTimeout(action, time2start);
}

function killThreads()
{
	for( var i=0; i<threads.length; i++)
	{
		clearTimeout(threads[i]);
	}
}

/* Define shift function for Arrays since IE doesn't support it */
Array.prototype.shift = function()
{
	firstElement = this[0];
	this.reverse();
	this.length = Math.max(this.length-1,0);
	this.reverse();
	return firstElement;
}

/* Define unshift function for Arrays since IE doesn't support it */
Array.prototype.unshift = function()
{
	this.reverse();
	for( var i=arguments.length-1; i>=0; i-- )
	{
		this[this.length]=arguments[i]
	}
	this.reverse();
	return this.length
}
/* Define a nice array copy function */
Array.prototype.copy = function( tempArray )
{
	this.length = 0;
	for(var i=0; i<tempArray.length; i++)
	{
		this[this.length] = tempArray[i];
	}
}

/* Define a nice array uniquification method */
Array.prototype.uniquify = function()
{
	var tempArray = new Array();
	main:
	for(var i=0; i<this.length; i++)
	{
		for(var k=0; k<tempArray.length; k++)
		{
			if( tempArray[k].value == this[i].value )
			{
				continue main;
			}
		}
		tempArray[tempArray.length] = this[i];
	}
	this.copy(tempArray);
}

var t_list = "";
/* New comparison function to handle sorting languages and countries */
function compareFormDataItem( item1 ,item2 )
{
	var i = 0;
	var f = true;
	var a = item1.text.replace(/\W/g,"");
	var b = item2.text.replace(/\W/g,"");
	var limit = Math.min(a.length, b.length)-1;
	var i = 0;
	for( ; i<limit; i++)
	{
		if( a.charCodeAt(i) > b.charCodeAt(i) )
                        return 1;
		if( a.charCodeAt(i) < b.charCodeAt(i) )
                        return -1;
	}
	return (a.length == limit+1)?-1:1;
}

/* Attempt to prepopulate the country and language values */
function initLocale()
{
	var sysLang = navigator.systemLanguage.toLowerCase();
	var sysLangRE;
	var cc=sysLang;
	if( sysLang.length == 2 )
	{
		sysLangRE = new RegExp( "^"+sysLang.substring(0,2)+"$" );
	}
	if( sysLang.length == 5 )
	{
		sysLangRE = new RegExp( "^"+sysLang.substring(0,2)+"."+sysLang.substring(3)+"$" );
		cc = sysLang.substring(3);
	}
	for( var i=0; i < languageList.length; i++ )
		if( sysLangRE.test(languageList[i].value) )
			data["language"] = languageList[i].value;
	for( var i=0; i < countryList.length; i++ )
		if( countryList[i].value == cc )
			data["country"] = countryList[i].value;
}

var configDone=(plyrObj.PlayerProperty("configurationcomplete") >= 1)?true:false;

/* Get stream auth stuff */
var authArray=new Array("hidden_web_url","hidden_stream_url","hidden_web_param","hidden_stream_param");
for( var i=0; i<authArray.length; i++ )
{
	data[authArray[i]] = plyrObj.PlayerProperty(authArray[i]);
}

var error = false;
var validating = false;
var debugStatus = new String(plyrObj.PlayerProperty("debugstatus"));

/*** Collection of action functions triggered
 ***   by the page buttons or default actions **/
function loginAction()
{
	validating = true;
	collectFormData();
	validateForm();
	if( ! error )
	{
		/* Render the contacting server image */
		renderContacting( frsubbody );
		startThread("attemptLogin();",500);
	}else{
		startThread("currentPage.render(frsubbody);error = false;",300);
	}
	validating = false;
}

function confirmSettings()
{
	/* ensure the user is online */
	if( (plyrObj.IsNetConnected()==0)||(plyrObj.PlayerProperty("WORKOFFLINE")==1) )
	{
		brokenPageId = currentPage.id;
		if (currentPage.id != "offline")
			prevPages[prevLength++] = currentPage;
		currentPage = pages["offline"];
		startThread("currentPage.render(frsubbody);",300);
		return;
	}

	focusItem=null;
	if( firstrun && ! iconSet )
	{
		setDeskTopShortcut();
	}
	/* call the server in another thread */
	startThread("postLoginSuccess();",500);
}

function confirmacctAction()
{
	validating = true;
	collectFormData();
	validateForm();
	if( ! error )
	{
		/* Render the contacting server image */
		renderContacting( frsubbody );
		startThread("confirmSettings();",500);
	}else{
		startThread("currentPage.render(frsubbody);error = false;",300);
	}
	startThread("validating = false;",600);
}

function getAccountAction()
{
	collectFormData();
	error = false;
	prevPages[prevLength++] = currentPage;
	currentPage = pages["account"];
	startThread("currentPage.render(frsubbody);",300);
}

function getSigninAction()
{
	collectFormData();
	error = false;
	prevPages[prevLength++] = currentPage;
	data["haveacct"] = true;
	currentPage = pages["login"];
	startThread("currentPage.render(frsubbody);",300);
}

function cancelAction()
{
	document.location="http://rp/command:closewindow";
}


function nextAction()
{
	validating = true;
	collectFormData();
	validateForm();
	if( ! error )
	{
		prevPages[prevLength++] = currentPage;
		currentPage = currentPage.next;
		currentPage.render(frsubbody);
	}else{
		currentPage.render(frsubbody);
		error = false;
	}
	validating = false;
}

function retryAction()
{
	error = false;
	errorcode = 0;
	if (brokenPageId != ""){
		if (prevLength > 0) {
			--prevLength;
		}
		currentPage = pages[brokenPageId];
		startThread("currentPage.render(frsubbody);",300);
	} else if (currentPage.id == "offline"){
		retryConnectAction();
	} else if (currentPage.id == "generror") {
		retryLoadAction();
	}
}

function nextLoadAction()
{
	if (getOnlineStatus()){
		initAllData();
		initLocale();
		data["user_name"] = user_name;
		currentPage.next = pages["login"];
	}else{
		currentPage.next = pages["offline"];
	}

	currentPage = currentPage.next;
	startThread("currentPage.render(frsubbody);",300);
}


function retryLoadAction()
{
	LOADSTATUS = -1;
	resetWait();
	renderContacting( frsubbody );
	startThread("attemptUpload()", 500);
	startThread("checkLoadStatus();",500);
}

function CreateAccount()
{
	data["step"] = "createacct";
	var serviceParam = "";
	var fullDataSet = "";
	var functRE=/^(copy)|(uniquify)|(shift)|(unshift)$/;

	login_username = urlHexEncode( data["user_name"].split(",")[0] );
	login_password = urlHexEncode( data["password"].split(",")[0] );

	for( i in data )
	{
		if( ! functRE.test(i) )
			fullDataSet += "&" + i + "=" + urlHexEncode( data[i] );
	}

	serviceParam = getServiceParam( data["user_name"] );

	var results = plyrObj.AuthenticateUser(login_username, login_password, 0, fullDataSet, serviceParam);

	if( debugStatus == "true" )	{
		alert("AuthenticateUser return code = "+results);
	}
	if( results > 0 )
	{
		/** Account is created successfully **/
		if( firstrun && ! iconSet )
		{
			/* Drop icons if required */
			setDeskTopShortcut();
		}
		prevPages[prevLength++] = currentPage;
		data["step"] = "";
		currentPage =  currentPage.next;
		currentPage.render( frsubbody );
		return;
	}
	/* Received an error code, find out what it means */
	error = true;
	switch( results )
	{
		case (-1):
			/* Bad password */
			currentPage.formItems[1].error = true;
			currentPage.formItems[2].error = true;
			break;
		case (-4):
			/* Bad Username */
			currentPage.formItems[0].error=true;
			break;
		case (-16):
		case (-17):
			/* Username already exists */
			errorcode = 016;
			currentPage.formItems[0].error=true;
			break;
		default:
			/* All other errors */
			brokenPageId = currentPage.id;
			prevPages[prevLength++] = currentPage;
			currentPage = pages["generror"];
			break;
	}
	currentPage.render( frsubbody );
    error = false;
    errorcode = 0;
}

function attemptCreateAcct()
{
	/* ensure the user is online */
	if( (plyrObj.IsNetConnected()==0)||(plyrObj.PlayerProperty("WORKOFFLINE")==1) )
	{
		brokenPageId = currentPage.id;
		if (currentPage.id != "offline")
			prevPages[prevLength++] = currentPage;
		currentPage = pages["offline"];
		startThread("currentPage.render(frsubbody);",300);
		return;
	}

	focusItem=null;

	startThread("CreateAccount();",500);
}

function createacctAction()
{
	validating = true;
	collectFormData();
	validateForm();
	if( ! error )
	{
		/* Render the contacting server image */
		renderContacting( frsubbody );
		startThread("attemptCreateAcct();",500);
	}else{
		startThread("currentPage.render(frsubbody);error = false;",300);
	}
	validating = false;
}

function retryConnectAction()
{
	NETSTATUS = -1;
	LOADSTATUS = -1;
	resetWait();
	renderContacting( frsubbody );
	attemptConnect();
	startThread("checkLoadStatus();",500);
}

function connectAction()
{
	NETSTATUS = -1;
	LOADSTATUS = -1;
	resetWait();
	prevPages[prevLength++] = currentPage;
	renderContacting( frsubbody );
	attemptConnect();
	startThread("checkLoadStatus();",500);
}

function backAction()
{
	collectFormData();
	error = false;
	errorcode = 0;

	if(prevLength > 0){
		currentPage = prevPages[--prevLength];
		prevPages[prevLength] = null;
		startThread("currentPage.render(frsubbody);",300);
	}
}

function finishAction()
{
	collectFormData();
	validateForm();
	authenticateUser();
}

function catchEvent( val )
{
	/** Catch the event codes from buttons
  	 ** Then trigger the appropriate action function */
	if( val == "undefined" ) return;
	if( validating )return;
	window.status +=  val + "Action()";
	eval( val + "Action()" );
}

function validateForm()
{
	/** Validate all the form field values in the currentPage **/
	var isbad = new Boolean(true);
	if (currentPage.formItems != null){
		for( var i=0; i < currentPage.formItems.length; i++ )
		{
			isbad = !currentPage.formItems[i].validate();
			currentPage.formItems[i].error = isbad;
			error = (isbad)?isbad:error;
		}
	}
}



function genericDataValidation()
{
	/* Verify that required fields have a value matching their format */
	var validateRegX = new RegExp( this.format );
	if( ! this.required ) return true;
	return validateRegX.test( data[ this.id ] );
}

function emailValidation()
{
	if( ! this.required ) return true;
	var hasAtRE = new RegExp("^[^\@]+\@[^\@]+$");
	var properSizeRE = new RegExp( this.format );
	return hasAtRE.test( data[ this.id ] ) && properSizeRE.test( data[ this.id ] );
}

function postalCodeValidation()
{
	if( ! this.required ) return true;
	/* Special case validation for postal codes */
	var usRE = "^\\s*(([\\d]{5})|([\\d]{5}\\-[\\d]{4}))\\s*$";
	var nonUSRE = "^\\s*[\\w\\d\\s\\-\\,\\/]{2,}\\s*$";
	var validateRegX = new RegExp( ( (data["country"].toLowerCase()=="us")?usRE:nonUSRE ) );
	return validateRegX.test( data[ this.id ] );
}


function confirmPwdValidation()
{
	/* Check that Confirm Password is equal to Password */
	return ((data[ this.id ] == data["password"]) && (data[ this.id ].length >= 6 ));
}

function collectFormData()
{
	/** Look through all forms in all frames and get the data
	  * for the main data array.
	  * form element names will be the index vor the array and
	  * the values the values.
	  * Allows overwriting data values and pre-population of
	  * form fields.
    */
	for( var i=0; i<document.frames.length; i++ )
	{
		for( var j=0; j< document.frames[i].document.forms.length; j++ )
		{
			for( var k=0; k<document.frames[i].document.forms[j].elements.length; k++ )
			{
				var feObj = document.frames[i].document.forms[j].elements[k];
				if( feObj.name && (feObj.name != "") )
				{
					data[ feObj.name ] = processFormElement( feObj );
				}
			}
		}
	}
}

function processFormElement( frmElementObj )
{
	/** Return the value of the form field based
	 ** upon the type of form field             */
	switch( frmElementObj.type )
	{
		case "text":
		case "textarea":
		case "password":
		case "hidden":
			return frmElementObj.value;
			break;
		case "select-one":
			return frmElementObj.options[frmElementObj.selectedIndex].value;
			break;
		case "checkbox":
			return ( (frmElementObj.checked)?frmElementObj.value:"" )
			break;
		default:
	}
		/* Need to implement:
			select-multiple
			radio
			(ignore others)
	 	*/
	 return "unknown";
}

function  showPage( url )
{
	/* make sure the user is online before attempting to open page */
	if( (plyrObj.IsNetConnected()==0) || ( plyrObj.PlayerProperty("WORKOFFLINE")==1) )
	{
		brokenPageId = currentPage.id;
		if (currentPage.id != "offline")
			prevPages[prevLength++] = currentPage;
		currentPage = pages["offline"];
		startThread("currentPage.render(frsubbody);",300);
		return;
	}
	var nw = window.open( url, "nw", "HEIGHT=400,WIDTH=780,scrollbars,resizeable=1");
}

/* Handle Cancel action */

var closeAction = 2;

var sessionid = 0;

function getServiceParam( user_field )
{
	return "&service="+user_field.substring( user_field.indexOf(",") +1);
}

function RPOnCloseRequest()
{
	if (plyrObj.PlayerProperty("configurationcomplete")==1 || LOGIN) {
		if (currentPage.id=="generror") {
			plyrObj.PlayerProperty("ConfigurationCountDec")=1;
		}
		killThreads();
		return 0;
	}
	else {
		if (currentPage == pages["welcome"] || currentPage == pages["nag"] || contactingPage == true )
		{
			var language = parent.window.external.PlayerProperty("LANGUAGEID");
			var cnclWin = window.showModalDialog("cancel.html",language,"dialogHeight:"+cancel_page_height+"px; dialogWidth:"+cancel_page_width+"px; center:yes; scroll:no; unadorned:yes; status:no; resizable:no; help:no; close:no");
			killThreads();
			return (cnclWin=="cancel")?0:2;
		}else{
			killThreads();
			return 0;
		}
	}
	if(closeAction==0)killThreads();
	return closeAction;
}

var sessionid = 0;


function utf8FromScalar( val )
{
	/* Create URL encoded utf-8	values from a scalar int */
	var output = "";
	/* Single Byte Values */
	if( (val & 0x7F) == val )
	{
		return "%" + ( val & 0x7F ).toString(16);
	}
	/* Two Byte translation */
	if( ( val & 0x07FF ) == val )
	{
		output += "%" + ( ( val>>6 ) | 0xC0 ).toString(16);
		output += "%" + ( ( val & 0x3F ) | 0x80 ).toString(16);
		return output;
	}
	/* Three byte translation */
	if( (val & 0xFFFF) == val )
	{
		output += "%" + (( val >> 12 ) | 0xE0 ).toString(16);
		output += "%" + ((( val >> 6 ) &  0x3F ) | 0x80 ).toString(16);
		output += "%" + (( val & 0x3F ) | 0x80 ).toString(16);
		return output;
	}
	/* Four Byte translation */
	if( (val & 0x1FFFFF) == val )
	{
		output += "%" + (( val >> 18 ) | 0xF0).toString(16);
		output += "%" + ((( val >> 12 ) & 0x3F ) | 0x80 ).toString(16);
		output += "%" + ((( val >> 6) & 0x3F ) | 0x80 ).toString(16);
		output += "%" + (( val & 0x3F ) | 0x80 ).toString(16);
		return output;
	}
}

function urlHexEncode( str )
{
	/* return the username as single-byte hex encoded values ( %val ) */
	var ret = "";
	for( var i=0; i<str.length; i++ )
	{
		ret += utf8FromScalar( str.charCodeAt( i ) );
	}
	return ret;
}

var login_username = "";
var login_password = "";

function getOnlineStatus()
{
	if (NETSTATUS < 0 || STATUS < 0)
	{
		/* Render the contacting server image, and get rid of the buttons */
		focusItem=null;
		renderContacting( frsubbody );
		if (NETSTATUS < 0)
			startThread("attemptConnect()", 500);
		else
			startThread("attemptUpload()", 500);
	}

	return NETSTATUS && LOADSTATUS;
}

function getPlayerVersion(){
	var raw = plyrObj.RealPlayerVersion;
	return "" + (raw>>28) + "." +
		((raw & 0xFF00000) >> 20) + '.' +
		((raw & 0xFF000) >> 12) + '.' +
		( raw & 0xFFF);
}


function attemptUpload()
{

        var configComplete = parent.window.external.PlayerProperty("ConfigurationComplete") ;

        if(configComplete == "1") {
                 if(top.parent.window.external.PlayerProperty("hidden_pcontrol") != "" &&
                    top.parent.window.external.PlayerProperty("hidden_pcontrol") != null) {

					document.all.dataloader.src = "http://switchboard.real.com/player/?cd=firstrun_acct&loader=3.0&LI="
						+parent.window.external.PlayerProperty("LANGUAGEID") +
						"&PV=" + getPlayerVersion();

				 } else {

					 document.all.dataloader.src = "http://switchboard.real.com/player/?cd=fv2_signin&LI=" +
							  parent.window.external.PlayerProperty("LANGUAGEID") +
							  "&PV=" + getPlayerVersion();

				 }
        } else {
                 document.all.dataloader.src = "http://switchboard.real.com/player/?cd=fv2_firstrun&LI=" +
                          parent.window.external.PlayerProperty("LANGUAGEID") +
                          "&PV=" + getPlayerVersion();
        }

}





function attemptConnect()
{
	/* ensure the user is online */
	if( !pagetest && (plyrObj.IsNetConnected()==0)||(plyrObj.PlayerProperty("WORKOFFLINE")==1) )
	{
		NETSTATUS = 0;
		if (currentPage.id != "offline")
			prevPages[prevLength++] = currentPage;

		currentPage.next = pages["offline"];
		currentPage = currentPage.next;
		startThread("currentPage.render(frsubbody);",300);
		return;
	}else{
		NETSTATUS = 1;
		startThread("attemptUpload()", 500);
	}

	return;
}

function resetWait()
{
	CURRENTWAIT = 0;
}

var MAXWAIT = 30;
var CURRENTWAIT = 0;
function checkLoadStatus()
{
	if( ((CURRENTWAIT++ * 100) >=  MAXWAIT * 1000))
	{
		LOADSTATUS = 0;
		if (NETSTATUS != 1 && currentPage.id != "offline"){
			prevPages[prevLength++] = currentPage;
			currentPage.next = pages["offline"];
			currentPage = currentPage.next;
			startThread("currentPage.render(frsubbody);",300);
		}else if (NETSTATUS == 1){
			if (currentPage.id != "generror")
				prevPages[prevLength++] = currentPage;
			currentPage.next = pages["generror"];
			currentPage = currentPage.next;
			startThread("currentPage.render(frsubbody);",300);
		}
	}
	if( LOADSTATUS < 0 )
	{
		startThread("checkLoadStatus();",100);
		return;
	}
}

function continuePclogin()
{
	var fullDataSet = "";
	/* Service Param removed */
	var functRE=/^(copy)|(uniquify)|(shift)|(unshift)$/;

	for( i in data )
	{
		if( ! functRE.test(i) )
			fullDataSet += "&" + i + "=" + urlHexEncode( data[i] );
	}

	/* Use password, instead of non-existent sessid, no service param (not possible to enter one anyway */
	var results = plyrObj.AuthenticateUser("pclogin", urlHexEncode( data["password"] ), -1, fullDataSet, "");

	if( debugStatus == "true" )
	{
		alert("Parental Controls Authenticate return code = "+results);
	}

	if( results > 0 )
	{
		/** Parental login is created successfull **/
		data["step"] = "";
		focusItem=null;
		currentPage.render = renderForward;
		currentPage.render( frsubbody );
		return;
	}

	/* Received an error code, find out what it means */
	error = true;

	/*
	-25 - API failed
	-26 - API had an INVALID password
	*/
	switch( results )
	{
		case (-1):
		case (-2):
		case (-3):
		case (-4):
		case (-26):
			/* Bad password */
			/* Password does not match */
			errorcode = 026;
			currentPage.formItems[0].error = true;
			break;
		default:
			/* All other errors */
			brokenPageId = currentPage.id;
			prevPages[prevLength++] = currentPage;
			currentPage = pages["generror"];
			break;
	}
	currentPage.render( frsubbody );
	error = false;
	errorcode = 0;
}

function attemptLogin()
{
	/* ensure the user is online */
	if( (plyrObj.IsNetConnected()==0)||(plyrObj.PlayerProperty("WORKOFFLINE")==1) )
	{
		brokenPageId = currentPage.id;
		if (currentPage.id != "offline")
			prevPages[prevLength++] = currentPage;
		currentPage = pages["offline"];
		startThread("currentPage.render(frsubbody);",300);
		return;
	}
	focusItem=null;

	/* continue to parental login if the value is set */
	if (data["step"] == "pclogin")
	{
		startThread("continuePclogin();",500);
	} else {
		login_username = urlHexEncode( data["user_name"].split(",")[0] );
		login_password = urlHexEncode( data["password"] );

		/* call the server in another thread */
		startThread("continueLogin();",500);
	}
}

function continueLogin()
{
	var serviceParam = "";
	var temp="";
	data["user_name"] = data["user_name"].toLowerCase();
	error = false;

	/*  Validate the user */
	serviceParam = getServiceParam( data["user_name"] );

	var testresults = plyrObj.ValidateUser( login_username, login_password, "", serviceParam);
	if( debugStatus == "true" )
	{
		alert("ValidateUser return code = "+testresults);
	}
	if( ! error && ( testresults > 0 ) )
	{
		/* user is good, keep moving on */
		sessionid = testresults;
		if( firstrun ) data["step"] = "login";
		postLoginSuccess();
	}
	else if(testresults <= -255 )
	{
		/* -12019 = server timeout */
		brokenPageId = currentPage.id;
		prevPages[prevLength++] = currentPage;
		currentPage = pages["generror"];
		currentPage.render( frsubbody );
	}else{
		error = true;
		/* 008 - GET_CONSUMER_INFO api failed */
		errorcode = 008;
		currentPage.render( frsubbody );
		error = false;
	}
}

function postLoginSuccess()
{
	var serviceParam = "";
	var fullDataSet = "";

	var functRE=/^(copy)|(uniquify)|(shift)|(unshift)$/;
	if( LOGIN  && !firstrun )
	{
		for( i in data )
		{
			if( ! functRE.test(i) )
				fullDataSet += "&" + i + "=" + urlHexEncode( data[i] );
		}
		serviceParam = getServiceParam( data["user_name"] );
		var results = plyrObj.AuthenticateUser("", "", sessionid, fullDataSet, serviceParam);
		focusItem=null;

		currentPage.render = renderForward;
		currentPage.render( frsubbody );
	}else{
		for( i in data )
		{
			if( ! functRE.test(i) )
				fullDataSet += "&" + i + "=" + urlHexEncode( data[i] );
		}

		serviceParam = getServiceParam( data["user_name"] );
		var results = plyrObj.AuthenticateUser("", "", sessionid, fullDataSet, serviceParam);

		if (data["step"] == "login"){
			if ( plyrObj.PlayerProperty("Language").length > 0 )
				data["language"]	= plyrObj.PlayerProperty("Language");
			if ( plyrObj.PlayerProperty("Country").length > 0 )
				data["country"] 	= plyrObj.PlayerProperty("Country").toLowerCase();
			data["postalcode"]	= plyrObj.PlayerProperty("PostalCode");
			data["gender"]		= plyrObj.PlayerProperty("Gender");
			data["birthyear"]	= plyrObj.PlayerProperty("BirthYear");

			plyrObj.PlayerProperty("Language")	= "";
			plyrObj.PlayerProperty("Country")	= "";
			plyrObj.PlayerProperty("PostalCode")= "";
			plyrObj.PlayerProperty("Gender")	= "";
			plyrObj.PlayerProperty("BirthYear")	= "";
			data["step"] = "";
		}
		prevPages[prevLength++] = currentPage;
		if( currentPage != null && currentPage.next != null )
		{
			currentPage = currentPage.next;
			currentPage.render( frsubbody );
		}
	}
}

function forceOnline()
{
	plyrObj.ForceOnline;
	document.location.href="index.html";
	//retryLoadAction();
}

function authenticateUser()
{
	var fullDataSet = "";
	var serviceParam = "";
	var functRE=/^(copy)|(uniquify)|(shift)|(unshift)$/;
	focusItem=null;
	/* Render the contacting server image */
	renderContacting( frsubbody );

	for( i in data )
	{
		if( ! functRE.test(i) )
			fullDataSet += "&" + i + "=" + data[i];
	}
	serviceParam = getServiceParam( data["user_name"] );
	/* Render the contacting server image, and
		get rid of the buttons                */
	if( (plyrObj.IsNetConnected()==1) && (plyrObj.PlayerProperty("WORKOFFLINE")==0) )
	{
		var results = plyrObj.AuthenticateUser("", "", sessionid, fullDataSet, serviceParam);
		if( debugStatus == "true" )
		{
			alert("AuthenticateUser return code = "+results);
		}
		if( results > 1 && LOGIN)
		{
			currentPage.render = renderForward;
			currentPage.render( frsubbody );
		}else if(results > 1){
			closeAction = 0;
			plyrObj.HandleAction("CloseWindow");
		}else if(results == -9){
			error=true;
			currentPage=pages["confirm"];
			currentPage.render( frsubbody );
		}else{
			brokenPageId = currentPage.id;
			if (currentPage.id != "generror")
				prevPages[prevLength++] = currentPage;
			currentPage = pages["generror"];
			startThread("currentPage.render(frsubbody);",300);
		}
	}else{
		brokenPageId = currentPage.id;
		if (currentPage.id != "offline")
			prevPages[prevLength++] = currentPage;
		currentPage = pages["offline"];
		startThread("currentPage.render(frsubbody);",300);
	}
}

/** Attempt to handle false reloads.  User tried to go forward,back, etc... **/
var allowReload = false;
function handleReload()
{
	if( ! allowReload )
		document.location.href="index.html";
}
var interupt=false;
function trapKeys()
{
	if( interupt )return;

	if( frsubbody.window.event.keyCode == 13 && (! validating) && frsubbody.document.readyState=="complete")
	{
		if(! (frsubbody.window.event.srcElement.href) )
		{
			catchEvent( currentPage.dfltButton.action );
		}
	}
	return;
}

function falseSubmit()
{
	interupt=true;
	catchEvent( currentPage.dfltButton.action );
	interupt=false;
	return false;
}

var focusThrd;
var focusItem=null;

function fixFocus()
{
	if( frsubbody.document.readyState != "complete" )
	{
		focusThrd=startThread("fixFocus()",500);
		return;
	}
	if( (focusItem)&&focusItem!=null)
	{
		focusItem.focus();
	}
}

function arrayFromList( list )
{
	var listAry = new Array();
	/* Is there anything to check? */
	if( list.length==0 ) return listAry;
	/* clean out the extra commas */
	list=list.replace(/\,+/g,",");
	list=list.replace(/^\,+/g,"");
	list=list.replace(/\,+$/g,",");
	/* do the actual parsing */
	var st = list.indexOf(",");
	var next = 0;
	while( st >0 )
	{
		listAry[ listAry.length ]=list.substring( next, st );
		list = list.substring( st+1, list.length );
		st = list.indexOf(",");
	}
	/* get the last value if there is one */
	if( list.length>0 )listAry[ listAry.length ]=list;
	return listAry;
}


var iconSet = false;

function loadExtraParameters()
{
	var params = plyrObj.PlayerProperty("param_list")+"";
	var paramAry = new Array();
	if( params.length == 0 )return;
	paramAry = arrayFromList( params );
	for( var i=0; i<paramAry.length; i++ )
	{
		data[ paramAry[i] ] = plyrObj.PlayerProperty( paramAry[i] );
	}
}
loadExtraParameters();

var off_actions_loaded = true;
