TP.Login = Class.create({
	
	container: null, 
	
	initialize: function(){
	
		window.loginComplete = function() {
			window.location.href = window.location.href.toString();
		}
	
		this.behavior.initialize(this);
	},
	
	loadPage: function(page){
		new Ajax.Request(page, {
			method:'get',
			onSuccess: function(transport) {
				this.insertPage(transport);		
				$('login_frame').src = 'https://' + location.hostname.toString() + '/login/login.html';
			}.bind(this)
		});
		
	},
	
	insertPage: function(transport){
		var isNew = false;
		if(this.container)
			this.container.remove();
		else
			isNew = true;
		
		this.container = new Element('div');
	
		if(isNew)
			this.container.hide();
		
		var response = new String(transport.responseText);
		this.container.innerHTML = response;
		
		$$('body').first().appendChild(this.container);
		
		this.behavior.setupCloseButtons();					
		
		if(isNew)
			Effect.Appear(this.container, {duration:0.5})
		
	},
	
	/**
	 * Behavior setup
	 */
	behavior: {
		login: null,
		
		initialize: function(login){
			this.login = login;
			
			if($('js_login_button'))
				$('js_login_button').observe('click', this.loginButton.bind(this));
		},
		
		loginButton: function(event){
			event.stop();
			this.login.loadPage('/login/secureframe.html');
		}, 
		
		setupCloseButtons: function(){
			this.login.container.select('.close a').each(function(closeButton){
				closeButton.observe('click', function(event){
					event.stop();
					
					Effect.Fade(this.login.container, {duration: 0.5, afterFinish:function(){
						this.login.container.remove();
						this.login.container = null;
					}.bind(this)});
				
				}.bind(this));
				
			}.bind(this));
		}
		
	}
	
});

document.observe('dom:loaded', function(){
	new TP.Login();
});
