Application = Class.create();
Application.prototype = {
	///
	user : null,
	shopppingCart : null,
	loginFunc : null,
	currentSection: null,
	checkout : false,
	coursepreloaded : "",
	///CLASS BODY
	initialize: function() {
		this.HistoryManager = new HistoryManager();
		this.SectionManager = new SectionManager();
		this.shopppingCart = new ShopCart();
		this.user = new Usuario();
		this.section = null;
    },
	init: function() {
		this.onLogout();
		///
		Event.observe($("login"), "click", this.loginClick.bindAsEventListener(this) );
		///
		this.listenForEvent( this.HistoryManager, 'SectionLoad', true, "onSectionLoad" );
		this.listenForEvent( this.user, 'onLogin', true, "onLogin" );
		this.listenForEvent( this.user, 'onLogout', true, "onLogout" );
		this.listenForEvent( this.shopppingCart, 'onNewItem', true, "onNewItem" );
		this.coursepreloaded = this.getQueryParam("course");
		if(this.getQueryParam("section")=="login")
		    this.loadSection(5);
		else
		    this.loadSection(0);
		this.user.checkSession();
		this.shopppingCart.checkSession();
    },
	loadSection: function(num){
		//if is same section dont load;
		if(this.currentSection == num){
			return;
		}
		//alert("current = "+this.currentSection+"  next = "+num)
		
		this.HistoryManager.loadSection(num);
	},
	onSectionLoad: function(evt){
		var n = evt.event_data.data.num;
		///
		n = ( n > 7 && !this.user.isLogged) ? 5 : n;
		n = ( n == 5 && this.user.isLogged) ? 8 : n;
		n = (n==7 && this.shopppingCart.isEmpty()==true) ? 6 : n;
		this.section = this.SectionManager.load(n);
		if(this.section != false){
			this.currentSection = n;
		}
	},
	loginClick : function(){
		if(!this.user.isLogged){
			//lo lle vo al login
			this.loadSection(5);
		}else{
			this.user.logout();
			//lo deslogueo
		}
	},
	onLogin: function(evt){
		$("my_account").style.display = "";
		$("login").innerHTML = "Logout";
		$("username").innerHTML = "Welcome " + this.user.data.fname +" " + this.user.data.lname + "!";
	},
	onLogout: function(evt){
		$("my_account").style.display = "none";
		$("login").innerHTML = "Login";
		$("username").innerHTML = "&nbsp;";
		// if in restricted area, send to login
		if(this.currentSection > 7){
			this.loadSection(5);
		}
	},
	onNewItem: function(evt){
		var obj = $("shop_cart");
		var items = evt.event_data.data.total;
		items = (items == 0) ? "" : "("+items+")";
		obj.innerHTML = "View Shopping cart " + items;
		///alert("nuevo item");
	},
	getQueryParam: function(p){
	  var query = window.location.search.substring(1);
	  var vars = query.split("&");
	  for (var i=0;i<vars.length;i++) {
	    var pair = vars[i].split("=");
	    if (pair[0] == p) {
	      return pair[1];
	    }
	  } 
	  return "";
	}
	
}
Object.extend( Application.prototype, Event.Listener )
var App = new Application();
Event.observe(window, "load", App.init.bindAsEventListener(App));