/**
 * 	login.js
 *
 *  Function to add login stuff to website.
 */
$(document).ready(function(){

	var $login_page = 'https://www.ayso104.org/tools/login2.php';
	var $check_login = '/check_login.php';

	var $logged;

	var loggedIn = function(name) {
		$logged = 1;
		$("#loginlink").hide().data('logged',1);
		$("#welcome").html('Welcome '+name);
		$(".loggedin").show();
	}
	
	var loggedOut = function() {
		$logged = 0;
		$(".loggedin").hide();
		$("#loginlink").show().data('logged',0);
	}
	
	checkLogin = function() {
		return $logged;
	}
	
	var getSID = function() {
		var nameEQ = 'PHPSESSID=';
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}
	
	var $sid = getSID();
	$('#sid').val($sid);
	
	$.get($check_login, 
		function(data){
			if ( data != null && data.logged == "1" ) {
				// Logged in
				loggedIn(data.name)
			} else {
				// Not logged in
				loggedOut()
			}
		}, "json"
	);
	
	$login_dialog = $("#d_login").dialog({ 
		autoOpen: false, 
		modal: true, 
		title: 'Login',
	});
	$login_dialog.dialog('option', 'buttons', { 
		"Ok": function() {
			postCORS($login_page, $("#login_form").serialize(),
				function(data) {
					if ( data != null && data.logged == "1" ) {
						$login_dialog.dialog("close"); 
						loggedIn(data.name);
					} else {
						alert('login error');
					}
				}, "json"
			);
		},
		"Cancel": function() { $(this).dialog("close"); }
	});
	$('#loginlink').live('click', function() {
//		console.log('Click');
		$login_dialog.dialog('open');
		return false;
	});
	$('#logoutlink').live('click', function() {
		postCORS($login_page, { action: 'logout', session: $sid },
			function(data){
				loggedOut();
			},"json"
		);
		return false;
	});
	$("#tabs").bind("tabsload",function(event, ui) {
		// When we load ajax content from a tab, 
		// we need to show the hidden elements if we're logged in.
		if ( $logged ) {
			$(".loggedin").show();
		}
	});
	$('#d_login').live('keyup', function(e){
		if (e.keyCode == 13) {
			$(':button:contains("Ok")').click();
		}
	});
});
/**
 * This is for Cross-site Origin Resource Sharing (CORS) requests.
 *
 * Additionally the script will fail-over to a proxy if you have one set up.
 *
 * @param string   url      the url to retrieve
 * @param mixed    data     data to send along with the get request [optional]
 * @param function callback function to call on successful result [optional]
 * @param string   type     the type of data to be returned [optional]
 */
function getCORS(url, data, callback, type) {
    try {
        // Try using jQuery to get data
        jQuery.get(url, data, callback, type);
    } catch(e) {
        // jQuery get() failed, try IE8 CORS
        if (jQuery.browser.msie && window.XDomainRequest) {
            // Use Microsoft XDR
            var xdr = new XDomainRequest();
            xdr.open("get", url);
            xdr.onload = function() {
                callback(this.responseText, 'success');
            };
            xdr.send();
		}
    }
}

/**
 * This method is for Cross-site Origin Resource Sharing (CORS) POSTs
 *
 * @param string   url      the url to post to
 * @param mixed    data     additional data to send [optional]
 * @param function callback a function to call on success [optional]
 * @param string   type     the type of data to be returned [optional]
 */
function postCORS(url, data, callback, type)
{
    try {
        // Try using jQuery to POST
        jQuery.post(url, data, callback, type);
    } catch(e) {
        // jQuery POST failed
        var params = '';
        for (key in data) {
            params = params+'&'+key+'='+data[key];
        }
        // Try XDR
        if (jQuery.browser.msie && window.XDomainRequest) {
            // Use XDR
            var xdr = new XDomainRequest();
            xdr.open("post", url);
            xdr.send(params);
            xdr.onload = function() {
                callback(xdr.responseText, 'success');
            };
        }
    }
}
/**
 *
 * Files that include this function also need a dialog box like so:
 *
   <div id="d_login">
	<form class="login_form" id="login_form" action="" method="post">
	<input type="hidden" id="sid" name="session" value="" />
	<fieldset>
		<ol>
			<li>
				<label for="login">User Name:</label> 
				<input id="login" type="text" size="15" name="login" /> 
			</li>
			<li>
				<label for="password">Password:</label>
				<input id="password>" type="password" size="15" name="password" /> 
			</li>
		</ol>
	</fieldset>
	</form>
	</div> 
**/
