/* ---------- jQuery Events ---------- */

jQuery(document).ready(function() {
	// register rollover graphics for login button
	jQuery('.login_submit').hover(
		function() { // mouseover
			jQuery(this).addClass('login_submit_rollover');
		},
		function() { // mouseout
			jQuery(this).removeClass('login_submit_rollover');
		}
	);

	// create hidden iframe - which MUST be done on document-ready as per IE7 "feature": http://www.clientcide.com/code-snippets/manipulating-the-dom/ie-and-operation-aborted/
	jQuery(document).find('body').append('<iframe id="asyncplaceholder" style="position: absolute; left: -10000px;" src="about:blank"></iframe>');

	// when document loads, explicitly update the show/hide status of the labels (some browsers pre-fill username/password, etc)
	updateLabelsVisible();
});

/*
 * Any <a> with class='asynclogout' will be invoked asynchronously to avoid redirecting user to non-visits pages.
 * The 'href' must reference the logout action (logout.php?do=logout).
 * The embedded form will be replaced when complete.
 */
jQuery('a.asynclogout').live('click', function(e) {
	e.preventDefault();

	domAjaxWaiting('Logging out...');

	// (re)register iframe-load-listener. the hidden iframe is loaded each time the user clicks on 'a.asynclogout' (see live-listener, below)
	jQuery('#asyncplaceholder').unbind('load');
	jQuery('#asyncplaceholder').load(function() {
		var docLogout;
		if(jQuery.browser.msie) {		
			docLogout = this.contentWindow.document;
		} else {
			docLogout = this.contentDocument;
		}

		var fullLogoutLink = jQuery(docLogout).find('a[href^="login.php?do=logout"]');

		// another AJAX call to re-do logout with 'logouthash'
		if (fullLogoutLink) {
			doRealLogout(window.location.protocol + '//' + window.location.host + '/' + fullLogoutLink.attr('href'));
		} else {
			// session has timed out
			makeStateAnonymous();
		}
	});

	// update the iframe 'src' attribute to load the "error occurred during logout" response, which contains a logout link with the 'logouthash' that will allow logout to succeed.
	jQuery('#asyncplaceholder').attr('src', this.href);
});


/* ---------- Functions ---------- */

/*
 * Updates client state to reflect that user is not logged in (guest access).
 */
function makeStateAnonymous() {
	VB_USERNAME = 'guest';
	domLoginForm();
	if (typeof(updateMediaLoggedInState) == 'function') {
		updateMediaLoggedInState();
	}
}

/*
 * This invokes 'urlWithLogoutHash' (within response of earlier AJAX call), updating the local DOM appropriately on success/failure.
 */
function doRealLogout(urlWithLogoutHash) {
	jQuery.ajax({
		url: urlWithLogoutHash,
		dataType: 'html',
		success: function(XMLHttpRequest, textStatus) {
			makeStateAnonymous();
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			domWelcomeAndLogout();
		},
		type: 'GET'
	});
}

function domAjaxWaiting(message) {
	jQuery('#login').empty();
	jQuery('#login').append('<div class="ajaxloading">' + message + '</div>');
}

function domWelcomeAndLogout() {
	jQuery('#login').empty();
	jQuery('#login').append('\
		<a id="login_welcome" href="' + URL_BBOARD + 'usercp.php">Welcome, ' + VB_USERNAME + '</a>\
		<br/>\
		<a id="login_logout" class="asynclogout" href="' + URL_BBOARD + 'login.php?do=logout">Logout</a>\
	');
}

function domLoginForm() {
	jQuery('#login').empty();
	jQuery('#login').append('\
		<form id="EmbeddedLoginForm" name="EmbeddedLoginForm" action="' + URL_BBOARD + 'login.php" method="post" onsubmit="md5hash(vb_login_password, vb_login_md5password, vb_login_md5password_utf, 0);">\
			<input type="hidden" name="s" value="" />\
			<input type="hidden" name="do" value="login" />\
			<input type="hidden" name="url" value="' + window.location + '" />\
			<input type="hidden" name="vb_login_md5password" />\
			<input type="hidden" name="vb_login_md5password_utf" />\
\
			<div id="login_title">\
				LOG IN:\
			</div>\
			<div class="loginrow">\
				<div id="usernamelabel" class="label" onclick="giveFocus(\'usernameinput\');">username</div>\
				<div class="input">\
					<input id="usernameinput" class="bginput" name="vb_login_username" size="10" accesskey="u" tabindex="101" type="text"\
						onfocus="hideLabel(\'usernamelabel\', true);" onblur="hideLabel(\'usernamelabel\', this.value != \'\');" onchange="hideLabel(\'usernamelabel\', this.value != \'\');" />\
				</div>\
			</div>\
			<div class="loginrow">\
				<div id="passwordlabel" class="label" onclick="giveFocus(\'passwordinput\');">password</div>\
				<div class="input">\
					<input id="passwordinput" class="bginput" name="vb_login_password" size="10" accesskey="p" tabindex="102" type="password"\
							onfocus="hideLabel(\'passwordlabel\', true);" onblur="hideLabel(\'passwordlabel\', this.value != \'\');" onchange="hideLabel(\'passwordlabel\', this.value != \'\');" />\
				</div>\
			</div>\
\
			<div class="loginrow" style="margin-top: 10px;">\
				<input class="login_submit" type="image" src="' + URL_BBOARD + 'images/v2/spacer.gif" alt="GO" />\
				<div style="width: 30px; height: 1px;"></div>\
				<a id="login_newuser" href="' + URL_BBOARD + 'register.php">New User?</a>\
			</div>\
			<div class="clear"></div>\
		</form>\
	');
	
	updateLabelsVisible();
}

/*
 * Hides the login form label with the given id.
 */
function hideLabel(labelId, hide) {
	var label = document.getElementById(labelId);
	if (label) {
		label.style.visibility = (hide ? 'hidden' : 'visible');
	}
}

/*
 * Gives focus to the the login form input with the given id.
 */
function giveFocus(inputId) {
	var input = document.getElementById(inputId);
	if (input) {
		input.focus();
	}
}

/*
 * If the login form is in DOM, ensures that the labels are hidden when applicable.
 * Note that some browsers may pre-fill form values, etc.
 * Extra defensive checks are made to ensure nothing happens when login form is in DOM.
 */
function updateLabelsVisible() {
	var form = document.getElementById('EmbeddedLoginForm');
	
	if (form == null) {
		// embedded form is not currently in the DOM
		return false;
	}
	
	hideLabel('usernamelabel', form.vb_login_username.value != '');
	hideLabel('passwordlabel', form.vb_login_password.value != '');
}
