LoginOverseer = {

	loginObserver: null,
	ajaxLoginUrl: 'services/LoginAjaxBox.html',
	observeCount: 0,
	base: '',

	init: function() {
		this.base = document.getElementsByTagName('base')[0].href;
		if($('login-image')) {
			this.loginObserver = setInterval(this.observeLoginImage.bind(this), 1000);
		}
		this.ajaxLogin();
	},
	
	ajaxLogin: function() {
		new Ajax.Request(this.base+this.ajaxLoginUrl, {
			method: 'post',
			onSuccess: this.ajaxUpdate.bind(this)
		});
	},
	
	ajaxUpdate: function(x, json) {
		if($('login-iframe')) {
			$('login-iframe').innerHTML = x.responseText;
			loginInit();
		}
	},
	
	observeLoginImage: function() {
		if($('login-image') && cookieGet('logged_in_complete') == 1) {
			this.ajaxLogin();
			clearInterval(this.loginObserver);
		}
		this.observeCount++;
		if(this.observeCount > 20)
			clearInterval(this.loginObserver);
	}

};

/**
 * Get value from the document cookie
 *
 * @param string name Name of the variable to retrieve
 * @return mixed
 */
function cookieGet(name)
{
    name = name + "=";
    var cookies = document.cookie.split(';');
 
    for (var i = 0; i < cookies.length; i++) {
        var c = cookies[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1, c.length);
        }
        if (c.indexOf(name) === 0) {
            return c.substring(name.length, c.length);
        }
    }
 
    return null;
}

document.observe('dom:loaded', function() { LoginOverseer.init() } );

