/**
 * This file is for any default javascript functions needed throughout the CMS
 */


$(document).ready( function(){
    //Do whatever you want when the page loads
    
    //Form errors
    $('.field .error .invalid').hover( function(){
        $(this).parent().children('.errors').fadeIn();
    }, function(){
        $(this).parent().children('.errors').fadeOut();
    });
    
    //Bunch of default confirm messages
    $('a.js_delete').click( function(){ return confirm("Are you sure?"); });
    
});

/**
 * Flash Alerts in Status Bar on the bottom of the CMS
 */
function flashAlert(level, message, timeout ){
    
    if( !timeout ) timeout = false
    
    if( !level.match(/notice|warning|loading|success|error/) ){
        alert("Invalid alert type. Use notice, warning, success, or error.");
        return false;
    }
    
    //fade out old message and put up the new one
    $('#cms_bottomMenu .status').fadeOut( 150, function(){
        $('#cms_bottomMenu .status').html( message );
        $('#cms_bottomMenu .status').removeClass('notice warning loading success error').addClass( level );
        $('#cms_bottomMenu .status').fadeIn();
        
        if (timeout) flashTimeout(timeout);
    });
    
    return true;
}

function flashTimeout( time ){
    setTimeout( "$('#cms_bottomMenu .status').fadeOut()", time * 1000 );
}


/***********Being Ajax Login Material ***************/

var loginLock = false; //Don't try to open two logins at once
var loginSuccess = false; //Don't allow closing until logged back in

//Catch unauthorised jQuery ajax to prompt for re-login
$.ajaxSetup({
	statusCode: {
		401: function() {
			promptLogin();
		}
	}
});

/*Creates and populates the login modal dialog*/
function promptLogin(){
	//Locking required to  prevent multiple logins
	if (loginLock) {return false;}
	loginLock = true;
	loginSuccess = false;

	//Make Embed the form in a new div
	$('body').append('<div id="loginOverlay"></div>');
	$('head').append('<link rel="stylesheet" href="/css/login.css" type="text/css" />');
	getForm();

	//Make it into a magical dialog
	$('#loginOverlay').dialog({
		modal: true,
		draggable: false,
		closeTest: "",
		resizable: false,
		closeOnEscape: false,
		width: 426,
		height: 389,
		beforeClose: function (event, ui) {
			return loginSuccess;
		}
	});
}

function getForm() {
	//This checks if there are incomplete ajax requests, if there are, try again later.
	//TIt's meant to avoid a problem with csrf tokens in asynchronous calls
	if ($.active > 0 ) {
		setTimeout("getForm();", 100);
	} else {
		$.ajax({
			url: "/login", 
			statusCode: { 
				401: function (data) { 
					$('#loginOverlay').html(data.responseText); 
					//Catch form submissiona for ajax request
					$('#cms_login .prettyform').attr('action', 'javascript:ajaxAuth();');
				} 
			} 
		});
	}
}

//Performs a login attempt via ajax
function ajaxAuth() {
	var dataString  = 'signin%5Busername%5D='+$('#signin_username').val()+'&signin%5Bpassword%5D='+$('#signin_password').val()+'&signin%5B_csrf_token%5D='+$('#signin__csrf_token').val()+'&login=Login';
	$.ajax({
		type: "POST",
		url: "/login",
		data: dataString,
		statusCode: {
			401: function (data) {
				$('#cms_login .error').html("The username and/or password is invalid.");
			}
		},
		success: function() {
			//Unlock everything and get rid of the dialog.
			loginSucces=true;
			$('#loginOverlay').dialog("close");
			$('#loginOverlay').dialog("destroy");
			$('#loginOverlay').remove();
			loginLock = false;

			//Set the site in the background if you're a superadmin(only they have the dropdown)
			var dropdown = $('#cms_topMenu form.sites_available #site');
			if (dropdown.length>0) {
				selectSite(dropdown.attr('value'));
			}

			replaceCsrfTokens();
		}
	});
}

//Sets a superadmin's site via ajx
function selectSite(siteId) {
	dataString = "site="+siteId+"&_csrf_token=dontmatter";
	$.ajax({
		type: "POST",
		url: "/sites/switch",
		data: dataString,
		statusCode: {
			401: function(data) {
				//donothing
			}
		}
	});
}

//Your cookie has changed, which invalidates all your csrf tokens.
//Let me fix that for you...
function replaceCsrfTokens() {
	$.ajax({
		type: "GET",
		url: window.location.href, //Refresh this window via ajax
		success: function(data) {
			var tokens = $(data).find('input[id*="csrf_token"]'); //Find all the tokens in the new page
			for (var i=0; i < tokens.length; i++) {
				$('#'+tokens[i].id).val(tokens[i].value);//Replace the old ones
			}
		},
		error: function() {
			flashAlert('error', 'Failed to recover from login expiration. Please refresh the page.', 10);
		}
	});

}

/******************End of Ajax login material *******************/

