var xmlRequest = null;

function customLoginBehavior()
   {
   // Does nothing by default.  Pages that need extra functionality upon login should redefine this function.
//alert("base customLoginBehavior");
   }

// set up the defaults for all AJAX calls made with jQuery
$.ajaxSetup({
   url: '/rpc.php',
   type: 'POST',
   dataType: 'html'
});

function getXMLRequest() {
	if(xmlRequest && xmlRequest.readyState != 4 && xmlRequest.readyState != 0) {
		//alert("Another operation is in progress--please wait until it finishes...");
		return null;
	}

	try {
		xmlRequest = new XMLHttpRequest();
	} catch (e) {
		try {
			xmlRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}

	xmlRequest.open("POST", "rpc.php", true);
	xmlRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

	xmlRequest = xmlRequest;

	return xmlRequest;
}

// LOGIN WINDOW HANDLERS

// popup login window
var _login_done_js = null;

function doLogin_save(result) {
			logged_in = true;

			var e = document.getElementById("header_auth");

			// FIXME Shouldn't have hardcoded content here...
			if(e)
				e.innerHTML = result + "&nbsp;&nbsp; <A HREF='myHomeGigapans.php'>My Home</A> | <A HREF='" + window.location.href + ((window.location.href.indexOf("?") > 0) ? "&header_mode=logout" : "?header_mode=logout") + "'>Logout</A>";

         // perform any required custom behavior
//alert("doLogin_save doing customLoginBehavior");
         customLoginBehavior();
}

function doLogin_process() {
	if(xmlRequest.readyState == 4) {
		var result = xmlRequest.responseText;

		if(result.indexOf("ERROR") < 0) {
			doLogin_save(result);
			dialog_hide(_login_done_js);
      } else
			alert("Bad username and/or password.");
	}

	return true;
}

function doLogin() {
	var r = getXMLRequest();

	if(! r)
		return false;

	var username = document.getElementById("dialog_username").value;
	var password = document.getElementById("dialog_password").value;

	r.onreadystatechange = doLogin_process;
	r.send("proc=login&username=" + username + "&password=" + password + "&url=" + window.location.href);

	return true;
}

function doForgotPassword()
   {

   var email = document.getElementById("dialog_email").value;

   $.ajax(
      {
      data:
         {
         proc: 'forgot_password',
         email: email
         },
      complete: function()
         {
         dialog_hide();
         },
      success: function()
         {
         alert("If "+email+" is the email address you used to register, we have mailed a new password to you.\n\n" +
               "If you have more than one email address and are not certain which you used when registering, it's OK to try more than one.");
         }
      });

   return true;
   }

function shiftFocusUponEnterKeyEvent(evt, elementIdToGetFocus, codeToExecute)
   {
   evt = (evt) ? evt : ((event) ? event : null);
   if (evt)
      {
      var element = document.getElementById(elementIdToGetFocus);
      if (evt.keyCode == 13)
         {
         if (element)
            {
            element.focus();
            }
         if (codeToExecute)
            {
            eval(codeToExecute);
            }
         }
      }
   }

function login(done_js, container) {
	_login_done_js = done_js;
	var login_html = '';

	login_html += '<DIV CLASS="dialog_login">';
	login_html += '		<DIV CLASS="field">';
	login_html += '			<SPAN CLASS="label">username</SPAN>';
	login_html += '			<INPUT TYPE="text" ID="dialog_username" onfocus="this.select();" onkeyup="shiftFocusUponEnterKeyEvent(event,\'dialog_password\');">';
	login_html += '		</DIV>';

	login_html += '		<DIV CLASS="field">';
	login_html += '			<SPAN CLASS="label">password</SPAN>';
	login_html += '			<INPUT TYPE="password" ID="dialog_password" onfocus="this.select();" onkeyup="shiftFocusUponEnterKeyEvent(event,\'submit\',\'doLogin();\');">';
	login_html += '		</DIV>';

	login_html += '		<INPUT TYPE="button" VALUE="login" ID="submit" onClick="doLogin();">';

	login_html += '		<A onClick="forgotPassword();" ID="forgot_password">I forgot my password</A>';

	login_html += '		<P>';
	login_html += '			or, <A HREF="createAccount.php">Create a FREE account now</A>';
	login_html += '		</P>';
	login_html += '</DIV>';

	return dialog_ask("Login", login_html, container,'','dialog_username');
}

function forgotPassword() {
	var forgot_password_html = "";

	forgot_password_html += '<DIV CLASS="dialog_forgot_password">';
	forgot_password_html += '	<DIV CLASS="field">';
	forgot_password_html += '		<SPAN CLASS="label">e-mail</SPAN>';
	forgot_password_html += '		<INPUT TYPE="text" ID="dialog_email" onfocus="this.select();" onkeyup="shiftFocusUponEnterKeyEvent(event,\'submit\',\'doForgotPassword();\');">';
	forgot_password_html += '	</DIV>';

	forgot_password_html += '	<INPUT TYPE="button" VALUE="send new password" ID="submit" onClick="doForgotPassword();">';
	forgot_password_html += '</DIV>';

	dialog_hide();

	return dialog_ask("Forgot Password", forgot_password_html, document.getElementById("flash_viewer_spacer_top"),'','dialog_email');
}

function isLoggedIn() {
	return logged_in;
}


// PAGE LOAD HANDLER

var _original_page_width = 0;

// redirects to URL that saves screen size in session
function fetchWindowSize(force) {
   if(_have_window_size == false || force == true) {

      if(document.body.clientWidth == _original_page_width && _have_window_size == true) {
         return true;
      }

      var queryString = "?";
      if (window.location.search != '') {
         var keyValuePairs = window.location.search.substring(1).split("&");
         for (var j=0; j < keyValuePairs.length; j++) {
            var keyValue = keyValuePairs[j].split("=");
            if ("window_width" != keyValue[0] && "window_height" != keyValue[0]) {
               queryString += keyValuePairs[j] + "&";
            }
         }
      }
      // todo: consider using this algorithm, for more accurate measurements: http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
      queryString += "window_height=" + document.body.clientHeight + "&window_width=" + document.body.clientWidth;

      // todo: consider passing this using AJAX, so we don't have to force a page reload
      window.location.href = window.location.protocol + "//" +
                             window.location.host +
                             window.location.pathname +
                             queryString +
                             window.location.hash;

      _have_window_size = true;
   }

	return true;
}

// Allow widgets to register for page load notification
var _load_callbacks = Array();
function doPageLoadCallbacks(e) {
	for(var i in _load_callbacks) {
		if(typeof(_load_callbacks[i]) != "string")
			continue;

		eval(_load_callbacks[i]);
	}

	return true;
}

function registerPageLoadCallback(f) {
	return _load_callbacks.push(f);
}

// Allow widgets to register for flash browser load notification
var _flash_load_callbacks = Array();
function doFlashBrowserLoadCallbacks() {
   for(var i in _flash_load_callbacks) {
		if(typeof(_flash_load_callbacks[i]) != "string")
			continue;

		eval(_flash_load_callbacks[i]);
	}

	return true;
}

function registerFlashBrowserLoadCallback(f) {
	return _flash_load_callbacks.push(f);
}

// RESIZE HANDLERS
function updateScreenSize() {
	if(_resize_timeout) {
		clearTimeout(_resize_timeout);
		_resize_timeout = null;
	}

	// no graphics on this page require knowing screen size
	if(typeof(_refresh_on_resize) != "undefined") {
		if(_refresh_on_resize != true)
			return false;
	}

	_resize_timeout = setTimeout("fetchWindowSize(true);", 500);
}

function getScreenSize() {
  _original_page_width = document.body.clientWidth;
}

var _resize_callbacks = Array();
function registerPageResizeCallback(f) {
	return _resize_callbacks.push(f);
}

var _resize_timeout = null;
function doPageResizeCallbacks(e) {
	for(var i in _resize_callbacks) {
		if(typeof(_resize_callbacks[i]) != "string")
			continue;

		eval(_resize_callbacks[i]);
	}

	return true;
}

registerPageResizeCallback("updateScreenSize()");
registerPageLoadCallback("getScreenSize()");
