
Ext.namespace('Ext.ux.wizard');

Ext.ux.wizard.Window = function(config){

	this.progressTpl = new Ext.XTemplate(
	    '<tpl for=".">',
	        '<div class="progress-wrap" title="{name}" id="wizard-progress-step-{[xindex]}">',
	        '<div {[xindex == 1 ? "class=\'active-step\'" : ""]}><span>{name}</span></div>',
			'</div>',
	    '</tpl>'
	);

	this.stepInfoTpl = new Ext.XTemplate(
	    '<tpl>',
    	    '<p ext:qtip="{qtip}" ext:qwidth="{qwidth}" class={cls}>{description}</p>',
	    '</tpl>'
	);

	this.cards = config.cards;

 	Ext.ux.wizard.Window.superclass.constructor.call(this, {
        title: config.title || 'Wizard',
        layout:'border',
	   	buttonAlign:'center',		        
	    items: [{
			region:'west',
			id:'wizard-progress',
			layout:'fit',
			width: config.progressWidth || 150,
			border:false,
			items: {border:false, bodyStyle:'padding:15px',html:this.progressTpl.applyTemplate(config.cards || [])}
		}, {
			region:'center',
			border:false,
			layout:'border',
			items:[{
				region:'north',
				height:config.stepInfoHeight || 60,
				bodyStyle:'padding:15px',
				id:'wizard-head',
				listeners:{
					mouseover:function(){
						console.log('a');
					}
				},	
				border:false,
				html: this.stepInfoTpl.applyTemplate({step:0, description:config.cards[0].description, cls:config.cards[0].stepCls || 'step-info', qtip:config.cards[0].qtip || '', qwidth:config.cards[0].qwidth || 0})	
			},{
				id:'wizard-body',
				region:'center',
				layout:'card',
				border:false,
				renderHidden:true,
				border:false,
				activeItem:0,
				items:config.cards || [{html:'No items specified'}]
			}]
		}],
		width: config.width || 700,
		height: config.height || 400,
        closeAction: 'hide',
        modal: true,
        plain: true,
        shadow: false,
        resizable: false,
                
        buttons: [{                             
            text:'Cancel',
            scope: this,
            handler: this.previous
        },{                             
            text:'Next &raquo;',
            scope: this,
            handler: this.next
        }]
    });    
    
    this.addEvents({'finish': true, 'show':true});

}

Ext.extend(Ext.ux.wizard.Window, Ext.Window,{

	currentStep: 0,

	removeCard : function(index){
		var body = Ext.getCmp('wizard-body');		 
		body.remove(index ? index : 0);
		this.currentStep = this.currentStep > index ? this.currentStep - 1 : this.currentStep;
		this.resetButtons();
		this.renderProgress();
		this.updateHead(this.currentStep, Ext.getCmp('wizard-body').items.items[this.currentStep]);
		this.doLayout();	
	},
	
	insertCard : function(index, config){
		var body = Ext.getCmp('wizard-body');		 
		body.insert(index,config);
		this.currentStep = this.currentStep > index ? this.currentStep + 1 : this.currentStep;
		this.resetButtons();
		this.renderProgress();
		this.updateHead(index, config);
		this.doLayout();
	},

	addCard : function(config){
		var body = Ext.getCmp('wizard-body');		 
		body.add(config);
		if (this.currentStep+1 < Ext.getCmp('wizard-body').items.items.length) this.buttons[1].setText('Next &raquo');
		this.resetButtons();
		this.doLayout();
	},
	
	next : function() {
        var p = this.getLayout().center.panel.layout.center.panel.layout.activeItem;
		if (this.currentStep+1 == Ext.getCmp('wizard-body').items.items.length) {
	        if ((p.form && p.getForm().isValid()) || !p.form){
				this.fireEvent('finish', this.getValues());
			} else {
			 	Ext.MessageBox.alert('The form contains errors', 'Please correct the fields marked in red.');
			}
		} else {
	        if ((p.form && p.getForm().isValid()) || !p.form){
				this.getLayout().center.panel.layout.center.panel.layout.setActiveItem(++this.currentStep);  
				this.doLayout();
				this.updateProgress();
				if (this.currentStep+1 == Ext.getCmp('wizard-body').items.items.length) this.buttons[1].setText('Finish');
				if (this.currentStep+1 == 2) {
					this.buttons[0].setText('&laquo Previous');			 
				}
			} else {
			 	Ext.MessageBox.alert('The form contains errors', 'Please correct the fields marked in red.');
			}
	     }
	 },
	 
	 previous : function() {
		if (this.currentStep == 0) this.hide();
		else {
			this.getLayout().center.panel.layout.center.panel.layout.setActiveItem(--this.currentStep);         
			this.doLayout();
			this.updateProgress();
			if (this.currentStep+1 == 1) this.buttons[0].setText('Cancel');
			if (this.currentStep+1 < Ext.getCmp('wizard-body').items.items.length) this.buttons[1].setText('Next &raquo');
		}
	 },
	 
	 updateProgress : function(){
		var steps = Ext.get('wizard-progress').query('.progress-wrap');				
		for (var x=0; x < steps.length; x++){
		 	var node = Ext.get(steps[x]);
			Ext.get(node.dom.firstChild).removeClass('active-step');
			if (this.currentStep == x) {
				Ext.get(node.dom.firstChild).addClass('active-step');
				this.getLayout().center.panel.layout.north.panel.body.dom.innerHTML = this.stepInfoTpl.applyTemplate({step:x, description:Ext.getCmp('wizard-body').items.items[x].description, cls:Ext.getCmp('wizard-body').items.items[x].stepCls || 'step-info', qtip: Ext.getCmp('wizard-body').items.items[x].qtip || '',qwidth:Ext.getCmp('wizard-body').items.items[x].qwidth || 0});
			}
		}
	},

	renderProgress : function(){
		Ext.getCmp('wizard-progress').items.items[0].body.update(this.progressTpl.applyTemplate(Ext.getCmp('wizard-body').items.items));
	},

	resetButtons : function(){
		if (this.currentStep+1 < Ext.getCmp('wizard-body').items.items.length) this.buttons[1].setText('Next &raquo');
		else this.buttons[1].setText('Finish');
		
		if (this.currentStep > 0) this.buttons[0].setText('&laquo Previous');
		else this.buttons[0].setText('Cancel');
		
	},

	updateHead : function(index, config){
		Ext.getCmp('wizard-head').body.update(this.stepInfoTpl.applyTemplate({step:index, description:config.description, cls:config.stepCls || 'step-info', qtip: config.qtip || '',qwidth:config.qwidth || 0}));
	},

	getValues : function(){
	 	var values = {};
		var cards = this.getLayout().center.panel.layout.center.panel.items.items;
		for (var x=0;x<cards.length;x++){
			if (cards[x].form){
				var obj = cards[x].getForm().getValues();
				for (var key in obj){
					values[key] = obj[key];
				}
			}
		}
		return values;		 
	},
	
	getActiveCard : function(){
		return this.getLayout().center.panel.layout.center.panel.layout.activeItem;	
	},

	setActiveCard : function(index){
		var body = Ext.getCmp('wizard-body');		 
		body.getLayout().setActiveItem(index);
		this.currentStep = index;
	},
	
	reset : function(){
		this.getLayout().center.panel.layout.center.panel.layout.setActiveItem(0);	
		var cards = this.getLayout().center.panel.layout.center.panel.items.items;
		for (var x=0;x<cards.length;x++){
		 	//console.log(cards[x]);
			if (cards[x].form && cards[x].clearOnReset != false){
				cards[x].getForm().reset();
			}
		}
		this.currentStep = 0;
		this.buttons[0].setText('Cancel');
		if (this.currentStep+1 < Ext.getCmp('wizard-body').items.items.length) this.buttons[1].setText('Next &raquo');
		this.updateProgress();
	}
	
});
