$(document).ready(function(){
    var debug = false;
	MCE.WaitingBox.init(null,null,debug); 
    MCE.Cart.init(null,debug);
    MCE.OrderingPopup.init(null,null,debug); 
    MCE.Ticketing.init(debug); 
	Cufon.refresh();	

});

function ItemInstance(badgeTypeId,badgeTypeName,price){
	this.badgeTypeId = badgeTypeId;
	this.badgeTypeName = badgeTypeName;
	this.price = price;
	this.instancesAvailable = false;
	this.instanceIds = new Array();
	this.instanceTimestamps = new Array();
	this.count =function(){ return this.instanceIds.length; };
	this.totalPrice = function(){ return this.count()*this.price; };
	this.lastInstanceId = function(){ return (this.count()>0 ? this.instanceIds[this.instanceIds.length-1] : null); };
	this.addInstance = function(instanceId, instanceTimestamp){
		if(instanceId!=null){ 
			this.instanceIds.push(instanceId); 
			return this.instanceTimestamps.push(Util.date.parse(instanceTimestamp));f
		}else{
			this.count(); 
		} 
	};
	this.invalidate = function(){ this.instancesAvailable=false; };
	this.prepareForParsingInvoice = function(){
		this.instanceIds = new Array();
		this.instanceTimestamps = new Array();
	};
}
ItemInstance.toString = function(){ return Util.json.toJSON(this,false); };

function Item(id,type,name,startsAt,defaultPrice){
	if(id.id==null){
		this.id = id;
		this.type = type;
		this.name = name;
		this.startsAt = Util.date.parse(startsAt);
		this.defaultPrice = defaultPrice;
	}else{
		//id is actually a show or product object
		var item = id;
		this.id = item.id;
		this.type = type;
		this.name = item.name;
		this.startsAt = Util.date.parse(item.starts_at);
		this.defaultPrice = item.default_price;
	}
	this.valid = false;
	this.itemInstances = {"0":new ItemInstance(0,'Regulier',this.defaultPrice)};
	this.itemInstances["0"].instancesAvailable=true;
	this.getId = function(){return this.type+':'+this.id; };
	this.count = function(){ var count=0; for(var badgeTypeId in this.itemInstances){ count+=this.itemInstances[badgeTypeId].count();} return count; };
	this.totalPrice = function(){ var totalPrice=0.0; for(var badgeTypeId in this.itemInstances){ totalPrice+=this.itemInstances[badgeTypeId].totalPrice();} return totalPrice; };
	this.addItemInstance = function(badgeTypeId,badgeTypeName,price){
		var itemInstance = this.itemInstances[""+badgeTypeId];
		if(itemInstance==null){
			itemInstance = new ItemInstance(badgeTypeId,badgeTypeName,price);
			this.itemInstances[""+badgeTypeId] = itemInstance;
		} else {
			itemInstance.badgeTypeName = badgeTypeName;
			itemInstance.price = price;
		}
		return itemInstance;
	};
	this.invalidate = function(){
		for(var badgeTypeId in this.itemInstances){ 
			if(badgeTypeId!="0"){//regular tickets can not be validated by jewel labs so cannot be invalidated either. Use the special functions for disabling/enabling the selling of regular tickets
				this.itemInstances[badgeTypeId].invalidate();
			}
		} 
		this.valid=false; 
	};
	this.prepareForParsingInvoice = function(){
		for(var badgeTypeId in this.itemInstances){ 
			this.itemInstances[badgeTypeId].prepareForParsingInvoice();
		}
	};
	this.disableRegular = function(){ this.itemInstances["0"].instancesAvailable=false;	};
	this.enableRegular = function(){ this.itemInstances["0"].instancesAvailable=true; };
}
Item.toString = function(){ return Util.json.toJSON(this,false); };

function Cart(debug,cartState){
	this.debug = (debug!=null && typeof(console) !== 'undefined' && console != null ? debug : false);
	
	this.issuedAt = (cartState!=null ? cartState.issuedAt : null);
	this.invoiceId = (cartState!=null ? cartState.invoiceId : null);;
	this.items = new Object();
	this.count = function(){ var count=0; for(var itemId in this.items){ count+=this.items[itemId].count();} return count; };
	this.totalPrice = function(){ var totalPrice=0.0; for(var itemId in this.items){ totalPrice+=this.items[itemId].totalPrice();} return totalPrice; };
	this.addItem = function(id,type,name,startsAt,defaultPrice){
		var itemId = ""+(id.id==null ? id : id.id); //id might actually be a show or product object
		var item = this.items[type+':'+itemId];
		if(item==null){
			item = new Item(id,type,name,startsAt,defaultPrice);
			this.items[type+':'+itemId] = item;
		}
		return item;
	};
	this.invalidate = function(itemId){
		if(itemId==null){
			for(var id in this.items){ this.items[id].invalidate(); }
		}else{
			if(this.items[itemId]!=null) this.items[itemId].invalidate();
		}
	};
	this.prepareForParsingInvoice = function(){
		this.issuedAt=null;
		this.invoiceId=null;
		for(var id in this.items){ this.items[id].prepareForParsingInvoice(); }
	};
	if(cartState!=null){
		for(var itemId in cartState.items){
			csItem = cartState.items[itemId];
			var item = this.addItem(csItem.id,csItem.type,csItem.name,csItem.startsAt,csItem.defaultPrice);
			item.valid = csItem.valid;
			for(var badgeTypeId in csItem.itemInstances){
				csItemInstance = csItem.itemInstances[badgeTypeId];
				itemInstance = item.addItemInstance(csItemInstance.badgeTypeId,csItemInstance.badgeTypeName,csItemInstance.price);
				itemInstance.instancesAvailable = csItemInstance.instancesAvailable;
				itemInstance.instanceIds = csItemInstance.instanceIds;
				itemInstance.instanceTimestamps = csItemInstance.instanceTimestamps;
			}
		}
	}
	this.matchesInvoice = function(invoice){
		if(invoice==null){
			if(this.invoiceId==null && this.count()==0){
				if(this.debug) console.log('cart model matches invoice');
				return true;
			}else{
				if(this.debug) console.log('cart model MISMATCH: invoice is null but cart model not');						
			}
		} else if(invoice.id==this.invoiceId){
			if(Util.date.parse(invoice.issued_at)==this.issuedAt){
				if(invoice.total_amount==this.totalPrice()){
					if((invoice.tickets.length+invoice.items.length)==this.count()){
						for(var i=0;i<invoice.tickets.length;i++){
							ticket = invoice.tickets[i];
							item = this.items['show:'+ticket.show.id];
							if(item==null){ if(this.debug) console.log('cart model MISMATCH: item model show:'+ticket.show.id+' could not be found in cart model'); return false; }
							badgeTypeId = (ticket.badge_id == null ? 0 : ticket.badge.badge_type_id);
							itemInstance = item.itemInstances[badgeTypeId]; //regular itemInstances always exist
							if(itemInstance==null) { if(this.debug) console.log('cart model MISMATCH: badge type model '+badgeTypeId+' for item show:'+item.id+' could not be found in cart model'); return false; }
							if(itemInstance.instanceIds.indexOf(ticket.id)==-1) { if(this.debug) console.log('cart model MISMATCH: instance id '+ticket.id+' could not be found in badge type model '+badgeTypeId+' for item show:'+item.id+' could not be found in cart model'); return false; }
							if(itemInstance.instanceTimestamps.indexOf(Util.date.parse(ticket.price_computed_at))==-1) { if(this.debug) console.log('cart model MISMATCH: ticket timestamp '+Util.date.parse(ticket.price_computed_at)+' could not be found in badge type model '+badgeTypeId+' for item show:'+item.id+' could not be found in cart model'); return false; }
						}
						for(var i=0;i<invoice.items.length;i++){
							productItem = invoice.items[i];
							if(item==null){ if(this.debug) console.log('cart model MISMATCH: item model product:'+productItem.product.id+' could not be found in cart model'); return false; }
							badgeTypeId = (productItem.badge_id == null ? 0 : productItem.badge.badge_type_id);
							itemInstance = item.itemInstances[badgeTypeId]; //regular itemInstances always exist
							if(itemInstance==null) { if(this.debug) console.log('cart model MISMATCH: badge type model '+badgeTypeId+' for item product:'+item.id+' could not be found in cart model'); return false; }
							if(itemInstance.instanceIds.indexOf(productItem.id)==-1) { if(this.debug) console.log('cart model MISMATCH: instance id '+productItem.id+' could not be found in badge type model '+badgeTypeId+' for item product:'+item.id+' could not be found in cart model'); return false; }
							if(itemInstance.instanceTimestamps.indexOf(Util.date.parse(productItem.price_computed_at))==-1) { if(this.debug) console.log('cart model MISMATCH: ticket timestamp '+Util.date.parse(productItem.price_computed_at)+' could not be found in badge type model '+badgeTypeId+' for item product:'+item.id+' could not be found in cart model'); return false; }
						}
						if(this.debug) console.log('cart model matches invoice');
						return true;
					}else{
						if(this.debug) console.log('cart model MISMATCH: item count in cart model is '+this.count()+' but it should have been '+invoice.tickets.length+invoice.items.length);						
					}
				}else{
					if(this.debug) console.log('cart model MISMATCH: item total in cart model is '+this.totalPrice()+' but it should have been '+invoice.total_amount);						
				}
			}else{
				if(this.debug) console.log('cart model MISMATCH: issued tiemstamp in cart model is '+this.issuedAt+' but it should have been '+Util.date.parse(invoice.issued_at));						
			}
		}else{
			if(this.debug) console.log('cart model MISMATCH: invoice id in cart model is '+this.invoiceId+' but it should have been '+invoice.id);						
		}
		return false;
	};
}
Cart.toString = function(){ return MCE.Ticketing.toJSON(this,false); };

//legacy interface
function bestel(itemId){ 
	if(itemId!=null){
		if(itemId.indexOf==null || itemId.indexOf('product:')==-1){
			itemId='show:'+itemId;
		}
	}
	MCE.Ticketing.initiateOrder(itemId); 
}
function adjust(){ MCE.Ticketing.initiateOrder();}
function addticket(itemId, badgeTypeId){ MCE.Ticketing.addItemInstance(itemId,badgeTypeId); }
function removeticket(itemId, itemInstanceId){ MCE.Ticketing.removeItemInstance(itemId,itemInstanceId); }
function showTab($tabChoosingAnchor){ MCE.OrderingPopup.showTab($tabChoosingAnchor.attr("id").split("_")[1]); }
function closeticketingpopup(){ MCE.OrderingPopup.hide(); }
function leaveMyTicketsTab(){ if(MCE.Session.isLoggedIn()){ MCE.OrderingPopup.showTab("tab3"); } else { MCE.OrderingPopup.showTab("tab1");}}
function leaveCustomerTab(){ MCE.OrderingPopup.CustomerTab.leave();}
function requestPasswd(){ MCE.OrderingPopup.CustomerTab.requestNewPassword(); }
function showRegistrationForm(){ MCE.OrderingPopup.CustomerTab.showRegistrationForm(); }
function hideRegistrationForm(){ MCE.OrderingPopup.CustomerTab.hideRegistrationForm(); }

function handlePayment(paymentType) {
    //MCE.OrderingPopup.CheckOutTab.emptyPaymentFrame();

    if (MCE.Session.isLoggedIn()) {
        
    	MCE.OrderingPopup.CheckOutTab.setPaymentFrameUrl(paymentType);
    	MCE.OrderingPopup.CheckOutTab.showPaymentFrame(true);
    	MCE.OrderingPopup.CheckOutTab.showPaymentOptions(false);
    }
	return false;
}

function paymentsuccessful() {

    //if (console) if (console.log) console.log('succes')

	MCE.OrderingPopup.CheckOutTab.showPaymentFrame(false);
	MCE.OrderingPopup.CheckOutTab.showPaymentOptions(true);
	MCE.OrderingPopup.CheckOutTab.showPaymentError(false);
	MCE.OrderingPopup.show("tab5");
	MCE.Session.logout();
	MCE.WaitingBox.hide();
}
function paymentfailed() {
  //  if (console) if (console.log) console.log('fail')

	MCE.OrderingPopup.CheckOutTab.showPaymentFrame(false);
	MCE.OrderingPopup.CheckOutTab.showPaymentOptions(true);
	MCE.OrderingPopup.CheckOutTab.showPaymentError(true);
	MCE.WaitingBox.hide();
}
function resetpayment() {
	//MCE.OrderingPopup.CheckOutTab.emptyPaymentFrame();
	//MCE.OrderingPopup.CheckOutTab.setPaymentFrameUrl(null,null);
	MCE.OrderingPopup.CheckOutTab.showPaymentFrame(false);
	MCE.OrderingPopup.CheckOutTab.showPaymentOptions(true);
	MCE.OrderingPopup.CheckOutTab.showPaymentError(false);
	MCE.WaitingBox.hide();
}
function successIdeal(){
	MCE.OrderingPopup.CheckOutTab.showPaymentFrame(false);
	MCE.OrderingPopup.CheckOutTab.showPaymentOptions(true);
	MCE.OrderingPopup.CheckOutTab.showPaymentError(false);
	MCE.OrderingPopup.show("tab5");
	MCE.Session.logout();
	MCE.WaitingBox.hide();
    
	/*
	$(document).ready(function(){
		$("#ticketing_popup").show();
		$("#tab1").hide();
		$(".ticketing_tab_active").addClass('ticketing_tab_nonactive');
		$(".ticketing_tab_active").removeClass('ticketing_tab_active');
		$("#show_tab4").parent().addClass('ticketing_tab_active');
		$("#show_tab4").parent().removeClass('ticketing_tab_nonactive');
		$("#tab2").hide();
		$("#tab5").show();
		$("#over").hide();
		$("#ticketing_loader").hide();
	});
	*/		
}

function failedIdeal(){
		MCE.OrderingPopup.CheckOutTab.showPaymentFrame(false);
		MCE.OrderingPopup.CheckOutTab.showPaymentOptions(true);
		MCE.OrderingPopup.CheckOutTab.showPaymentError(true);
		MCE.OrderingPopup.show("tab4");
		MCE.WaitingBox.hide();
    
	/*
	$(document).ready(function(){
		$("#ticketing_loader").show();
		$("#cart").hide();
		$("#ticketing_popup").show();
		showTab($("#show_tab4"));
		$("#payment_error").html("Helaas, er is iets fout gegaan bij het betalen. Probeer het nogmaals.");
		$("#payment_error").show();
		$("#payment_content").show();
		$("#over").hide();
		$("#ticketing_loader").hide();
	});
	*/
}

MCE.Ticketing = {
	TRIG_CART_CHANGED : 'mc.ticketing.invoice_changed',
	TRIG_BADGE_TYPES_LOADED : 'mc.ticketing.badge_types_loaded',
	TRIG_SHOW_LOADED : 'mc.ticketing.show_loaded',
	TRIG_PAYMENT_TYPES_LOADED: 'mc.ticketing.payment_types_loaded',
	
	incompleteItems : {},
	activeItemId : null,
	
	getInvoice : function() { return MCE.Session.invoice; },
	setInvoice : function(invoice) { MCE.Session.setInvoice(invoice); },
	cartIsEmpty : function() { return (MCE.Session.invoice == null || (MCE.Session.invoice.tickets.length + MCE.Session.invoice.items.length) == 0); },
	writeCartState : function(){
		var cartState = Util.json.toJSON(this.cart,false);
		if(this.debug) console.log('writing cart state :'+cartState);
		Util.cookie.create('cart', "'"+cartState+"'");
	},
	readCartState : function(){ 
	
		cartStateCookie = Util.cookie.read('cart');

        if(cartStateCookie!=null && cartStateCookie.length>2){
			cartStateCookie = cartStateCookie.substring(1,(cartStateCookie.length-1));
            eval('cartState='+cartStateCookie+';');
		}else{
			cartState=null;
		}
        
 	    if(this.debug) console.log('reading cart state :'+(cartStateCookie!=null && cartStateCookie.length>2 ? cartStateCookie : 'null'));
		return cartState;
	},

	init : function(debug) {

        this.debug = (debug!=null && typeof(console) !== 'undefined' && console != null ? debug : false);
        
        this.cart = new Cart(this.debug,this.readCartState());

        this.$ticketingPopup = $('div#ticketing_popup');
		this.$cart = $('#cart');
		
		
		MCE.TriggerManager.bind(this.$ticketingPopup, MCE.Session.TRIG_LOGGED_IN,	this, this.handleLogin);
		MCE.TriggerManager.bind(this.$ticketingPopup, MCE.Session.TRIG_LOGGED_OUT,	this, this.handleLogout);
		MCE.TriggerManager.bind(this.$ticketingPopup, MCE.Session.TRIG_LOGGED_IN,	this, this.handleCustomerUpdate);
		MCE.TriggerManager.bind(this.$ticketingPopup, MCE.Session.TRIG_LOGGED_OUT,	this, this.handleCustomerUpdate);
		MCE.TriggerManager.bind(this.$ticketingPopup, MCE.Session.TRIG_ANONYMOUS_CREATED, this, this.handleCustomerUpdate);
		MCE.TriggerManager.bind(this.$ticketingPopup, MCE.Session.TRIG_CUSTOMER_CHANGED, this, this.handleCustomerUpdate);
		MCE.TriggerManager.bind(this.$ticketingPopup, MCE.Ticketing.TRIG_CART_CHANGED, this, this.handleCartUpdate);
		
		if(!this.cart.matchesInvoice(this.getInvoice())){
			this.cart.invalidate();
			this.parseInvoice(MCE.Session); //this will trigger TRIG_CART_CHANGED
		}else{
			MCE.TriggerManager.trigger(this.TRIG_CART_CHANGED,MCE.Session);
		}
		MCE.TriggerManager.trigger(MCE.Session.TRIG_CUSTOMER_CHANGED,MCE.Session);
	},
	loadInvoice : function(session, succesCallback, noSuccesCallback, errorCallback, callbackContext) {
		Ticketing = this;
		if (session.getCustomerId() != null) {
			MCE.JewelLabs.loadInvoice(session.getCustomerId(), function(invoice){
				Ticketing.cart.invalidate();
				Ticketing.setInvoice(invoice);
				Ticketing.parseInvoice(session); //this will trigger TRIG_CART_CHANGED
				if (succesCallback != null) succesCallback.call((callbackContext != null ? callbackContext : window),invoice);}, 
				noSuccesCallback, errorCallback, callbackContext);
		}
	},
	loadBadgeTypes : function(session, itemId, itemType, succesCallback,noSuccesCallback, errorCallback, callbackContext) {
		Ticketing = this;
		if (session.getCustomerId() != null) {
			MCE.JewelLabs.loadBadgeTypes(session.getCustomerId(),itemId,itemType, function(badgeTypes){
				if (succesCallback != null) succesCallback.call((callbackContext != null ? callbackContext: window),{"session" : session,"item_id" : itemId, "item_type" : itemType, "badge_types" : badgeTypes});
				MCE.TriggerManager.trigger(Ticketing.TRIG_BADGE_TYPES_LOADED,{"session" : session, "item_id" : itemId, "item_type" : itemType, "badge_types" : badgeTypes});},
				noSuccesCallback, errorCallback, callbackContext);
		}
	},
	loadItem : function(session, itemId, itemType, succesCallback, noSuccesCallback, errorCallback, callbackContext) {
		Ticketing = this;
		if (session.getCustomerId() != null) {
			MCE.JewelLabs.loadItem(itemId, itemType, function(loadedItem){
				this.logObject(loadedItem,'loadedItem');
				var data ={"session" : session,"item_id" : itemId, "item_type" : itemType}; data[itemType]=loadedItem; 
				this.logObject(data,'data');
				if (succesCallback != null) succesCallback.call((callbackContext != null ? callbackContext: window),data);
				MCE.TriggerManager.trigger(Ticketing.TRIG_SHOW_LOADED,data);},
				noSuccesCallback, errorCallback, callbackContext);
		}
	},
	loadPaymentTypes : function(succesCallback ,noSuccesCallback, errorCallback, callbackContext) {
		Ticketing = this;
		MCE.JewelLabs.loadPaymentTypes(function(paymentTypes){
				if (succesCallback != null) succesCallback.call((callbackContext != null ? callbackContext: window),paymentTypes);
				MCE.TriggerManager.trigger(Ticketing.TRIG_PAYMENT_TYPES_LOADED,{"payment_types" : paymentTypes});},
				noSuccesCallback, errorCallback, callbackContext);
	},
	logObject: function(object,name){
		if(this.debug){
			console.log(name+'='+Util.json.toJSON(object,false));
		}
	},
	//parse invoice functionality
	parseInvoice : function(session) {
		this.cart.prepareForParsingInvoice();
		if (!this.cartIsEmpty()) {
			var invoice = this.getInvoice();
			
			this.cart.invoiceId = invoice.id;
			this.cart.issuedAt = Util.date.parse(invoice.issued_at);
			
			for ( var i = 0; i < invoice.tickets.length; i++) {
				var ticket = invoice.tickets[i];

				var showItem = this.cart.items['show:'+ticket.show.id];
				if (showItem == null) showItem = this.cart.addItem(ticket.show,'show');

				var badgeTypeId = (ticket.badge_id == null ? 0 : ticket.badge.badge_type_id);
				var itemInstance = showItem.itemInstances[badgeTypeId]; //regular itemInstance always exist
				if (itemInstance == null)	itemInstance = showItem.addItemInstance(badgeTypeId, ticket.badge.badge_type_name, ticket.sales_price);
				itemInstance.addInstance(ticket.id, ticket.price_computed_at);
			}
			for ( var i = 0; i < invoice.items.length; i++) {
				var invoiceProductItem = invoice.items[i];

				var productItem = this.cart.items['product:'+invoiceProductItem.product.id];
				if (productItem == null) productItem = this.cart.addItem(invoiceProductItem.product,'product');

				var badgeTypeId = (invoiceProductItem.badge_id == null ? 0 : invoiceProductItem.badge.badge_type_id);
				var itemInstance = productItem.itemInstances[badgeTypeId]; //regular itemInstance always exist
				if (itemInstance == null)	itemInstance = productItem.addItemInstance(badgeTypeId, invoiceProductItem.badge.badge_type_name, invoiceProductItem.sales_price);
				itemInstance.addInstance(invoiceProductItem.id, invoiceProductItem.price_computed_at);
			}
		}
		this.validateCart(session);
	},
	validateCart: function(session){
		Ticketing = this;
		var allItemsAreValid = true;
		for (var itemId in this.cart.items) {
			var item = this.cart.items[itemId];
			if (!item.valid) {
				allItemsAreValid=false;
				this.loadBadgeTypes(session, item.id,item.type,
						function(data){
							var badgeTypes = data["badge_types"];
							var itemToValidate = Ticketing.cart.items[data["item_type"]+':'+data["item_id"]];
							for ( var i = 0; i < badgeTypes.length; i++) {
								var badgeType = badgeTypes[i];
								itemToValidate.addItemInstance(badgeType.id, badgeType.name,badgeType.price).instancesAvailable = true;
							}
							itemToValidate.valid=true;
							Ticketing.itemHasBeenValidated(session);
						});//TODO proper error handling
			}
		}
		if(allItemsAreValid) MCE.TriggerManager.trigger(Ticketing.TRIG_CART_CHANGED,session);
	},
	itemHasBeenValidated: function(session){
		var allValid =true;
		for (var itemId in this.cart.items) {
			if (!this.cart.items[itemId].valid) allValid=false;
		}
		if(allValid){ 
			MCE.TriggerManager.trigger(Ticketing.TRIG_CART_CHANGED,session);
		}
		return allValid;
	},
	initiateOrder: function(itemId){
		this.activeItemId = itemId;
		if(MCE.Session.customer==null){
			Ticketing = this;
			MCE.Session.createAnonymousCustomer(function(){
				Ticketing.cart.invalidate();
				Ticketing.putItemInCart(itemId);});
		}else{
			this.putItemInCart(itemId);
		}
	},
	addItemInstance: function(itemId, badgeTypeId){
		Ticketing = this;
		if(MCE.Session.getCustomerId()!=null){
			MCE.WaitingBox.show('#addTicket');
			var item = this.cart.items[itemId];
			MCE.JewelLabs.addItemInstance(MCE.Session.getCustomerId(),item.id, item.type, badgeTypeId,function(invoice){
					Ticketing.cart.invalidate(itemId);
					Ticketing.setInvoice(invoice);
					Ticketing.parseInvoice(MCE.Session); //this will trigger TRIG_CART_CHANGED
				},function(error){
					if(Ticketing.debug) console.log("add item instance FAILED: "+error);
					if(error=='The customer could not be found'){
						//the anonymous user has timed out
					}
//show it					
				},function(error){
					if(Ticketing.debug) console.log("add item instance FAILED: "+error);
//show it					
				},this);
		}
	},
	removeItemInstance: function(itemId, itemInstanceId){
		if(MCE.Session.getCustomerId()!=null){
			MCE.WaitingBox.show('#removeTicket');
			var item = this.cart.items[itemId];
			MCE.JewelLabs.removeItemInstance(MCE.Session.getCustomerId(), itemInstanceId, (item.type=='show' ? 'ticket' : 'item'), function(invoice){
 					Ticketing.cart.invalidate(itemId);
 					Ticketing.setInvoice(invoice);
 					Ticketing.parseInvoice(MCE.Session); //this will trigger TRIG_CART_CHANGED
				},function(error){
					if(Ticketing.debug) console.log("remove item instance FAILED: "+error);
//			show it					
				},function(error){
					if(Ticketing.debug) console.log("remove item instance FAILED: "+error);
//			show it					
				},this);
		}
	},
	putItemInCart: function(itemId){
		if(itemId!=null){
			var parsedItemId = itemId.split(':');
			var type=parsedItemId[0];
			var id=parsedItemId[1];
			var item = this.cart.items[itemId];
			if(item==null){
				MCE.WaitingBox.show('#loadShow');
				this.incompleteItems[itemId]={ type:null, "badgeTypes":null};
				this.loadItem(MCE.Session, id,type, this.handleIncompleteItems, null, null, this);//TODO proper error handling
				this.loadBadgeTypes(MCE.Session, id,type, this.handleIncompleteItems,null, null, this);//TODO proper error handling
			}else{
				MCE.WaitingBox.show('#updateBasket');
				MCE.OrderingPopup.show("tab2");
				this.parseInvoice(MCE.Session);
			}
		}else{
			MCE.WaitingBox.show('#updateBasket');
			MCE.OrderingPopup.show("tab2");
			MCE.TriggerManager.trigger(Ticketing.TRIG_CART_CHANGED,MCE.Session);
		}
	},
	handleIncompleteItems: function(data){
		var session = data["session"];
		var id = data["item_id"];
		var type = data["item_type"];
		var itemId = type+':'+id;
		if(this.debug) console.log('data returned form server for item '+itemId+': badge_types='+data["badge_types"]+' '+type+'='+data[type]);

		
		var incompleteItem = this.incompleteItems[itemId];
		if(incompleteItem == null){//should not happen!!
			this.incompleteItems[itemId]={type:null, "badgeTypes":null}; 
			incompleteItem = this.incompleteItems[itemId];
		}
		if(data[type]!=null){
			incompleteItem[type]=data[type]; 
			if(this.debug) console.log('item returned form server for incomplete item '+itemId+': '+incompleteItem[type]);
		}
		if(data["badge_types"]!=null){
			incompleteItem["badgeTypes"] = data["badge_types"]; 
			if(this.debug) console.log('badge types returned form server for incomplete item '+itemId+': '+incompleteItem["badgeTypes"]);
		}
		if(incompleteItem["badgeTypes"]!=null && incompleteItem[type]!=null){
			//add the item to the cart
			var newItem = this.cart.addItem(incompleteItem[type],type);
			for ( var i = 0; i < incompleteItem.badgeTypes.length; i++) {
				var badgeType = incompleteItem.badgeTypes[i];
				newItem.addItemInstance(badgeType.id,badgeType.name,badgeType.price).instancesAvailable = true;
			}
			newItem.valid=true;
			if(this.debug) console.log('incomplete item '+itemId+' added to cart as: '+newItem);
			
			this.incompleteItems[itemId] = null;
			delete this.incompleteItems[itemId];
			MCE.WaitingBox.show('#updateBasket');
			MCE.OrderingPopup.show("tab2");
			this.parseInvoice(MCE.Session);
		}
	},
	//event handlers
	handleLogin : function(event, session) {
		Ticketing = event.data;
		Ticketing.loadInvoice(session);//this will trigger TRIG_CART_CHANGED
		// TODO give proper error handlers
	},
	handleLogout : function(event, session) {
		Ticketing = event.data;
		Ticketing.setInvoice(null);
		Ticketing.cart = new Cart(Ticketing.debug);
		//if (console) console.log(MCE.OrderingPopup.getActiveTabId())
		//if(MCE.OrderingPopup.getActiveTabId()!="show_tab5"){
			//MCE.OrderingPopup.hide();
		//}
		MCE.TriggerManager.trigger(Ticketing.TRIG_CART_CHANGED,session);
	},
	handleCartUpdate: function(event,session){
		Ticketing = event.data;
		Ticketing.writeCartState();
		MCE.OrderingPopup.TicketsTab.OrderForm.update(Ticketing.cart,Ticketing.activeItemId);
		MCE.OrderingPopup.OverviewTab.update(Ticketing.cart,null);
		MCE.OrderingPopup.CheckOutTab.update(Ticketing.cart);
		MCE.Cart.update(Ticketing.cart);
		MCE.Cart.toggle();
		MCE.WaitingBox.hide();
	},
	handleCustomerUpdate : function(event, session) {
		Ticketing = event.data;
		MCE.OrderingPopup.OverviewTab.update(null,session);
		MCE.OrderingPopup.CustomerTab.update(session);
	}
};
MCE.OrderingPopup={
	init:function(fadeSpeed,slideSpeed, debug){
		this.FADE_SPEED = (fadeSpeed!=null ? fadeSpeed : 250);
		this.SLIDE_SPEED = (slideSpeed!=null ? slideSpeed : 600);
		this.debug = (debug!=null && typeof(console) !== 'undefined' && console != null ? debug : false);
		this.$orderingPopup = $('div#ticketing_popup');
		
		this.tabs={
			'tab1': this.CustomerTab,
			'tab2': this.TicketsTab,
			'tab3': this.OverviewTab,
			'tab4': this.CheckOutTab,
			'tab5': this.PaymentSuccesfullTab
		};
		
		for( tabId in this.tabs) this.tabs[tabId].init(this.debug,this.FADE_SPEED,this.SLIDE_SPEED);
		OrderingPopup = this;
		$("#delete_popup",this.$orderingPopup).click(function(){ OrderingPopup.hide(); return false; });
		
		$(".tab").click(function(){
			showTab($(this));
			return false;
		});

		if(this.debug) console.log('ordering popup initialized');
	},
	resize: function(){
		Util.positioning.resize(); 
		if(this.$orderingPopup.css('display')=='none'){
			Util.positioning.alignTop(); 
		} 
	},
	show: function(tabId){
		if(tabId!=null) OrderingPopup.showTab(tabId);
		if(this.$orderingPopup.css('visibility')=='hidden'){
			OrderingPopup = this;
			Util.positioning.alignTop();
			this.$orderingPopup.css('display','none');
			this.$orderingPopup.css('visibility','visible');
			this.$orderingPopup.fadeIn(this.FADE_SPEED,function(){
				if(OrderingPopup.debug) console.log('ordering popup VISIBLE');
				MCE.Cart.toggle(true);
			});
		}
	},
	hide: function(){
		if(this.$orderingPopup.css('visibility')=='visible'){
			OrderingPopup = this;
			this.$orderingPopup.fadeOut(this.FADE_SPEED,function(){
			
			    // Robert's hack...
			    $('#ticketing_register_form tr').attr('style', null)
			
				OrderingPopup.$orderingPopup.css('visibility','hidden');
				OrderingPopup.$orderingPopup.css('display','block');
				if(OrderingPopup.debug) console.log('ordering popup HIDDEN');
				MCE.Cart.toggle(true);
				MCE.WaitingBox.hide();
			});			
		}
	},
	showTab: function(tabId) {
	
	    // if the user is not logged in / anonymous, the login tab is shown instead of the pay tab
	
	    if (tabId == 'tab4' && MCE.Session.isLoggedIn() == false) {
	        tabId = 'tab1';
	    }
		
		$(".ticketing_tab_active").addClass("ticketing_tab_nonactive");
		$(".ticketing_tab_active").removeClass("ticketing_tab_active");
		this.tabs[tabId].$tabSelector.addClass("ticketing_tab_active");
		this.tabs[tabId].$tabSelector.removeClass("ticketing_tab_nonactive");
		
		$(".tabje").hide();
		Cufon.refresh();	
		this.tabs[tabId].$tab.show();
		for(var id in this.tabs){
			this.tabs[id].handleVisibilityChange((id==tabId));
		}
	    this.resize();
	},
	getActiveTabId: function(){
		$(".ticketing_tab_active a").attr('id');
	},
	CustomerTab:{
		id: 'tab1',
		init: function(debug,fadeSpeed,slideSpeed){
			this.FADE_SPEED = (fadeSpeed!=null ? fadeSpeed : 250);
			this.SLIDE_SPEED = (slideSpeed!=null ? slideSpeed : 600);
			this.DUMMY_PASSWORD = '********';
			this.debug = (debug!=null && typeof(console) !== 'undefined' && console != null ? debug : false);
			this.$tab = $('#'+this.id,MCE.OrderingPopup.$orderingPopup);
			this.$tabSelector = $('#show_'+this.id,MCE.OrderingPopup.$orderingPopup).parent();
			this.$loginFormContainer = $('div#grey_container',this.$tab); //don't ask me why they called it that 
			this.$loginForm = $('form',this.$loginFormContainer);
			var CustomerTab = this;
			this.requestPassword=false;
			this.$loginForm.validate({
				rules: {
					ticket_email: {required:true, email:true},
					password: {required:true, minlength:6}
				},
				messages: {
					ticket_email:{ required:"Dit veld is verplicht!", email:"Vul a.u.b. een geldig e-mailadres in!" },
					password: { required: "Dit veld is verplicht!",	minlength: "Het wachtwoord moet minimaal 6 tekens lang zijn!"}
				},
				submitHandler: function(form) {
					var email = $('#ticket_email',CustomerTab.$loginForm).attr('value');
					if(CustomerTab.requestPassword){
						CustomerTab.requestPassword=false;
						var formSettings = CustomerTab.$loginForm.validate().settings;
						formSettings.rules.password = { required:true, minlength:6  };
						MCE.WaitingBox.show('#newPassword');
						MCE.JewelLabs.requestNewPassword(email,null,null,function(invoice){
							CustomerTab._setLoginErrorMessage('new_password');//actually a normal message
							MCE.WaitingBox.hide();
						},function(error){
							CustomerTab._setLoginErrorMessage('unknown',error);
							MCE.WaitingBox.hide();
						},function(){
							CustomerTab._setLoginErrorMessage('error');
							MCE.WaitingBox.hide();
						},this);
					}else{
						var password = $('#password',CustomerTab.$loginForm).attr('value');
						var credentialsMap = { "email":email, "password":password };
						MCE.WaitingBox.show('#logIn');

						MCE.Session.login(credentialsMap,function(customer){
							CustomerTab._setLoginErrorMessage('null');
							MCE.OrderingPopup.showTab('tab3');
						},function(error){
							CustomerTab._setLoginErrorMessage('failure');
							//TODO figure out which message is send back
							/*
							if (error == '???') {
								CustomerTab._setLoginErrorMessage('failure');
							} else {
								CustomerTab._setLoginErrorMessage('unknown',error);
							}*/
							MCE.WaitingBox.hide();
						},function(error){
							CustomerTab._setLoginErrorMessage('error');
							MCE.WaitingBox.hide();
						},this);
					}
				}
			});
			this.$customerFormContainer = $('div#ticketing_register_form',this.$tab);
			this.$customerForm = $('form',this.$customerFormContainer);
			$('form input, form select',this.$customerFormContainer).bind('change',this,this._customerFormChanged);
			this.$customerForm.validate({
				rules: {
					email: { required:true, email: true	},
					email_confirm: { required: true, equalTo: "#email_register"	},
					password: {	required:true, minlength:6 },
					confirm: { required: true, equalTo: "#password_register" },
					day: { number: true, minlength: 1, maxlength: 2, max: 31, min: 1 },
					month: { number: true, minlength: 1, maxlength: 2, max: 12, min: 1 },
					year: { number: true, minlength: 4, maxlength: 4,min: 1	},
					firstname: {required:true},
					lastname: {required:true},
					street: {required:true},
					number: {required:true},
					zipcode: {required:true},
					city: {required:true}
				},
				messages: {
					email: {
						required: "Dit veld is verplicht!",
						email: "Vul a.u.b. een geldig e-mailadres in!"
					},
					email_confirm: {
						required: "Dit veld is verplicht!",
						equalTo: "Vul a.u.b. hetzelfde e-mail adres in als hierboven!"
					},
					password: {
						required: "Dit veld is verplicht!",
						minlength: "Het wachtwoord moet minimaal 6 tekens lang zijn!"
					},
					confirm: {
						required: "Dit veld is verplicht!",
						equalTo: "Vul dezelfde waarde in als voor het wachtwoord!"
					},
					day: {
						number: "Vul a.u.b. een geldig nummer in!",
						minlength: "Vul minimaal 2 cijfer in!",
						maxlength: "Vul maximaal 2 cijfers in!",
						min: "Geen negatieve waarden!",
						max: "Niet hoger dan 31!"
					},
					month: {
						number: "Vul a.u.b. een geldig nummer in!",
						minlength: "Vul minimaal 2 cijfer in!",
						maxlength: "Vul maximaal 2 cijfers in!",
						min: "Geen negatieve waarden!",
						max: "Niet hoger dan 12!"
					},
					year: {
						number: "Vul a.u.b. een geldig nummer in!",
						minlength: "Vul minimaal 4 cijfers in!",
						maxlength: "Vul maximaal 4 cijfers in!",
						min: "Geen negatieve waarden!"
					},
					firstname: "Dit veld is verplicht!",
					lastname: "Dit veld is verplicht!",
					street: "Dit veld is verplicht!",
					number: "Dit veld is verplicht!",
					zipcode: "Dit veld is verplicht!",
					city: "Dit veld is verplicht!"
				},
				submitHandler: function(form) {
					if(!CustomerTab._isValidCustomerBirthDateField()){
						CustomerTab._setCustomerErrorMessage('ill_date');
						return false;
					}else{
						CustomerTab._setCustomerErrorMessage(null);
					}
					var customerMap = CustomerTab._readCustomerForm(true);
					
					MCE.Session.insertUpdateCustomer(customerMap, function(){
						CustomerTab._setCustomerErrorMessage(null);
						MCE.WaitingBox.hide();
						CustomerTab._setCustomerFormSubmitButton('next_step');
						if(MCE.Session.isLoggedIn()){
							$('#ticketing_register_cancel',CustomerTab.$customerFormContainer).hide();
						}
						MCE.OrderingPopup.showTab("tab3");
					},function(error){
						MCE.WaitingBox.hide();
						if (error == 'Login has already been taken') {
							CustomerTab._setCustomerErrorMessage('login_taken');
						} else if (error == 'Illegal date') {
							CustomerTab._setCustomerErrorMessage('ill_date');
						} else {
							CustomerTab._setCustomerErrorMessage('unknown',error);
						}
					},function(){
						MCE.WaitingBox.hide();
						CustomerTab._setCustomerErrorMessage('error');
					},this);
					return false;
				}
			});
			
			if(this.debug) console.log('customer tab ('+this.id+') initialized');
		},
		handleVisibilityChange: function(visible){
			if(visible){
				if(MCE.Session.isLoggedIn()){
					$('#ticketing_register_cancel',this.$customerFormContainer).hide();
				}
			}
		},
		show: function(){
			MCE.OrderingPopup.showTab(this.id);
		},
		update: function(session){
			//the default scenario is the abscense of a customer 
			var showLoginform = true;
			var showCustomerform = false;
			var customerEmailAndPasswordRequired = true;
			var customer = session.getCustomer();
			if(customer!=null && session.isLoggedIn()){//a non-anonymous customer
				showLoginform = false;
				showCustomerform = true;
				customerEmailAndPasswordRequired = false;
			}
   			$('#ticket_email',this.$loginFormContainer).attr('value','');
   			$('#password',this.$loginFormContainer).attr('value','');
   			this._writeCustomerForm(customer);
			this._setFormVisibility(showLoginform, showCustomerform, customerEmailAndPasswordRequired);
		},
		leave: function(){
			if(this._isCustomerChanged()){
				this.$customerForm.submit();
			}else{
				if(MCE.Session.isLoggedIn()){
					this._setCustomerErrorMessage(null);
					MCE.OrderingPopup.showTab("tab3");
				}else{
					this._setCustomerErrorMessage('register');
				}
			}
			return false;
		},
		requestNewPassword: function(){
			this.requestPassword=true;
			var formSettings = this.$loginForm.validate().settings;
			delete formSettings.rules.password;
			this.$loginForm.submit();
		},
		showRegistrationForm: function(){
			if(MCE.Session.isLoggedIn()){
				this._setFormVisibility(false, true, false);
			}else{
				this._setFormVisibility(false, true, true);
			}
		},
		hideRegistrationForm: function(){
			this._writeCustomerForm(MCE.Session.getCustomer());
			if(MCE.Session.isLoggedIn()){
				this._setFormVisibility(false, true, false);
			}else{
				this._setFormVisibility(true, false, true);
			}
		},
		_writeCustomerForm:function(customer){
			var dummyPassword = (customer!=null && MCE.Session.isLoggedIn() ? this.DUMMY_PASSWORD :'');
			if(customer!=null && !MCE.Session.isLoggedIn()){//a customer is present but is anonymous
				customer=null; //causes the fileds in the form to be blank.
			}
			$('#email_register',this.$customerForm).attr('value',(customer!=null ? customer.email_address : ''));
			$('#email_confirm',this.$customerForm).attr('value','');
			$('#password_register',this.$customerForm).attr('value',dummyPassword);
			$('#confirm',this.$customerForm).attr('value','');
			$('#firstname',this.$customerForm).attr('value',(customer!=null ? customer.first_name : ''));
			$('#lastname',this.$customerForm).attr('value',(customer!=null ? customer.last_name : ''));
			$('#street',this.$customerForm).attr('value',(customer!=null ? customer.address_1 : ''));
			$('#number',this.$customerForm).attr('value',(customer!=null ? customer.address_number : ''));
			$('#zipcode',this.$customerForm).attr('value',(customer!=null ? customer.zip_code : ''));
			$('#city',this.$customerForm).attr('value',(customer!=null ? customer.city : ''));
			$('#country',this.$customerForm).attr('value',(customer!=null ? Util.country.getIso(customer.country_id) : 'NL'));
			$('#telephone',this.$customerForm).attr('value',(customer!=null ? customer.day_phone : ''));
			var dateOfBirth = (customer!=null && customer.date_of_birth!=null ? new Date(Util.date.parse(customer.date_of_birth)) : null);
			$('#birthdate_date',this.$customerForm).attr('value', Util.date.getDayStr(dateOfBirth));
			$('#birthdate_month',this.$customerForm).attr('value', Util.date.getMonthStr(dateOfBirth));
			$('#birthdate_year',this.$customerForm).attr('value', Util.date.getYearStr(dateOfBirth));
			if(customer!=null && customer.gender=='f'){
				$('#sex_male',this.$customerForm).removeAttr('checked');
				$('#sex_female',this.$customerForm).attr('checked','checked');
			}else{
				$('#sex_male',this.$customerForm).attr('checked','checked');
				$('#sex_female',this.$customerForm).removeAttr('checked');
			}
			if(customer!=null && customer.is_send_notifications){
				if(customer.interests.indexOf('4')!=-1){
					$('#snailmail',this.$customerForm).attr('checked','checked');
				}else{
					$('#snailmail',this.$customerForm).removeAttr('checked');
				}
				if(customer.interests.indexOf('3')!=-1){
					$('#digitaal',this.$customerForm).attr('checked','checked');
				}else{
					$('#digitaal',this.$customerForm).removeAttr('checked');
				}
			}else{
				$('#snailmail',this.$customerForm).removeAttr('checked');
				$('#digitaal',this.$customerForm).removeAttr('checked');
			}
		},
		_readCustomerForm: function(changedOnly){
			var customer={};
			customer['email_address']=this._readCustomerFormField('#email_register');
			customer['password']=this._readCustomerFormField('#password_register');
			customer['first_name']=this._readCustomerFormField('#firstname');
			customer['last_name']=this._readCustomerFormField('#lastname');
			customer['address_1']=this._readCustomerFormField('#street');
			customer['address_number']=this._readCustomerFormField('#number');
			customer['zip_code']=this._readCustomerFormField('#zipcode');
			customer['city']=this._readCustomerFormField('#city');
			customer['country_id']=Util.country.getId(this._readCustomerFormField('#country'));
			customer['day_phone']=this._readCustomerFormField('#telephone');
			var year = new Number(this._readCustomerFormField('#birthdate_year'));
			var month = new Number(this._readCustomerFormField('#birthdate_month'));
			var date = new Number(this._readCustomerFormField('#birthdate_date'));
			if(year!=0 && month!=0 && date!=0 ){
				var dateOfBirth = new Date(year,month-1,date);
				customer['date_of_birth'] = Util.date.toJewelLabsDateString(dateOfBirth);
			}else{
				customer['date_of_birth']=null;
			}
			customer['gender'] =($('#sex_male',this.$customerForm).attr('checked') ? 'm' : 'f');
			var interests = '';
			if($('#snailmail',this.$customerForm).attr('checked')) interests += '4';
			if($('#digitaal',this.$customerForm).attr('checked')) interests += (interests.length>0 ? ',': '')+'3';
			customer['is_send_notifications'] = (interests.length>0);
			if(customer['is_send_notifications']){
				customer['interests'] = interests;
			}else{
				customer['interests'] = '0';
			}
			if(changedOnly!=null && changedOnly){
				var orgCustomer = MCE.Session.getCustomer();
				if(!this._isCustomerFieldChanged(orgCustomer,customer,'email_address')) delete customer['email_address'];				
				if(!this._isCustomerFieldChanged(orgCustomer,customer,'password','password')) delete customer['password'];				
				if(!this._isCustomerFieldChanged(orgCustomer,customer,'first_name')) delete customer['first_name'];				
				if(!this._isCustomerFieldChanged(orgCustomer,customer,'last_name')) delete customer['last_name'];				
				if(!this._isCustomerFieldChanged(orgCustomer,customer,'address_1')) delete customer['address_1'];				
				if(!this._isCustomerFieldChanged(orgCustomer,customer,'address_number')) delete customer['address_number'];				
				if(!this._isCustomerFieldChanged(orgCustomer,customer,'zip_code')) delete customer['zip_code'];				
				if(!this._isCustomerFieldChanged(orgCustomer,customer,'city')) delete customer['city'];				
//				if(!this._isCustomerFieldChanged(orgCustomer,customer,'country_id')) delete customer['country_id'];				
				if(!this._isCustomerFieldChanged(orgCustomer,customer,'day_phone')) delete customer['day_phone'];				
				if(!this._isCustomerFieldChanged(orgCustomer,customer,'date_of_birth')) delete customer['date_of_birth'];				
				if(!this._isCustomerFieldChanged(orgCustomer,customer,'gender')) delete customer['gender'];				
				if(!this._isCustomerFieldChanged(orgCustomer,customer,'is_send_notifications')) delete customer['is_send_notifications'];				
				if(!this._isCustomerFieldChanged(orgCustomer,customer,'interests')) delete customer['interests'];				
			}
			return customer;
		},
		_readCustomerFormField: function(fieldSelector){
			var value = $(fieldSelector,this.$customerForm).attr('value');
			if(value.length==0) return null;	
			return value;
		},
		_isValidCustomerBirthDateField: function(){
			var year = new Number(this._readCustomerFormField('#birthdate_year'));
			var month = new Number(this._readCustomerFormField('#birthdate_month'));
			var date = new Number(this._readCustomerFormField('#birthdate_date'));
			if(year!=0 && month!=0 && date!=0 ){
				var valid = Util.date.isValid(year,month-1,date);
				if(this.debug) console.log('DATE CHECK: year='+year+' month='+month+' day='+date+' valid='+valid);
				return valid;
			}else{
				return true;
			}
		},
		_customerFormChanged: function(event){
			CustomerForm = event.data;
			$input=$(this);
			
			var customer = MCE.Session.getCustomer();
			var formCustomer = CustomerForm._readCustomerForm();
			var emailChanged = CustomerForm._isCustomerFieldChanged(customer,formCustomer,'email_address');
			var passwordChanged = CustomerForm._isCustomerFieldChanged(customer,formCustomer,'password','password');
			if($input.attr('id')=='password_register'){
				if(!passwordChanged && MCE.Session.isLoggedIn()){
					CustomerForm._showPasswordConfirmField(false);
				}else{
					CustomerForm._showPasswordConfirmField(true);
				}
			}
			if($input.attr('id')=='email_register'){
				if(!emailChanged && MCE.Session.isLoggedIn()){
					CustomerForm._showEmailConfirmField(false);
				}else{
					CustomerForm._showEmailConfirmField(true);
				}
			}
			var CustomerTab = event.data;
			var customerHasChanged = CustomerTab._isCustomerChanged();
			if(customerHasChanged){
				$('#ticketing_register_cancel',CustomerTab.$customerFormContainer).show();
			}else{
				if(MCE.Session.isLoggedIn()){
					$('#ticketing_register_cancel',CustomerTab.$customerFormContainer).hide();
				}
			}
			CustomerTab._setCustomerFormSubmitButton((customerHasChanged?(MCE.Session.isLoggedIn() ? 'save':'register'):'next_step'));
		},
		_showPasswordConfirmField: function(show){
			var $passwordConfirm = $('#confirm',this.$customerForm).parent().parent();
			var formSettings = this.$customerForm.validate().settings;
			if(show){
				$passwordConfirm.css({position:'static', visibility:'visible'});
//				formSettings.rules.password = { required:true, minlength:6 };
				formSettings.rules.confirm = { required: true, equalTo: "#password_register"};
			}else{
				$passwordConfirm.css({position:'absolute', visibility:'hidden'});
//				formSettings.rules.password = { required:false, minlength:6 };
				delete formSettings.rules.confirm;
			}
		},
		_showEmailConfirmField: function(show){
			var $emailConfirm = $('#email_confirm',this.$customerForm).parent().parent();
			var formSettings = this.$customerForm.validate().settings;
			if(show){
				$emailConfirm.css({position:'static', visibility:'visible'});
//				formSettings.rules.email = { required:true, email:true };
				formSettings.rules.email_confirm = { required: true, equalTo: "#email_register"};
			}else{
				$emailConfirm.css({position:'absolute', visibility:'hidden'});
//				formSettings.rules.email = { required:false, email:true };
				delete formSettings.rules.email_confirm;
			}
			
		},
		_setCustomerFormSubmitButton: function(messageSelector){
			$('#ticketing_register_submit a', this.$customerFormContainer).html($('div.submit_labels span.'+messageSelector, this.$customerFormContainer).text());
		},
		_setCustomerErrorMessage: function(messageSelector,extraMessageText){
			if(messageSelector==null){
				$('#register_error', this.$customerFormContainer).hide();
			}else{
				$('#register_error', this.$customerFormContainer).html($('div.error_messages span.'+messageSelector, this.$customerFormContainer).text()+(extraMessageText!=null?extraMessageText:'')).show();
			}
		},
		_setLoginErrorMessage: function(messageSelector,extraMessageText){
			if(messageSelector==null){
				$('#login_error', this.$loginFormContainer).hide();
			}else{
				$('#login_error', this.$loginFormContainer).html($('div.error_messages span.'+messageSelector, this.$loginFormContainer).text()+(extraMessageText!=null?extraMessageText:'')).show();
			}
		},
		_isCustomerChanged: function(){
			var customer = MCE.Session.getCustomer();
			var formCustomer = this._readCustomerForm();
			if(this._isCustomerFieldChanged(customer,formCustomer,'email_address')) return true;
			if(this._isCustomerFieldChanged(customer,formCustomer,'password','password')) return true;
			if(this._isCustomerFieldChanged(customer,formCustomer,'first_name')) return true;
			if(this._isCustomerFieldChanged(customer,formCustomer,'last_name')) return true;
			if(this._isCustomerFieldChanged(customer,formCustomer,'address_1')) return true;
			if(this._isCustomerFieldChanged(customer,formCustomer,'address_number')) return true;
			if(this._isCustomerFieldChanged(customer,formCustomer,'zip_code')) return true;
			if(this._isCustomerFieldChanged(customer,formCustomer,'city')) return true;
			if(this._isCustomerFieldChanged(customer,formCustomer,'country_id','radio')) return true;
			if(this._isCustomerFieldChanged(customer,formCustomer,'day_phone')) return true;
			if(this._isCustomerFieldChanged(customer,formCustomer,'date_of_birth')) return true;
			if(this._isCustomerFieldChanged(customer,formCustomer,'gender','radio')) return true;
			if(this._isCustomerFieldChanged(customer,formCustomer,'is_send_notifications')) return true;
			if(this._isCustomerFieldChanged(customer,formCustomer,'interests')) return true;
			return false;
		},
		_isCustomerFieldChanged: function(customer,formCustomer,fieldName,type){
			if(customer==null && type=='radio') return false;
			var fieldValue = formCustomer[fieldName];
			if(type=='password'&& fieldValue!=null && fieldValue!=this.DUMMY_PASSWORD && fieldValue.length>0) return true;
			if(type=='password'&& (fieldValue==null || fieldValue==this.DUMMY_PASSWORD || fieldValue.length==0)) return false;
			if(customer==null && fieldValue!=null && fieldValue.length==0) return true;
			if(customer[fieldName]==null && (fieldValue==null || fieldValue.length==0)) return false;
			if(customer[fieldName]!=fieldValue) return true;
			return false;
		},
		_setFormVisibility: function(showLogin,showCustomer,customerEmailAndPasswordRequired){
			if(customerEmailAndPasswordRequired){
				this._showEmailConfirmField(true);
				this._showPasswordConfirmField(true);
			}else{
				this._showEmailConfirmField(false);
				this._showPasswordConfirmField(false);
			}
			if(showCustomer && (!MCE.Session.isLoggedIn() || this._isCustomerChanged())){
				$('#ticketing_register_cancel',this.$customerFormContainer).show();
			}else{
				$('#ticketing_register_cancel',this.$customerFormContainer).hide();
			}

			var loginVisible = this.$loginFormContainer.css('display')!='none';
			var customerVisible = this.$customerFormContainer.css('display')!='none';
			var needResize = showLogin!=loginVisible || showCustomer!=customerVisible;
						
			if(showLogin && !loginVisible) this.$loginFormContainer.show();
			if(!showLogin && loginVisible) this.$loginFormContainer.hide();
			if(showCustomer && !customerVisible) this.$customerFormContainer.show();
			if(!showCustomer && customerVisible) this.$customerFormContainer.hide();
//			if(needResize && this.$tab.css('display')!='none') MCE.OrderingPopup.resize();
		}
	},
	TicketsTab:{
		id: 'tab2',
		init: function(debug,fadeSpeed,slideSpeed){
			this.FADE_SPEED = (fadeSpeed!=null ? fadeSpeed : 250);
			this.SLIDE_SPEED = (slideSpeed!=null ? slideSpeed : 600);
			this.debug = (debug!=null && typeof(console) !== 'undefined' && console != null ? debug : false);
			this.$tab = $('#'+this.id,MCE.OrderingPopup.$orderingPopup);
			this.$tabSelector = $('#show_'+this.id,MCE.OrderingPopup.$orderingPopup).parent();
			if(this.debug) console.log('tickets tab ('+this.id+') initialized');
		},
		handleVisibilityChange: function(visible){},
		show: function(){
			MCE.OrderingPopup.showTab(this.id);
		},
		OrderForm:{
			update: function(cartModel,itemId) {
				var orderFormMarkup='';
				if(itemId!=null){//do not show them all
					var item = cartModel.items[itemId];
					if(item!=null){//only one item has been requested on the form
						orderFormMarkup=this._getMarkupForItem(item,false);
					}else{
						orderFormMarkup='';
					}
				}else{//show them all
					for(var id in cartModel.items) {
						var item = cartModel.items[id];
						if(item.count()>0 || (item.type+':'+item.id)==itemId){
							orderFormMarkup+=this._getMarkupForItem(item,false);
						}
					}
				}
				$("#tab2_content").html(orderFormMarkup);
				MCE.OrderingPopup.resize();
			},
			_getMarkupForItem: function(item,hidden){
				if(item!=null){
					var html = 
						'<div class="ticketing_popup_kader order_box" id="'+ item.getId()+ '"'+(hidden!=null && hidden==true ? ' style="display:none;"' : '')+'>'+
						'<p class="ticketing_popup_voorstelling_maker" id="current_maker">'+ item.name	+ '</p>'+
						'<p class="ticketing_popup_voorstelling_datum" id="current_date">'+ Util.date.getLabel(item.startsAt) + '</p>'+
						'<table><tr>';
					html+= this._getMarkupForItemInstance(item.getId(),item.itemInstances['0']);//regular tickets go first
					for(badgeTypeId in item.itemInstances){
						if(badgeTypeId!='0' && badgeTypeId!='22' && badgeTypeId!='23' && badgeTypeId!='26'){ //regular and special cases have to be skipped here 
							html+= this._getMarkupForItemInstance(item.getId(),item.itemInstances[badgeTypeId]);//regular tickets go first
						}
					}
					html+= this._getMarkupForItemInstance(item.getId(),item.itemInstances['22']);//special case 22
					html+= this._getMarkupForItemInstance(item.getId(),item.itemInstances['23']);//special case 23
					html+= this._getMarkupForItemInstance(item.getId(),item.itemInstances['26']);//special case 26
					html+=
						'<td>'+
						'<p>Totaal</p><p>&nbsp;</p>'+
						'<ul class="badge">'+
						'<li></li>'+
						'<li class="cart_voorstelling_counter_count" id="total_'+ item.getId()+ '">'+item.count()+'</li>'+
						'<li></li>'+
						'</ul>'+
						'</td>'+
						'</tr></table></div>';
					return html;
				}else{
					return '';
				}
			},
			_getMarkupForItemInstance: function(itemId, itemInstance){
				if(itemInstance!=null){
					var html= 
						'<td>'+
						'<p>'+ itemInstance.badgeTypeName+ '</p>'+
						'<p>&euro; '+ Util.number.format(itemInstance.price, 2, ",", ".")+ '</p>'+
						'<ul class="badge">'+
						'<li '+(itemInstance.count()==0 ? 'style="display:none;"' : '')+'>'+
						'<a href="#" class="less" onclick="removeticket(\''+ itemId+ '\', \''+ itemInstance.lastInstanceId()+ '\'); return false;">'+
						'<img src="../tickets/img/button-minus-11x11.png" class="ticketing_popup_voorstelling_ticketcounter_less" alt="less" />'+
						'</a>'+
						'</li>'+
						'<li class="cart_voorstelling_counter_count" id="regular_amount_'+ itemId + '">'+
						itemInstance.count()+
						'</li>'+
						'<li '+(!itemInstance.instancesAvailable ? 'style="display:none;"' : '')+'>'+
						'<a href="#" class="more" onclick="addticket(\''+ itemId+ '\', \''+itemInstance.badgeTypeId + '\'); return false;">'+
						'<img src="../tickets/img/button-plus-11x11.png" class="ticketing_popup_voorstelling_ticketcounter_more" alt="more" />'+
						'</a>'+
						'</li>'+
						'</ul>'+
						'</td>';
					return html;
				}else{
					return '';
				}
			}
		}
	},
	OverviewTab:{
		id: 'tab3',
		init: function(debug,fadeSpeed,slideSpeed){
			this.FADE_SPEED = (fadeSpeed!=null ? fadeSpeed : 250);
			this.SLIDE_SPEED = (slideSpeed!=null ? slideSpeed : 600);
			this.debug = (debug!=null && typeof(console) !== 'undefined' && console != null? debug : false);
			this.$tab = $('#'+this.id,MCE.OrderingPopup.$orderingPopup);
			this.$tabSelector = $('#show_'+this.id,MCE.OrderingPopup.$orderingPopup).parent();
			if(this.debug) console.log('overview tab ('+this.id+') initialized');
		},
		handleVisibilityChange: function(visible){},
		show: function(){
			MCE.OrderingPopup.showTab(this.id);
		},
		update: function(cartModel,session) {
			if(session!=null){
				if (session.isLoggedIn()) {
					$("#user_details",this.$tab).html(session.getCustomerFullName()+'<br />'+ session.customer.address_1 + ' '+ session.customer.address_number + '<br />'+ session.customer.zip_code + ' '+ session.customer.city);
					$("#more_user_details",this.$tab).html('Email adres: ' + session.customer.email_address+'<br />');
					$("div.ticket_popup_controle_besteller",this.$tab).show();
					$("h5#loginanonymous",this.$tab).hide();
					$("div.ticket_popup_controle_besteller",this.$tab).show();
				} else {
					$("h5#loginanonymous",this.$tab).show();
					$("div.ticket_popup_controle_besteller",this.$tab).hide();
					$("#user_details",this.$tab).html("");
					$("#more_user_details",this.$tab).html("");
				}
			}
			var overviewMarkup = '';
			if(cartModel!=null){
				if(cartModel.count()>0){
					for(var itemId in cartModel.items){
						var item = cartModel.items[itemId];
						overviewMarkup+=this._getMarkupForItem(item);
					}
					$("h5#ticketing_voorstelling_modify",this.$tab).show();
					if(MCE.Session.isLoggedIn()){
						$("h5#payup",this.$tab).show();
					}
				}else{
					$("h5#ticketing_voorstelling_modify",this.$tab).hide();
					$("h5#payup",this.$tab).hide();
					overviewMarkup = "<div id='jehebtietsfoutgedaan'>U heeft nog geen tickets besteld. Klik op de knop 'aanpassen' of 'verder shoppen' hieronder om tickets te bestellen.</div>";					
				}
				$("#overview_content").html(overviewMarkup);
			}
		},
		_getMarkupForItem: function(item){
			var markupForItem='';
			if(item.count()>0){
				markupForItem = 
					'<div class="ticket_popup_controle_voorstelling">'+
						'<h5 class="black">'+item.name+'</h5>'+
						'<p class="besteller_groen">'+Util.date.getLabel(item.startsAt)+'</p>';
				for(var badgeTypeId in item.itemInstances){
					var itemInstance = item.itemInstances[badgeTypeId];
					markupForItem+=this._getMarkupForItemInstance(itemInstance);
				}
				markupForItem+=
						'<p class="controle">'+
							'<strong>'+item.count()+' kaart/product'+(item.count()>1?'(en)':'')+', &euro; '+Util.number.format(item.totalPrice(), 2, ",", ".")+'</strong>'+
						'</p>'+
					'</div>';
			}
			return markupForItem;
		},
		_getMarkupForItemInstance: function(itemInstance){
			var markupForItemInstance = '';
			if(itemInstance.count()>0){
				markupForItemInstance = '<p class="controle">'+itemInstance.count()+' x &euro; '+Util.number.format(itemInstance.price, 2, ",", ".")+' ('+itemInstance.badgeTypeName+')</p>';
			}
			return markupForItemInstance;
		}
	},
	CheckOutTab:{
		id: 'tab4',
		init: function(debug,fadeSpeed,slideSpeed){
			this.FADE_SPEED = (fadeSpeed!=null ? fadeSpeed : 250);
			this.SLIDE_SPEED = (slideSpeed!=null ? slideSpeed : 600);
			this.debug = (debug!=null && typeof(console) !== 'undefined' && console != null ? debug : false);
			this.$tab = $('#'+this.id,MCE.OrderingPopup.$orderingPopup);
			this.$tabSelector = $('#show_'+this.id,MCE.OrderingPopup.$orderingPopup).parent();
			this.$paymentError = $('#payment_error',this.$tab);
			this.$paymentMessage = $('#payment_content',this.$tab);
			this.$paymentOptions = $('#payment_options',this.$tab);
			this.$paymentFrame = $('#payment_frame',this.$tab);
			//get the payment types
			var checkOutTab = this;
			
			// is there a customer check?
			MCE.Ticketing.loadPaymentTypes(function(paymentTypes){
				html = '<table class="ticketing_payment_method" text-align="left">';
				for(var i=0; i< paymentTypes.length; i++){
					html+=checkOutTab._getMarkupForPaymentType(MCE.Session.getCustomerId(),paymentTypes[i].id,paymentTypes[i].name.NL,'../tickets/img/payment-logo-'+paymentTypes[i].short_name.toLowerCase()+'.png');
				}
				html+='</table>';
				checkOutTab.$paymentOptions.html(html);
				});
				
			//TODO add proper error handlers

			if(this.debug) console.log('check out tab ('+this.id+') initialized');
		},
		handleVisibilityChange: function(visible){},
		show: function(){
			MCE.OrderingPopup.showTab(this.id);
		},
		update: function(cartModel) {
			var customerId = MCE.Session.getCustomerId();
			if(customerId!=null){
				var html='';
				if (cartModel.count()>0 && cartModel.totalPrice() == 0) {//free tickets only
					html = 
					'<table class="ticketing_payment_method" text-align="left">'+
						'<tr><td><h5 class="black">U heeft gratis tickets/producten geselecteerd, <a href="../tickets/pay.xql?customer='+customerId+'&type=7" onclick="$(\'#payment_frame\').attr(\'src\', \'../tickets/pay.xql?customer='+customerId+'&type=7\'); $(\'#payment_content\').hide(); return false;">klik hier</a> om de bestelling af te ronden.</h5></td></tr>'+
					'</table>';
					this.$paymentOptions.hide();
					$("#choose_payment_method").hide();
					this.$paymentMessage.html(html);
				} else if (cartModel.count()==0) {//no tickets yet
					html = 
					'<table class="ticketing_payment_method" text-align="left">'+
						'<tr><td><h5 class="black">U heeft nog geen tickets/producten besteld.</h5></td></tr>'+
					'</table>';
					this.$paymentOptions.hide();
					$("#choose_payment_method").hide();
					this.$paymentMessage.html(html);
				} else {// tickets where to pay for in cart
					html = '';
					this.$paymentMessage.html(html);
					this.$paymentOptions.show();
					$("#choose_payment_method").show();
				}
			}
			$("#total_price").html(	Util.number.format(cartModel.totalPrice(), 2, ",", "."));
		},
		showPaymentError: function(show){
			if(show){
				if(this.$paymentError.css('display')=='none'){
					this.$paymentError.show();
				}
			}else{
				if(this.$paymentError.css('display')!='none'){
					this.$paymentError.hide();
				}
			}
		},
		showPaymentOptions: function(show){
			if(show){
				if(this.$paymentOptions.css('display')=='none'){
					this.$paymentOptions.show();
				}
			}else{
				if(this.$paymentOptions.css('display')!='none'){
					this.$paymentOptions.hide();
				}
			}
		},
		showPaymentFrame: function(show){
			if(show){
				if(this.$paymentFrame.css('display')=='none'){
					this.$paymentFrame.show();
				}
			}else{
				if(this.$paymentFrame.css('display')!='none'){
					this.$paymentFrame.hide();
				}
			}
		},
		setPaymentFrameUrl: function(paymentType){
		    customerId = MCE.Session.getCustomerId()
			if(customerId !=null && paymentType!=null){
			    this.$paymentFrame.attr('src', '../tickets/pay.xql?customer='+customerId+'&type='+paymentType);
			}
		},
		emptyPaymentFrame: function(){
				this.$paymentFrame.empty();
		},		
		_getMarkupForPaymentType: function(customerId, type, name, logoUrl){
			var markUp= 
			'<tr>'+
			'<td><a onclick="handlePayment(\''+type+'\'); return false;"><img src="'+logoUrl+'" alt="" /></td>'+
			'<td><h5 class="black"><a onclick="handlePayment(\''+type+'\'); return false;">'+name+'</a></h5></td>'+
			'</tr>';
			return markUp;
		}
	},
	PaymentSuccesfullTab: {
		id: 'tab5',
		init: function(debug,fadeSpeed,slideSpeed){
			this.FADE_SPEED = (fadeSpeed!=null ? fadeSpeed : 250);
			this.SLIDE_SPEED = (slideSpeed!=null ? slideSpeed : 600);
			this.debug = (debug!=null && typeof(console) !== 'undefined' && console != null ? debug : false);
			this.$tab = $('#'+this.id,MCE.OrderingPopup.$orderingPopup);
			this.$tabSelector = $('#show_'+this.id,MCE.OrderingPopup.$orderingPopup).parent();
		},
		handleVisibilityChange: function(visible){},
		show: function(){
			MCE.OrderingPopup.showTab(this.id);
		}
	}
};

MCE.Cart={
	init:function(slideSpeed,debug){
		this.SLIDE_SPEED = (slideSpeed!=null ? slideSpeed : 250);
		this.debug = (debug!=null && typeof(console) !== 'undefined' && console != null ? debug : false);
		this.$cart = $('#cart');
		this.$cartContent = $('#cart_content',this.$cart);
		this.$totalPriceField = $("#total_price");		
		this.$ticketingPopup = $('div#ticketing_popup');
		if(this.debug) console.log('cart initialized');
	},
	cartIsEmpty : function() { return (MCE.Session.invoice == null || MCE.Session.invoice.tickets.length + MCE.Session.invoice.items.length == 0); },
	toggle: function(slide){
		slide = (slide==null ? false : slide);
		if(!this.cartIsEmpty() && this.$ticketingPopup.css('visibility')=='hidden'){
			if(this.$cart.css('display')=='none'){
				if(slide){
					this.$cart.slideDown(this.CART_SLIDE_SPEED,function(){
						if(this.debug) console.log('cart VISIBLE');
					});
				}else{
					this.$cart.show();
					if(this.debug) console.log('cart VISIBLE');
				}
			}
		}else{
			if(this.$cart.css('display')!='none'){
				if(slide){
					this.$cart.slideUp(this.CART_SLIDE_SPEED,function(){
						if(this.debug) console.log('cart HIDDEN');
					});
				}else{
					this.$cart.hide();
					if(this.debug) console.log('cart HIDDEN');
				}
			}
		}
	},
	update: function(cartModel) {
		if(cartModel.count()>0){
			var cartMarkup = '';
			for(var itemId in cartModel.items) {
				var item = cartModel.items[itemId];
				cartMarkup+=this._getMarkupForItem(item);
			}
			this.$cartContent.html(cartMarkup);
		}else{
			this.$cartContent.html('');
		}
	},
	_getMarkupForItem: function(item){
		if(item!=null && item.count()>0){
			var html = 
			'<div class="cart_voorstelling">'+
				'<p class="cart_voorstelling_delete" style="display:none;">'+
					'<a href="">'+
						'<img src="../tickets/img/button-delete-red-8x8.png" alt="" />'+
					'</a>'+
				'</p>'+
				'<p class="cart_voorstelling_maker">'+
					item.name+
				'</p>'+
				'<p class="cart_voorstelling_datum">'+
					Util.date.getLabel(item.startsAt)+
				'</p>'+
				'<div class="cart_voorstelling_counter">'+
					'<ul>'+
						'<li class="cart_voorstelling_counter_label">aantal</li>'+
						'<li></li>'+
						'<li class="cart_voorstelling_counter_count">'+
							item.count()+
						'</li>'+
						'<li></li>'+
					'</ul>'+
				'</div>'+
			'</div>';
			return html;
		}else{
			return '';
		}
	}
};
MCE.WaitingBox={
	init:function(boxFadeSpeed,messageFadeSpeed,debug){
		this.WAITING_BOX_FADE_SPEED = (boxFadeSpeed!=null ? boxFadeSpeed : 250);
		this.WAITING_MESSAGE_FADE_SPEED = (messageFadeSpeed!=null ? messageFadeSpeed : 250);
		this.debug = (debug!=null && typeof(console) !== 'undefined' && console != null ? debug : false);
		this.$waitingBox = $('#ticketing_loader');
		this.$waitingMessageDiv = $('div.waiting.message',this.$waitingBox);
		this.$measurementWaitingMessage = $('h3.message.hidden',this.$waitingMessageDiv);
		this.currentMessageSelector = null;
		this.messageWidth=null;
		if(this.debug) console.log('waiting box initialized');
	},
	show: function(messageSelector){
		if(this.$waitingBox.css('visibility')=='hidden'){
			WaitingBox = this;
			Util.positioning.center(this.$waitingBox,$('img',this.$waitingBox));
			this.$waitingBox.css('display','none');
			this.$waitingBox.css('visibility','visible');
			this.$waitingBox.fadeIn(this.WAITING_BOX_FADE_SPEED,function(){
				if(WaitingBox.debug) console.log('waiting box VISIBLE');
				WaitingBox._message(messageSelector);});
		}else{
			this._message(messageSelector);
		}
	},
	hide: function(){
		if(this.$waitingBox.css('visibility')=='visible'){
			this._message(null);
			WaitingBox = this;
			this.$waitingBox.fadeOut(this.WAITING_BOX_FADE_SPEED,function(){
				WaitingBox.$waitingBox.css('visibility','hidden');
				WaitingBox.$waitingBox.css('display','block');
				if(WaitingBox.debug) console.log('waiting box HIDDEN');
			});			
		}else{
			this._message(null);
		}
	},
	_message: function(messageSelector){
		var WaitingBox = this;
		if(this.currentMessageSelector != messageSelector){
			if(this.currentMessageSelector==null){//no message visible at this moment
				this.$waitingMessageDiv.slideDown(this.WAITING_MESSAGE_FADE_SPEED,function(){
					if(WaitingBox.debug) console.log('slided DOWN waiting message div');
					WaitingBox.messageWidth = WaitingBox.$measurementWaitingMessage.width();
					$('h3.message',WaitingBox.$waitingMessageDiv).width(WaitingBox.messageWidth+'px');
					WaitingBox._setMessage(messageSelector);
				});
			}else{//a message is already visible at this moment
				this._setMessage(messageSelector);
				if(messageSelector==null){
					this.$waitingMessageDiv.slideUp(this.WAITING_MESSAGE_FADE_SPEED,function(){
						if(WaitingBox.debug) console.log('slided UP waiting message div');
					});
				}
			}
		}
	},
	_setMessage: function(messageSelector){
		if(this.$waitingBox.css('visibility')=='visible' && this.currentMessageSelector != messageSelector){
			if(this.currentMessageSelector != null){
				if(this.debug) console.log('fading OUT waiting message '+this.currentMessageSelector);
				$(this.currentMessageSelector,this.$waitingMessageDiv).fadeOut(this.WAITING_MESSAGE_FADE_SPEED);
			}
			this.currentMessageSelector = messageSelector;
			if(this.currentMessageSelector != null){
				if(this.debug) console.log('fading IN waiting message '+this.currentMessageSelector);
				$(this.currentMessageSelector,this.$waitingMessageDiv).fadeIn(this.WAITING_MESSAGE_FADE_SPEED);
			}
		}
	}
};

