// JavaScript Document
var included_files = new Array();
var unload_msg = '';

//  this handles setting everything that needs to be setup as soon as the page is loaded
$().ready(function()
{
	auto_redirect = 0;
	if((window.location["pathname"]=="/login") || (window.location["pathname"]=="/login/")) {
		auto_redirect = 1;
		displayLoginRegisterModal(null);
	}
	bindLoginButtons();
});

function bindLoginButtons()
{
	$('.Login.Button, .silverleaf.login.button').unbind('click');
	$('.Login.Button, .silverleaf.login.button').click(function(e)
	{
		e.preventDefault();
		displayLoginRegisterModal(null);
	});
}

function setConfirmUnload(msg) {
	if(msg)
	{
	    unload_msg = msg;
		window.onbeforeunload = unloadMessage;
	} else
	{
		unload_msg = '';
		window.onbeforeunload = null;
	}
}

function unloadMessage() {
	return unload_msg;
}

function include_once(script_filename) {
	if (!in_array(script_filename, included_files)) {
	included_files[included_files.length] = script_filename;
	include_dom(script_filename);
	}
}

function include_dom(script_filename) {
	var html_doc = document.getElementsByTagName('head').item(0);
	t=script_filename.substring(script_filename.lastIndexOf('.')+1);
	if (t=='js'){
		var file = document.createElement('script');
		file.setAttribute('language','javascript');
		file.setAttribute('type','text/javascript');
		file.setAttribute('src',script_filename);
	}else if (t=='css'){
		var file = document.createElement('link');
		file.setAttribute('rel','stylesheet');
		file.setAttribute('type','text/css');
		file.setAttribute('href',script_filename);
	}
	html_doc.appendChild(file);
	return false;
}

function in_array(needle, haystack) {
    for (var i = 0; i < haystack.length; i++) {
        if (haystack[i] == needle) {
            return true;
        }
    }
    return false;

}

function displayLoginRegisterModal(callback) {
	//alert("Showing you the login form, and then redisplaying the originally requested form...");
	
	var mod_params = {"action": "fetch-login-register-form"};
	createModalPopup(null,true,'auth', mod_params, login_form_display);
	if($('#auth_email', modal).val()=='') $('#auth_email', modal).focus();
	else $('#auth_pwd', modal).focus();
	//$('*:input[type!=hidden]:first', modal).focus();
	/*if($("#auth_email", modal).val().length>0) $("#auth_pwd", modal).focus();
	else $("#auth_email", modal).focus();*/
	//callback(self._name, self.type);
}

function login_form_display(xml) {
	if(typeof $('response-code', xml) == 'undefined')
	{
		// show the form
		$('.modal-status-message', modal).html('<pre>'+$(this).text()+'</pre><p style="margin-top:20px;"><a href="#" class="close button">close</a></p>').show();
		$('.modal-status-message .close.button', modal).click(function(e)
		{
			e.preventDefault();
			$('.modal-status-message', modal).html('').hide();
			$('.modalBody', modal).show();
		});
	} else
	{
		$(xml).find('response-code').each(function(){
			if($(this).text() == "0") {
				$(xml).find('response-message').each(function(){
					$('.modal-status-message', modal).html('<h2>Error</h2><pre>'+$(this).text()+'</pre><p style="margin-top:20px;"><a href="#" class="close button">close</a></p>').show();
					$('.modal-status-message .close.button', modal).click(function(e)
					{
						e.preventDefault();
						$('.modal-status-message', modal).html('').hide();
						$('.modalBody', modal).show();
						hideModal(modal);
					});
				});
			} else if($(this).text() == "1") {
				var modal_body = $('response-message', xml);
				$('.modal-status-message', modal).html('').hide();
				$('.modalBody', modal).html($(modal_body).text()).show();
				
				$('.modal-user-registration-form #reg_email, .modal-user-registration-form #reg_email2', modal).bind('change', function(e)
				{
					email = $('.modal-user-registration-form #reg_email', modal).val();
					email2 = $('.modal-user-registration-form #reg_email2', modal).val();
					
					if((email !='') && (email2 != '') && (email != email2)) {
						$('.reg-msgs', modal).html("The two email addresses you've entered do not match.");
					} else {
						$('.reg-msgs', modal).html("&nbsp;");
					}
				});
				
				//$('#UserRegForm', modal).submit(checkUserRegForm);
				
				$('*:input[type!=hidden]:first', modal).focus();
			} else {
				modal_body  = "<h1>"+$('sl-form', xml).attr("title")+"</h1>";
				$(xml).find('xhtml').each(function(){
					modal_body += $(this).text();
				});
				$('.modal-status-message', modal).html('').hide();
				$('.modalBody', modal).html(modal_body).show();
				$('*:input[type!=hidden]:first', modal).focus();
			}
		});
	}
}
function checkLoginForm(form) {
	
	email = $('#auth_email', form).val();
	pwd = $('#auth_pwd', form).val();
	
	if($('#auth_email', form).val() == '') return false;
	if($('#auth_pwd', form).val() == '') return false;
	
	// everything appears to be okay so we'll make an ajax call to submit the login credentials
	$('.modal-status-message', modal).html('<h1>Logging in...</h1>').show();
	$('.modalBody', modal).hide();
	
	$.ajax({
		'type': "POST",
		async: false,										//  **non-asynchronous call**
		'url': "/cms/ajax/",
		'data': {'mod': "auth",
				 'action': "login",
				 'auto-redirect': auto_redirect,
				 'auth_email': email,
				 'auth_pwd': pwd,
				 'remember_me': $('#remember_me', form).val() },
		'success': userLoginSubmitSuccess,
		'error': ajaxError
	});
	return false;
}

function userLoginSubmitSuccess(xml) {
	$(xml).find('response-code').each(function(){
		if($(this).text() == "0") {
			$(xml).find('response-message').each(function(){
				$('.system-messages', modal).html('<p>Login Failed: '+$(this).text()+'</p>');
				$('#auth_pwd', modal).val('');
				$('.modal-status-message', modal).html('').hide();
				$('.modalBody', modal).show();
				$('#auth_pwd', modal).focus();
			});
		} else if($(this).text() == "1") {
			if(typeof original_modal_callback != "undefined")
			{
				hideModal(modal);
				original_modal_callback(self._name, self.type);
			}
			else
			{
				redirect_url = $('redirect', xml);
				if(typeof(redirect_url) != 'undefined') {
					redirect_url = redirect_url.text();
					if(redirect_url != '')
					{
						$('.modal-status-message', modal).html('<p>Login Succeeded. Redirecting to: '+redirect_url+'</p>');
						window.location.href = $('redirect', xml).text();
					} else
					{
						// reload the current page
						window.location.reload();
					}
				} else
				{
					// reload the current page
					window.location.reload();
					/*
					if(typeof(current_user) == 'undefined') current_user = new Array();
					current_user['display-name'] = $('display-name', xml).text();
					current_user['email'] = $('user-email', xml).text();
					
					var authorization = new Array();
					permissions = $('permissions', xml).text();
					authorization['create'] = permissions.charAt(0);
					authorization['modify'] = permissions.charAt(1);
					authorization['approve'] = permissions.charAt(2);
					authorization['publish'] = permissions.charAt(3);
					
					checkAuthentication();
					
					if(typeof(page_id) == 'undefined') page_id = 0;
					if(typeof(page_lang) == 'undefined') page_lang = '';
					if(typeof(timezone) == 'undefined') timezone = -600;
					
					//html = '<script type="text/javascript">var page_id = '+page_id+';';
					//html += 'var session_lang = "'+page_lang+'";';
					//html += 'server_timezone = '+timezone+';';
					//html += '</script>';
					
					html = '<script type="text/javascript" src="/_shared/scripts/content-editor/ckeditor/ckeditor.js"></script>';
					html += '<script type="text/javascript" src="/cms/_scripts/silverleaf-admin.js"></script>';
					html += '<link href="/_shared/jquery/jqmodal/jqModal.css" rel="stylesheet" type="text/css" /><link href="/skins/silverleaf/admin.css" rel="stylesheet" type="text/css" />';
					
					$('body').append(html);
					
					$('.modal-status-message', modal).html('<p>Welcome back, '+current_user['display-name']+'!</p>');
					hideModal(modal, 3000);
					
					if(authorization['create']==1) $('body').addClass('auth-create');
					if(authorization['modify']==1) $('body').addClass('auth-modify');
					if(authorization['approve']==1) $('body').addClass('auth-approve');
					if(authorization['publish']==1) $('body').addClass('auth-publish');
					*/
				}
			}
		} else {
			modal_body  = "<h1>"+$('sl-form', xml).attr("title")+"</h1>";
			$(xml).find('xhtml').each(function(){
				modal_body += $(this).text();
			});
			$('.modal-status-message', modal).html('').hide();
			$('.modalBody', modal).html(modal_body).show();
			$('*:input[type!=hidden]:first', modal).focus();
		}
	});
}

function checkAuthentication() {
	if(typeof(current_user) != 'undefined')
	{
		$('body').addClass('authenticated');
		$('.silverleaf.login.button').closest('div').html('<a href="/me/" title="click here to visit your personal page" class="silverleaf my-page button">'+current_user['display-name']+'</a> | <a href="./?action=logout" title="Click here to end your session and log out" class="silverleaf logout button">Logout</a>');
		return true;
	} else
		return false;
}

function checkUserRegForm(form) {
	
	email = $('#reg_email', form).val();
	email2 = $('#reg_email2', form).val();

	if((email !='') && (email2 != '') && (email != email2)) {
		$('.reg-msgs', modal).html("The two email addresses you've entered do not match.");
	} else {
		$('.reg-msgs', modal).html("&nbsp;");
	}
	
	if((email !='') && (email2 != '') && (email != email2)) {
		$('.reg-msgs', form).html("The two email addresses you've entered do not match.");
	} else if(email == "" || email2 == "") {
		$('.reg-msgs', form).html("&nbsp;");
	} else {
		$('.reg-msgs', form).html("&nbsp;");
		
		// everything appears to be okay so we'll make an ajax call to submit the new user registration information
		$('.modal-status-message', modal).html('<h1>Sending user registration information...</h1>').show();
		$('.modalBody', modal).hide();
		
		$.ajax({
			'type': "POST",
			async: false,										//  **non-asynchronous call**
			'url': "/cms/ajax/",
			'data': {'mod': "users",
					 'action': "create-new-user",
					 'email': email },
			'success': userRegSuccess,
			'error': ajaxError
		});
	}
	return false;
}

function userRegSuccess(xml) {
	$(xml).find('response-code').each(function(){
		if($(this).text() != "1") {
			$(xml).find('response-message').each(function(){
				$('.modal-status-message', modal).html('<h2 style="margin-bottom:15px;">Error:</h2>'+$(this).text()+'<p style="margin-top:20px;"><a href="#" class="close button">close</a></p>').show();
				$('.modal-status-message .close.button', modal).click(function(e)
				{
					e.preventDefault();
					$('.modal-status-message', modal).empty().hide();
					$('.modalBody', modal).show();
					//hideModal(modal);
				});
			});
		} else if($(this).text() == "1") {
			$('.modal-status-message', modal).empty().hide();
			$('.modalBody', modal).empty().html($('response-message', xml).text()).show();
			$('*:input[type!=hidden]:first', modal).focus();
		}
	});
	return false;
}

function submitActivationCode(form) {
	
	key = $('#activation-key', form).val();
	pwd = $('#pwd', form).val();
	
	if(key == '') return false;
	
	if(pwd != $('#pwd2', form).val()) {
		$('.system-messagess', form).text('The two passwords you entered do not match.');
		return false;
	}
	
	// everything appears to be okay so we'll make an ajax call to submit the form data
	$('.modal-status-message', modal).html('<h1>Sending activation key...</h1>').show();
	$('.modalBody', modal).hide();
	
	$.ajax({
		'type': "POST",
		async: false,										//  **non-asynchronous call**
		'url': "/cms/ajax/",
		'data': {'mod': "users",
				 'action': "activate-pwd",
				 'key': key,
				 'new_pwd': pwd,
				 'uid': $('#uid', form).val() },
		'success': userAcctActivationSuccess,
		'error': ajaxError
	});
	return false;
}

function userAcctActivationSuccess(xml) {
	$(xml).find('response-code').each(function(){
		if($(this).text() == "0") {
			$(xml).find('response-message').each(function(){
				$('.system-messages', modal).html('<p>Account activation failed: '+$(this).text()+'</p>');
				//$('#auth_pwd', modal).val('');
				$('.modal-status-message', modal).html('').hide();
				$('.modalBody', modal).show();
			});
		} else if($(this).text() == "1") {
				if(typeof original_modal_callback != "undefined")
				{
					if(typeof modal !== 'undefined')
					{
						hideModal(modal);
						delete modal;
					}
					original_modal_callback(self._name, self.type);
				} else 
				{
					$('.modal-status-message', modal).html('').hide();
					$('.modalBody', modal).html('<p>Account activation succeeded! You should automatically be redirected to the page you originally requested. If not, <a href="'+$('redirect', xml).text()+'">please click this link to go there immediately.</a></p>').show();
					window.location.href = $('redirect', xml).text();
				}
		} else {
			modal_body  = "<h1>"+$('sl-form', xml).attr("title")+"</h1>";
			$(xml).find('xhtml').each(function(){
				modal_body += $(this).text();
			});
			$('.modal-status-message', modal).html('').hide();
			$('.modalBody', modal).html(modal_body).show();
			$('*:input[type!=hidden]:first', modal).focus();
		}
	});
	return false;
}

function ajaxError(XMLHttpRequest, textStatus, errorThrown)
{
	if(typeof(ajax_status) != 'undefined') ajax_status = '';
	if(typeof(modal) != 'undefined')
	{
		$('.modal-status-message', modal).html('<h2>AJAX request error: &quot;' + textStatus + '&quot; : &quot;' + errorThrown + '&quot;</h2><p>Server response:</p><pre>' + XMLHttpRequest.responseText +'</pre><p style="margin-top:20px;"><a href="#" class="close button">close</a></p>').show();
		$('.modal-status-message .close.button', modal).click(function(e)
		{
			e.preventDefault();
			// show the form
			$('.modal-status-message', modal).html('').hide();
			$('.modalBody', modal).show();
		});
	} else
	{
		alert('AJAX request error: "' + textStatus + ' : "' + errorThrown + "\n\nServer response: " + XMLHttpRequest.responseText);
	}
}

function createModalPopup(modalBody, is_ajax, sl_mod, mod_params, callBack) {
	if($('#modal-window-container').css('display') == "none")
	{
		modal = $('#modal-window-container');
		
		$('.modalBody', modal).hide();
		$('.modal-status-message', modal).html('<h1>Loading content...</h1>').show();
				
		//  set actions for 'close' and 'cancel' buttons
		if(window.onbeforeunload == null)
		{
			$('.modal-button-close, .cancel.button', modal).click(function(e)
			{
				e.preventDefault();
				$(this).parents('.silverleaf.modal').removeClass('modal-page-properties');
				hideModal(modal);
				setConfirmUnload(false);		// turn this off it was set AFTER the modal form was requested
			});
		} else
		{
			$('.modal-button-close, .cancel.button', modal).click(function(e)
			{
				e.preventDefault();
				$(this).parents('.silverleaf.modal').removeClass('modal-page-properties');
				hideModal(modal);
			});
		}
		
		revealModal(modal);
		
		if(is_ajax !== false) {
			//  load the modal window contents from the server using AJAX - **non-asynchronous call**
			
			mod_params["mod"] = sl_mod;
			
			/*ajax_data = {'mod': sl_mod,
						 'action': mod_params["action"],
						 'form-id': mod_params["form-id"] };*/
			
			$.ajax({
				'type': "GET",
				async: false,										//  **non-asynchronous call**
				'url': "/cms/ajax/",
				'data': mod_params,
				'success': callBack,
				'error': ajaxError
			});
		} else {
			//  function is being passed HTML content elsewhere on the current page, which should be placed into the 'modalBody' section of the modal window
			$('.modalBody', modal).html(modalBody);
		}
	} else {
		alert('WARNING!!!\n\nThere is already a visible modal window open!\n\nUnable to open new modal window.');
	}
}

//  generic function to display a particular modal window
function revealModal(modal)
{
	$(modal).show();
	$('html, body').scrollTop(0);		//  since our modal popup windows currently always display a set distance from top of the page, we scroll to the top of the page so the user can see the contents of the modal window
}

//  generic function to hide a particular modal window
function hideModal(modal, delay)
{
	if(typeof(delay) == 'undefined') $(modal).hide();
	else $(modal).delay(delay).hide('slow');
}
