/*
 * Copyright 2008 Web Service Solutions, Inc.  All rights reserved.
 */
/*jslint evil: true */

var clientNonce = 1;
var deviceID = Math.ceil(1000000 * Math.random());
var syncSWorld = new SyncSWorld();

function initPage() {
	// BEGIN: No longer necessary. Delete after June 6, 2009
	var hrefLC = window.location.href.toLowerCase();
	if (hrefLC.indexOf("sw2") < 0) {
		//alert("changing to sw2");
		var slash = hrefLC.indexOf("/", 10);
		window.location = hrefLC.substring(0, slash) + "/sw2/index.html";
		return;
	}
	// END

	startheadline();
	//DynarhLIB_preload_images();
	//preloadSW();

	var user = document.getElementById("userID");
	user.focus();
	var password;

	var userIDParam = gup("userID");
	if (userIDParam && userIDParam.length > 0) {
		user.value = decodeURIComponent(userIDParam);
		password = document.getElementById("passID");
		password.focus();
	}
	try {
		syncSWorld.startup();
		var swCookie = syncSWorld.loadObject(syncSWorld.SW_COOKIE);
		var now = new Date();
		var loginDiv = document.getElementById("middle_login");
		var startDiv = document.getElementById("middle_start");
		if (now.getTime() < swCookie.ttl) {
			// userSettingsDTO will be good unless its offline cache was not.
			if (!syncSWorld.userSettingsDTO ||
				!syncSWorld.userSettingsDTO.ICalendarInfoL ||
				typeof swCookie.calUserID == 'undefined') {
				// try to re-use the same deviceID
				swCookie = {};
				swCookie.deviceID = deviceID;

				loginDiv.style.display = "block";
				startDiv.style.display = "none";
			}
			else {
				loginDiv.style.display = "none";
				startDiv.style.display = "block";
			}
		}
		else {
			loginDiv.style.display = "block";
			startDiv.style.display = "none";
		
			var x = "" + swCookie.calUserID;
			if ( (typeof swCookie.calUserID == "string") &&
				(typeof swCookie.sessionID == "undefined") ) {
				var username = document.getElementById("userID");
				username.value = swCookie.calUserID;
				password = document.getElementById("passID");
				password.value = "";
				password.focus();
			}
		}
	} catch(exp) {
		swCookie = {};
	}
	// version
	var currentVersion = document.getElementById("currentVersionID");
	currentVersion.innerHTML = syncSWorld.clientVersion;
	
}

function gotoSwApp() {
	var hrefLC = window.location.href.toLowerCase();
	if (hrefLC.indexOf("scheduleworld") >= 0) {
		window.location="/sw2/swapp.html";
	}
	else if (hrefLC.indexOf("index.html") >= 0) {
		window.location="/sw2/swapp.html";
	}
	else {
		window.location="/sw2/swappDev.html";
	}
}

function signinCallback(answer) {
	var swCookie;
	if (!answer) {
		// If we have an existing swCookie just start the app 
		swCookie = syncSWorld.loadObject(syncSWorld.SW_COOKIE);
		var now = new Date();
		if (swCookie) {
			if (now.getTime() < swCookie.ttl) {
				gotoSwapp();
			}
		}
		alert("Could not continue because the server was not available\nand sw2 is not cached locally.");
		return;
	}
	if (answer.success) {
		// use answer.text here to get text data, or
		// use answer.xml here to get a XMLDocument
		// (only if your server sent XML back)
		var response = swEval(answer.text);
		if (response.failedI18nKey) {
			alert(response.failedI18nKey);
			return;
		}
		//alert("response:" + response.toSource());
		clientNonce = response.nextSyncAnchor;
		if (response.badNonce) {
			signIn();
			return;
		}
		else {
			swCookie = {};
			swCookie.sessionID = response.sessionID;
			swCookie.ttl = response.ttl;
			swCookie.calUserID = response.calUserID;
			swCookie.clientNonce = response.nextSyncAnchor;
			swCookie.deviceID = deviceID; // re-use
			swCookie.password = document.getElementById("passID").value;

			// Also use the flash cookie as a way to let the application
			// know that the user has just logged in and can access x calendars
			swCookie.userSettingsDTO = response.userSettingsDTO;
			syncSWorld.saveObject(syncSWorld.SW_COOKIE, swCookie, gotoSwApp);
		}
	}
	else {
		alert("The server seems to be unavailable and your session has expired.");
	}
}

function signIn() {
	try {
		//alert("signIn()");
		var username = document.getElementById("userID").value;
		if (!username || username.length === 0) {
			alert("Missing username");
			return;
		}
		var re = /[^0-9]/;
		if (re.test(username)) {
			if (username.indexOf("@") < 1) {
				alert("Missing '@' symbol in your email.\n \nUse the email you signed up with\nor your ScheduleWorld ID (number).");
				return;
			}
		}
		var password = document.getElementById("passID").value;
		if (!password || password.length === 0) {
			alert("Missing password");
			return;
		}
	
		var encUser = encodeURIComponent(username);
		var createSession = {};
		createSession.username = username;
		var b64 = syncSWorld.encode(password);
		createSession.passwordB64 = hex_sha256(b64 + clientNonce);
		createSession.deviceID = deviceID;
		createSession.clientNonce = clientNonce;
		var xml = Sarissa.xmlize(createSession, "createSession");
	
		var url = "/sw2/commandV3";
		var rpc = new DlRPC( {
			url			: url,
			callback	: signinCallback,
			args		: { user: encUser },
			data		: xml } );
		rpc.call();
	} catch(ex) {
		alert("Failed signIn():" + ex);
	}
}

function showLogin() {
	document.getElementById("middle_login").style.display="block";
	document.getElementById("middle_start").style.display="none";
}

function showStart() {
	document.getElementById("middle_login").style.display="none";
	document.getElementById("middle_start").style.display="block";
}


