Ext.onReady(function(){
var MBACoreModules = [
	{html: '<div>1. Strategic Planning</div>', xtype:'label'},
	{html: '<div>2. Corporate Finance</div>', xtype:'label'},
	{html: '<div>3. Marketing Management</div>', xtype:'label'},
	{html: '<div>4. Operations Management</div>', xtype:'label'},
	{html: '<div>5. Organisational Behavior</div>', xtype:'label'},
	{html: '<div>6. Managing Information</div>', xtype:'label'}
];
	    
var MSCinFinanceCoreModules = [
	{html: '<div>1. Corporate Finance</div>', xtype:'label'},
	{html: '<div>2. Financial Reporting and Analysis</div>', xtype:'label'},
	{html: '<div>3. Quantitative Methods in Investment Management</div>', xtype:'label'},
	{html: '<div>4. Financial Markets and Institutions</div>', xtype:'label'}
];
  
var MSCinMarketingCoreModules = [
	{html: '<div>1. Strategic Planning</div>', xtype:'label'},
	{html: '<div>2. Consumer Behaviour</div>', xtype:'label'},
	{html: '<div>3. Marketing Management</div>', xtype:'label'},
	{html: '<div>4. Integrated Marketing Communications</div>', xtype:'label'}
];

    var Question = Ext.extend(Ext.form.RadioGroup, {
        allowBlank: false,
        labelStyle: 'font-weight: bold;',
        labelSeparator: '',
        defaults: {
             autoWidth: true
        },
        
        initComponent: function(){
            Question.superclass.initComponent.call(this);
            
            this.addEvents({selectionchange: true})
            
            // revalidate radiogroup on selectionchange
            this.on('selectionchange', function(component){
                component.validate();
            });

            // limit radiogroup width if .columns property are array
            if (Ext.isArray(this.columns)) {
                this.width = function(c){
                    return c[0] + (c.length > 1 ? arguments.callee(c.slice(1)) : 0);
                }(this.columns);
            }

            Ext.each(this.items, function(item){ 
                item.name = this.name
            }, this)

            this.on('render', function(component){
               component.items.each(function(item){
                    item.on('check', function(radio, checked){
                        if (checked) {
                            component.fireEvent('selectionchange', component, radio.getRawValue())
                        }
                    })
                })
            })
        }
    })
    
    Ext.reg('quiz.question', Question);
	  
    var ProgramModules = Ext.extend(Ext.form.CheckboxGroup, {
        allowBlank: true,
        hideParent: true,
        labelStyle: 'font-weight: bold; cursor: pointer;',
        labelSeparator: '',
        columns: 1,
        vertical: true,
        defaults: {
             autoWidth: true
        },
        initComponent: function(){
            ProgramModules.superclass.initComponent.call(this);
            this.toogle = function(type){
                set = true;
                this.items.items.each(function(item){
                     set = item.getValue() && set;
                })

                if(set && counter[type].getValue() == 2){
                    this.reset();
                }
                else
                {
                    counter[type].reset();
                    this.items.items.each(function(item){
                            item.setValue(true);
                    })
                }
            }
        }
    })

    Ext.reg('quiz.program-modules', ProgramModules);
    
    var QuestionYesNo = Ext.extend(Question, {
        columns: [50, 50],
        initComponent: function() {
            this.items = [{
                boxLabel: 'Yes',  
                inputValue: 'yes'
            }, {
                boxLabel: 'No',
                inputValue: 'no'
            }];

            QuestionYesNo.superclass.initComponent.call(this);
        }
    })

    Ext.reg('quiz.question-yesno', QuestionYesNo);
    var QuestionSet = Ext.extend(Ext.form.FieldSet, {
        labelAlign: 'top',
        autoHeight: true,
        baseCls: 'x-fieldset-noborder',
        initComponent: function(){
            QuestionSet.superclass.initComponent.call(this);

            var question = this.getComponent('question'); 

            if (typeof question !== 'undefined') {
                question.on('selectionchange', function(field, value){
                    field.ownerCt.items.each(function(item){
                        if (item === field) {
                            return;
                        }
                        
                        var disabled = item.allowValues.indexOf(value) === -1;

                        item.setVisible(!disabled);
                    })
                 })
            }

            this.on('beforeshow',function(container){
                container.items.each(function(component){
                    if (component.isXType(container.getXType())) {
                        component.setVisible(false)
                    } else if (component.isXType('quiz.question')) {
                        component.reset()
                        component.setDisabled(false)
                    }
                })
            })

            var disabler = function(container){
                container.items.each(function(component){
                    if (component.isXType(container.getXType())) {
                        // recursively call disabler on all child questionsets
                        disabler(component)
                    } else if (component.isXType('quiz.question')) {
                        component.setDisabled(true)
                    }
                })
            };
            this.on('hide', disabler)
        }
    })

    Ext.reg('quiz.questionset', QuestionSet);

    var personalInformation = new Ext.form.FieldSet({
        itemId: 'personalInformation',
        defaults: {
            anchor: '100%',
            allowBlank: false
        },
        baseCls: 'x-fieldset-noborder',
        labelWidth: 160,
        width: 445,
        autoHeight: true,
        listeners: {
            render: function(){
                this.getEl().mask('Loading');
            }
        },
        items: [{
            xtype: 'combo',
            fieldLabel: 'Title<b>*</b>',
            hiddenName: 'title',
            store: new Ext.data.SimpleStore({
                fields: ['value'],
                data: [['Mr'], ['Ms'], ['Mrs'], ['Mrs'], ['Dr'], ['Miss']]
            }),
            editable: false,
            valueField: 'value',
            displayField: 'value',
            mode: 'local',
            triggerAction: 'all',
            emptyText: 'Select a title',
            selectOnFocus: true
        }, {
            xtype: 'textfield',
            name: 'first_name',
            fieldLabel: 'First Name<b>*</b>',
            maskRe: /[\w0-9\s]/
        }, {
            xtype: 'textfield',
            name: 'surname',
            fieldLabel: 'Surname<b>*</b>',
            maskRe: /[\w0-9\s]/
        }, {
            xtype: 'phone',
            width: 280,
            name: 'contact_number',
            fieldLabel: 'Telephone Number'
        }, {
            xtype: 'combo',
            fieldLabel: 'Country of Residence<b>*</b>',
            hiddenName: 'residenceCountry',
            store: new Ext.data.JsonStore({
                fields: ['code', 'title', 'iso'],
                root: 'countryNames',
                autoLoad: true,
                url: document.baseURI + 'dictionary/countries'
            }),
            editable: false,
            valueField: 'iso',
            displayField: 'title',
            mode: 'local',
            triggerAction: 'all',
            emptyText: 'Select a country',
            selectOnFocus: true
        }, {
            xtype: 'textfield',
            name: 'email',
            fieldLabel: 'Email<b>*</b>',
            vtype: 'email'
        }, {
            xtype: 'textfield',
            name: 'priority_code',
            fieldLabel: 'Reference Code',
            allowBlank: true
        }]
    })
    
    var mbaModules = [{
	    	id: 'finance',
	    	title: 'Finance',
	    	items: ['Risk Management','Equity and Fixed Income Investments']
	    },
	    {
	    	id: 'accounting',
	    	title: 'Accounting',
	    	items: ['Financial Reporting and Analysis','Performance Management and Control']
	    },
	    {
	    	id: 'project_management',
	    	title: 'Project Management',
	    	items: ['Project Management','Virtual Teams Management']
	    },
	    {
	    	id: 'hr_management',
	    	title: 'HR Management',
	    	items: ['International HR Management','Coaching and Mentoring for Leadership & Management']
	    },
	    {
	    	id: 'marketing',
	    	title: 'Marketing',
	    	items: ['Global Marketing','Integrated Marketing Communications']
	    },
	    {
	    	id: 'e-business',
	    	title: 'E-Business',
	    	items: ['E-Commerce','Internet and Digital Marketing Communications']
	    },
	    {
	    	id: 'sales_management',
	    	title: 'Sales Management',
	    	items: ['Strategic Sales Management','Key Account Management']
	    },
	    {
	    	id: 'business_intelligence',
	    	title: 'Business Intelligence',
	    	items: ['Marketing Research','Managing Information']
	    },
	    {
	    	id: 'travel_and_hospitality_management',
	    	title: 'Travel and Hospitality Management',
	    	items: ['Strategic Planning for Hospitality Management','International Hospitality Management']
	    },
	    {
	    	id: 'it-management',
	    	title: 'IT Management',
	    	items: ['Innovation and Planning Strategies for IT Environments','International Competition in IT']
	    },
	    {
	    	id: 'islamic_banking_and_finance',
	    	title: 'Islamic Banking and Finance',
	    	items: ['Fundamentals of Islamic Banking and Finance **','Islamic Portfolio Management **']
	    },
	    {
	    	id: 'pr_and_reputation_management',
	    	title: 'PR and Reputation Management',
	    	items: ['PR and Corporate Communications','Internet and Digital Marketing Communication'],
	    	sub: '_sub_'
	    }
    ]
    
    var MSCinFinance = [{
	    	id: 'msc_in_finance_and_accounting',
	    	title: 'MSc in Finance and Accounting',
	    	items: ['Performance Management and Control','Advanced Financial Reporting']
	    },
	    {
	    	id: 'msc_in_finance_and_m_a',
	    	title: 'MSc in Finance and M&A',
	    	items: ['Corporate Valuation and Restructuring','Advanced Financial Modelling']
	    },
	    {
	    	id: 'msc_in_finance_and_investment_management',
	    	title: 'MSc in Finance and Investment Management',
	    	items: ['Equity and Fixed Income Investment','Derivatives Application']
	    },
	    {
	    	id: 'msc_in_finance_and_fund_management',
	    	title: 'MSc in Finance and Fund Management',
	    	items: ['Equity and Fixed Income Investment','Fund Management'],
	    	sub: '_sub_'
	    },
	    {
	    	id: 'msc_in_finance_and_risk_management',
	    	title: 'MSc in Finance and Risk Management',
	    	items: ['Risk Management','Actuarial Science']
	    },
	    {
	    	id: 'msc_in_investment_banking_and_securities',
	    	title: 'MSc in Investment Banking and Securities',
	    	items: ['Trading: Capital and Money Markets','Securities and Options']
	    },
	    {
	    	id: 'msc_in_finance_and_international_banking',
	    	title: 'MSc in Finance and International Banking',
	    	items: ['Advanced Financial Modelling','Trading: Capital and Money Markets'],
	    	sub: '_sub_'
	    },
	    {
	    	id: 'msc_in_islamic_banking_and_finance',
	    	title: 'MSc in Islamic Banking and Finance',
	    	items: ['Fundamentals of Islamic Banking **','Islamic Portfolio Management **']
    }]
    
	var MSCinMarketing = [{
			id: 'msc_in_marketing-and_management',
			title: 'MSc in Marketing and Management',
			items: ['Operations Management','Project Management']
		},
		{
			id: 'msc_in_marketing_and_international business',
			title: 'MSc in Marketing and International Business',
			items: ['Global Marketing','International Advertising and Brand Management'],
	    	sub: '_sub_'
		},
		{
			id: 'msc_in_marketing_and_business_intelligence',
			title: 'MSc in Marketing and Business Intelligence',
			items: ['Marketing Research','Managing Information']
		},
		{
			id: 'msc_in_e-marketing',
			title: 'MSc in E-Marketing',
			items: ['Internet and Digital Marketing Communications','Web-Marketing: Metrics, Analysis and Evaluation'],
	    	sub: '_sub_'
		},
		{
			id: 'msc_in_marketing_and_sales_management',
			title: 'MSc in Marketing and Sales Management',
			items: ['Strategic Sales Management','Key Account Management **']
		},
		{
			id: 'msc_in_marketing_and_advertising',
			title: 'MSc in Marketing and Advertising',
			items: ['Advertising Management **','International Advertising and Brand Management']
		},
		{
			id: 'msc_in_marketing_pr_and_reputation_management',
			title: 'MSc in Marketing, PR and Reputation Management',
			items: ['PR and Corporate Communications **','Internet and Digital Marketing Communications']
	}]
    var counterItem = function(){}
    counterItem.prototype = {
        count:0,
        items:[],
        reset: function(){
            this.items.each(function(el,index){
                el.toggleValue();
            })
        },
        getValue: function(){return this.count},
        setValue: function(checkbox){
            if (checkbox.getValue()){
                this.count += 1;
                this.items.push(checkbox);
            }
            else{
                this.count -= 1;
                this.items.remove(checkbox);
            }
            return this.count;
        }
    }

    var counter = {
    	'MBA': new counterItem(),
    	'MSc_in_Finance': new counterItem(),
    	'MSc_in_Marketing': new counterItem()
    };
    
    function getModuleElement(el, type){
    	var items = [];
    	for(var i = 0; i < el.items.length; i++)
    	{
    		items.push( {
    			boxLabel: el.items[i], 
    			name: type + '[' + el.items[i] + (el.sub ? el.sub : '') + ']',
    			listeners: {
    				'check': function(checkbox, value){
    					if (counter[type].setValue(checkbox) > 2) {
    						Ext.Msg.alert('', 'You can only select two electives');
    						checkbox.setValue(false);
    					}
    				}
    			}
    		});
    	}
    	
    	return new Ext.form.FieldSet({
		    defaults: {
		        anchor: '100%',
		        allowBlank: true
		    },
		    labelAlign: 'top',
		    baseCls: 'x-fieldset-noborder',
                    autoWidth: true,
		    autoHeight: true,
		    items: [{
                        id: type +'_'+ el.id,
                        fieldLabel : '<span onclick="Ext.getCmp(\''+ type +'_'+ el.id +'\').toogle(\''+ type +'\')">' + el.title + '</span>',
                        xtype: 'quiz.program-modules',
                        items: items
                    }]
    	})
    }
    
    
    
    function modulesLineBuildProcess(type, elements, line){
        var i = line;
        var result = [];
        Ext.each(
        	elements, 
        	function(item){
        		if (i = !i)
                            this.push(getModuleElement(item, type))
        	},
        	result 
    	);
        return result;
    }
    
    var MBAModules1 = modulesLineBuildProcess('MBA',mbaModules,0);
    var MBAModules2 = modulesLineBuildProcess('MBA',mbaModules,1);
    var MSCinFinanceModules1 = modulesLineBuildProcess('MSc_in_Finance',MSCinFinance,0);
    var MSCinFinanceModules2 = modulesLineBuildProcess('MSc_in_Finance',MSCinFinance,1);
    var MSCinMarketingModules1 = modulesLineBuildProcess('MSc_in_Marketing',MSCinMarketing,0);
    var MSCinMarketingModules2 = modulesLineBuildProcess('MSc_in_Marketing',MSCinMarketing,1);

    var Program = new Ext.form.FieldSet({
        defaults: {
            anchor: '100%',
            allowBlank: false
        },
        baseCls: 'x-fieldset-noborder',
        width: 445,
        labelWidth: 160,
        autoHeight: true,
        items: [{
            xtype: 'combo',
            id: 'programme-select-box',
            fieldLabel: 'Program<b>*</b>',
            hiddenName: 'programme',
            allowBlank: false,
            labelStyle: 'font-weight: bold;',
            labelSeparator: '',
            store: new Ext.data.SimpleStore({
                fields: ['value'],
                data: [['MBA'],['MSc in Finance'],['MSc in Marketing']]
            }),
            mode: 'local',
            triggerAction: 'all',
            emptyText: 'Select a program',
            editable: false,
            valueField: 'value',
            displayField: 'value',
            selectOnFocus: true,
            listeners: {
        		'select': function (combo){
                                                record = this.getValue();
//                                                Ext.getDom('programme-placeholder').innerHTML = record;
				        	Ext.getCmp('mba').hide();
				    		Ext.getCmp('mba').disable();
				    		Ext.getCmp('mscf').hide();
				    		Ext.getCmp('mscf').disable();
				    		Ext.getCmp('mscm').hide();
				    		Ext.getCmp('mscm').disable();
			    			Ext.getCmp('mscmCore').hide();
			    			Ext.getCmp('mbaCore').hide();
			    			Ext.getCmp('mscfCore').hide();
			    			Ext.getCmp('electives').show();
				    		if (record == 'MBA')
				    		{
				    			Ext.getCmp('mba').enable();
				    			Ext.getCmp('mba').show();
				    			Ext.getCmp('mbaCore').show();
				    		}
				    		if (record == 'MSc in Finance')
				    		{
				    			Ext.getCmp('mscf').enable();
				    			Ext.getCmp('mscf').show();
				    			Ext.getCmp('mscfCore').show();
				    		}
				    		if (record == 'MSc in Marketing')
				    		{
				    			Ext.getCmp('mscm').enable();
				    			Ext.getCmp('mscm').show();
				    			Ext.getCmp('mscmCore').show();
				    		}
				    	}
        	}	
        }]
    })
    
    var ProgramModules = new Ext.form.FieldSet({
        defaults: {
            anchor: '100%',
            allowBlank: false
        },
        baseCls: 'x-fieldset-noborder',
        autoHeight: true,
        items: [new Ext.form.FieldSet({
		        defaults: {
		            anchor: '100%',
		            allowBlank: false
		        },
		        baseCls: 'x-fieldset-noborder',
		        autoHeight: true,
		        items: [
		                new Ext.Panel({
		        			id: 'mba',
		        			layout: 'column',
		                	items: [{items: MBAModules1, style: 'padding:0 10px 0 0;', columnWidth: .50},
		                	        {items: MBAModules2, columnWidth: .50}],
		                	hidden: true,
				        	disabled: true
		                }),
		                new Ext.Panel({
		        			id: 'mscf',
		        			layout: 'column',
		                	items: [{items: MSCinFinanceModules1, style: 'padding:0 10px 0 0;', columnWidth: .50},
		                	        {items: MSCinFinanceModules2, columnWidth: .50}],
		                	hidden: true,
				        	disabled: true
		                }),
		                new Ext.Panel({
		        			id: 'mscm',
		        			layout: 'column',
		                	items: [{items: MSCinMarketingModules1, style: 'padding:0 10px 0 0;', columnWidth: .50},
		                	        {items: MSCinMarketingModules2, columnWidth: .50}],
		                	hidden: true,
				        	disabled: true
		                })]
			    })]
    })
    
    var Quiz = Ext.extend(Ext.form.FormPanel, {
        buttonAlign: 'left',
        buttons: [{
            text: 'Submit',
            handler: function(button){
                var form = button.ownerCt.getForm();
                if (form.isValid()) {
                    form.submit({
                        method: 'POST',
                        url: document.baseURI + 'applicationprocess/verify',
                        success: function(form, action){
                            document.location = document.baseURI + action.result.location 
                        }
                    })
                    
                    return;
                }
            }
        }],
        initComponent: function(){
            Quiz.superclass.initComponent.call(this);
            
            this.add( {
                xtype: 'label',
                html: '<h1>Application Process</h1>'
            },
            Program,
            {
            	items:[
	            new Ext.form.FieldSet({
	            	id: 'mbaCore',
			        baseCls: 'x-fieldset-noborder',
			        autoHeight: true,
			        hidden: true,
	    			layout: 'column',
			        items: [{text: 'Core Modules', xtype:'label', width: 160, labelStyle: "font-weight: bold;"},
			                {items: MBACoreModules}]
			    }),
			    new Ext.form.FieldSet({
	            	id: 'mscfCore',
			        baseCls: 'x-fieldset-noborder',
			        autoHeight: true,
			        hidden: true,
	    			layout: 'column',
			        items: [{text: 'Core Modules', xtype:'label', width: 160, labelStyle: "font-weight: bold;"},
			                {items: MSCinFinanceCoreModules}]
				    }),
			    new Ext.form.FieldSet({
	            	id: 'mscmCore',
			        baseCls: 'x-fieldset-noborder',
			        autoHeight: true,
			        hidden: true,
	    			layout: 'column',
			        items: [{text: 'Core Modules', xtype:'label', width: 160, labelStyle: "font-weight: bold;"},
			                {items: MSCinMarketingCoreModules}]
			    }),{
	            	id:'electives',
	            	hidden: true,
	            	items:[{
				        xtype: 'label',
				        html: '<h3 style="padding-bottom: 5px;">Electives Modules:</h3>'
					},{
					    xtype: 'label',
					    html: '<h3 style="padding-bottom: 10px;">Please select two elective modules or one specialism pathway to study:</h3>'
					}]			
	            }]
            },
            ProgramModules,
            {
                xtype: 'label',
                html: '<div><span>**</span> This elective is currently unavailable.</div><br /><h4>Personal Information</h4>'
            }, 
            personalInformation, 
            {
                xtype: 'label',
                html: '<div id="data-protection">'
                     + '<h4>Data Protection</h4>'
                     + '<div>We are committed to protecting the privacy of your personal information, which will be processed in a manner which meets the requirements of the 1998 Data Protection Act. The information we collect on this form will be used with the sole purpose of processing your application and contacting you with relevant information about the programme of your choice. Please note: This application does not guarantee admission.</div>'
                     + '</div>'
            });

            var callback = function(form) {
                form.clearInvalid();
                
                var c = this.getComponent('personalInformation');
                var unmask = function(){
                    c.getEl().unmask();
                }
                
                if (c.rendered) {
                    unmask();
                } else {
                    c.on('render', unmask);
                }
            }

            this.load({
                url: document.baseURI + 'applicationprocess/form',
                method: 'POST',
                success: callback,
                failure: callback,
                scope: this
            })
        }
    });
    
    new Quiz({
        id: 'debug',
        renderTo: 'quiz-form'
    });
});

    
