MCE.Session= {		
	TRIG_LOGGED_IN: 'mc.session.logged_in',
	TRIG_LOGGED_OUT: 'mc.session.logged_out',
	TRIG_ANONYMOUS_CREATED: 'mc.session.anonymous_created',
	TRIG_CUSTOMER_CHANGED: 'mc.session.customer_changed',
	TRIG_PASSWORD_CHANGED: 'mc.session.password_changed',

	customer: MCHttpSession.customer,
	invoice: MCHttpSession.invoice,
	getCustomerFullName: function(){ return (this.customer==null ? null : (this.customer.is_anonymous ? "" : this.customer.first_name+" "+this.customer.last_name)); }, 
	getCustomerId: function() {return (this.customer!=null ? this.customer.id : null);},
	isLoggedIn: function(){ return (this.customer!=null && !this.customer.is_anonymous ? true : false ); },
	setCustomer: function(customer) {
		oldCustomerId = (this.customer!=null ? this.customer.id : null);
		this.customer = this._fixCustomer(customer);
		MCHttpSession.customer = customer;
		if(oldCustomerId!=null && ( this.customer==null || this.customer.id!=oldCustomerId ) ) this.setInvoice(null);
	},
	_fixCustomer: function(customer){
		if(customer!=null && customer.day_phone==null) customer.day_phone=customer.mobile_phone; //legacy: use day_phone instead of mobile_phone
		if(customer!=null && customer.is_send_notifications && customer.interests==null) customer.interests='4'; //interests not send with customer. Default to regular mail
		return customer;
	},
	getCustomer: function(){ return this._fixCustomer(this.customer);},
	setInvoice: function(invoice) { this.invoice = invoice; MCHttpSession.invoice = invoice; },
	getInvoice: function(){ return this.invoice;},

	login: function(credentialsMap,succesCallback,noSuccesCallback,errorCallback,callbackContext){
		if(!this.isLoggedIn()){
			Session = this;
			MCE.JewelLabs.login(credentialsMap,this.getCustomerId(),function(customer){
				Session.setCustomer(customer);
				if(succesCallback!=null) succesCallback.call((callbackContext!=null ? callbackContext : window),Session.getCustomer());
				MCE.TriggerManager.trigger(Session.TRIG_LOGGED_IN,Session);},
				noSuccesCallback,errorCallback,callbackContext);
		}
	},
	logout: function(succesCallback,noSuccesCallback,errorCallback,callbackContext){
		if(this.isLoggedIn()){
			Session = this;
			MCE.JewelLabs.logout(function(message){
				Session.setCustomer(null);//resets invoice as well
				if(succesCallback!=null) succesCallback.call((callbackContext!=null ? callbackContext : window));
				MCE.TriggerManager.trigger(Session.TRIG_LOGGED_OUT,Session);},
				noSuccesCallback,errorCallback,callbackContext);
		}
	},
	createAnonymousCustomer: function(succesCallback,noSuccesCallback,errorCallback,callbackContext){
		if(this.customer==null){
			Session = this;
			MCE.WaitingBox.show('#createBasket');
			MCE.JewelLabs.createAnonymousCustomer(function(customer){
				Session.setCustomer(customer);//resets invoice as well
				if(succesCallback!=null) succesCallback.call((callbackContext!=null ? callbackContext : window),Session.getCustomer());
				MCE.TriggerManager.trigger(Session.TRIG_ANONYMOUS_CREATED,Session);},
				noSuccesCallback,errorCallback,callbackContext);
		}
	},
	insertUpdateCustomer: function(customerMap,succesCallback,noSuccesCallback,errorCallback,callbackContext){
		Session = this;
		if(!this.isLoggedIn()){//insert
			MCE.WaitingBox.show('#insertCustomer');
			MCE.JewelLabs.insertCustomer(customerMap,function(customer){
				MCE.WaitingBox.show('#logIn');
				Session.login({ email: customerMap["email_address"], password: customerMap["password"]},succesCallback,noSuccesCallback,errorCallback,callbackContext);},
				noSuccesCallback,errorCallback,callbackContext);
		}else{//update
			MCE.WaitingBox.show('#updateCustomer');
			MCE.JewelLabs.updateCustomer(Session.customer.id,customerMap,function(customer){
				Session.setCustomer(customer);
				if(succesCallback!=null) succesCallback.call((callbackContext!=null ? callbackContext : window),Session.getCustomer());
				MCE.TriggerManager.trigger(Session.TRIG_CUSTOMER_CHANGED,Session);},
				noSuccesCallback,errorCallback,callbackContext);
		}
	},
	requestNewPassword: function(email,password,succesCallback,noSuccesCallback,errorCallback,callbackContext){
		Session = this;
		MCE.JewelLabs.requestNewPassword(email,password,this.getCustomerId(),function(message){
			if(succesCallback!=null) succesCallback.call((callbackContext!=null ? callbackContext : window));
			MCE.TriggerManager.trigger(Session.TRIG_PASSWORD_CHANGED,Session);},
			noSuccesCallback,errorCallback,callbackContext);
	}
};

MCE.LoginForm= {
	init: function(fadeSpeed,successTimeout, errorTimeout, validationTimeout){
		var Login = this;
		this.fadeSpeed = fadeSpeed;
		this.$loginDiv = $('div.article.teaser.login.bh-toggle-form');
		this.$loginForm = $('div.article.teaser.login form');
		this.currentMessageSelector = null;
		this.messageWidth=null;
		this.$loginCaption = $('div.article.teaser h3#login');
		this.$logoutCaption = $('div.article.teaser h3#logout');
		this.originalLogoutCaptionHtml = this.$logoutCaption.text();
		this.loggedInName=(!MCE.Session.isLoggedIn() ? null : MCE.Session.getCustomerFullName());
		if(this.loggedInName!=null){
			this.setToLoggedIn({data:Login},MCE.Session);
			this.$loginCaption.hide();
			this.$logoutCaption.show();
		}else{
			this.$loginCaption.show();
			this.$logoutCaption.hide();
		}
		MCE.TriggerManager.bind(this.$loginDiv,MCE.Session.TRIG_LOGGED_IN,this,this.setToLoggedIn);
		MCE.TriggerManager.bind(this.$loginDiv,MCE.Session.TRIG_LOGGED_OUT,this,this.setToLoggedOut);
		MCE.TriggerManager.bind(this.$loginDiv,MCE.Session.TRIG_CUSTOMER_CHANGED,this,this.changeCustomerName);

		$('input[type=submit]',this.$loginForm).click(function(event){
			event.preventDefault();
			if((checkResult=Login.check())==null){
				Login.showMessage('h3#loggingIn',fadeSpeed,-1,null);
				MCE.Session.login(Login.getValueMap(),function(){
					//context is MCLogin
					Login=this;
					this.showMessage('h3#success',this.fadeSpeed,successTimeout,function(){
						Login.$loginCaption.trigger('click');
					});
				},function(){
					//context is MCLogin
					this.showMessage('h3#unsuccessfull',this.fadeSpeed,successTimeout,null);
				},function(){
					//context is MCLogin
					this.showMessage('h3#failure',this.fadeSpeed,errorTimeout,null);
				},Login);
			}else{
				Login.showMessage('h3#'+checkResult,this.fadeSpeed,validationTimeout,null);
			}
		});
	},
	setToLoggedIn: function(event,mc_session){
		Login = event.data;
		Login.loggedInName = mc_session.getCustomerFullName();
		Login.$logoutCaption.html(Login.originalLogoutCaptionHtml.replace("##NAME##",Login.loggedInName));
		Login.$loginDiv.addClass('loggedin');
		Login.$loginCaption.fadeOut(Login.fadeSpeed);
		Login.$logoutCaption.fadeIn(Login.fadeSpeed);
	},
	setToLoggedOut: function(event,mc_session){
		Login = event.data;
		Login.$loginCaption.fadeIn(Login.fadeSpeed);
		Login.loggedInName = null;
		Login.$loginDiv.removeClass('loggedin');
		Login.$logoutCaption.fadeOut(Login.fadeSpeed, function(){
			Login.$logoutCaption.html(Login.originalLogoutCaptionHtml);
		});
	},
	changeCustomerName: function(event,mc_session){
		Login = event.data;
		Login.loggedInName = mc_session.getCustomerFullName();
		Login.$logoutCaption.html(Login.originalLogoutCaptionHtml.replace("##NAME##",Login.loggedInName));
	},
	check: function(){
		status=null;
		var fields = this.getValueMap();

		var noEmail = fields.email==null;
		var noPassword = fields.password==null;
		var noCredentials = noEmail && noPassword;

		if(noCredentials){
			status='noCredentials'; 
		}else if(noEmail){
			status='noEmail'; 
		}else if(noPassword){
			status='noPassword'; 
		}

		return status;
	},
	getValueMap:function(includeEmpty, emptyValue){
		var all = (includeEmpty!=null && includeEmpty==true ? true : false);
		var nill = (emptyValue!=null ? emptyValue : null);

		var defaultsMap = {};
		$('label',this.$loginForm).each(function(index,labelElem){
			$labelElem = $(labelElem);
			defaultsMap[$labelElem.attr('for')]=$labelElem.text();
		});
		var fields = this.$loginForm.serializeArray();
		var fieldMap = {};
		for(var i=0;i<fields.length;i++){
			var isNotEmpty = fields[i].value!=defaultsMap[fields[i].name];
			if(all || isNotEmpty ){
				fieldMap[fields[i].name]=(isNotEmpty ? fields[i].value : nill);
			}
		}
		return fieldMap;
	},
	serialize:function(fieldMap){
		var serializedMap = '';
		for(var key in fieldMap){
			serializedMap+=(serializedMap.length>0 ? '&' : '')+escape(key)+'='+escape(fieldMap[key]);
		}
		return serializedMap;
	},
	showMessage:function(messageSelector, fadeSpeed, timeout, callBack){
		var Login = this;
		if(this.currentMessageSelector != messageSelector){
			if(this.currentMessageSelector==null){
				$('div.login.message',this.$loginForm).slideDown(fadeSpeed,function(){
					Login.messageWidth = $('h3.message.hidden',Login.$loginForm).width();
					$('h3.message',Login.$loginForm).width(Login.messageWidth+'px');//width:159px;
					Login.setMessage(messageSelector, fadeSpeed, timeout, callBack);

				});
				if(this.messageWidth!=null){
					this.currentMessageSelector = messageSelector;
					if(this.currentMessageSelector != null) $(this.currentMessageSelector,this.$loginForm).fadeIn(fadeSpeed);
				}

			}else if(messageSelector==null){
				if(this.currentMessageSelector != null) $(this.currentMessageSelector,this.$loginForm).fadeOut(fadeSpeed);
				this.currentMessageSelector = messageSelector;
				$('div.login.message',this.$loginForm).slideUp(fadeSpeed);
				this.setMessage(messageSelector, fadeSpeed, timeout, callBack);
			}else{
				this.setMessage(messageSelector, fadeSpeed, timeout, callBack);
			}
		}else{
			this.setMessage(messageSelector, fadeSpeed, timeout, callBack);
		}
	},
	setMessage: function(messageSelector, fadeSpeed, timeout, callBack){
		var Login = this;
		if(this.currentMessageSelector != messageSelector){
			if(this.currentMessageSelector != null) $(this.currentMessageSelector,this.$loginForm).fadeOut(fadeSpeed);
			this.currentMessageSelector = messageSelector;
			if(this.currentMessageSelector != null) $(this.currentMessageSelector,this.$loginForm).fadeIn(fadeSpeed);
		}
		if(timeout>0){
			setTimeout(function(){
				Login.showMessage(null,fadeSpeed,-1,null);
				if(callBack!=null){
					callBack.call(this);
				}
			},timeout);
		}
	},

	toggleForm: function()
	{
		var Login = this;
		var $loginDiv = $('div.article.teaser.login.bh-toggle-form');

		Login.originalLogoutCaption = $('>h3#logout',$loginDiv).html();
		$loginDiv.find('h2, h3').css({cursor: 'pointer'});
		$loginDiv.addClass('minimized');
		$loginDiv.find('form').toggle();
		$loginDiv.find('h2, h3#login').click(function(){
			if ( $(this).parent().hasClass('minimized') ) {
				$(this).parent().find('form').slideDown({
					easing: "easeInOutExpo",
					time: 600
				});
			}else{
				Login.showMessage(null,Login.fadeSpeed,-1,null);
				$(this).parent().find('form').slideUp({
					easing: "easeInOutExpo",
					time: 600
				});
			}
			$(this).parent().toggleClass('minimized');	
		});
		$loginDiv.find('h3#logout').click(function(){
			MCE.Session.logout();
		});
	}
};


