Ext.onReady(function(){
    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 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 languageLevel = {
        xtype: 'quiz.questionset',
        items: [
                
                {
            xtype: 'quiz.question-yesno',
            itemId: 'question',
            name: 'english_language',
            fieldLabel: 'Is English your first Language?'
        }, {
            xtype: 'quiz.questionset',
            allowValues: ['no'],
            hidden: true,
            items: [{
                xtype: 'quiz.question-yesno',
                itemId: 'question',
                name: 'bachelor_degree',
                fieldLabel: 'Have you completed a Bachelor\'s degree in an institution where the primary language of instruction is English?'
            }, {
                xtype: 'quiz.questionset',
                allowValues: ['no'],
                items: [{
                    xtype: 'quiz.question-yesno',
                    itemId: 'question',
                    name: 'acca_cima_level',
                    fieldLabel: 'Have you completed Level II of either ACCA or CIMA?'
                }, {
                    xtype: 'quiz.questionset',
                    allowValues: ['no'],
                    items: [{
                        xtype: 'quiz.question',
                        itemId: 'question',
                        name: 'english_test',
                        columns: [60, 60, 60],
                        fieldLabel: 'Have you taken ANY of the following English proficiency tests in the past two years?',
                        items: [{
                            boxLabel: 'IELTS',
                            inputValue: 'ielts'
                        }, {
                            boxLabel: 'TOEFL',
                            inputValue: 'toefl'
                        }, {
                            boxLabel: 'None',
                            inputValue: 'none'
                        }]
                    }, {
                        xtype: 'quiz.questionset',
                        allowValues: ['ielts'],
                        items: [{
                            xtype: 'combo',
                            name: 'ielts_result',
                            fieldLabel: 'What is your English proficiency test result?',
                            labelStyle: 'font-weight:bold;',
                            labelSeparator: '',
                            listWidth: 164,
                            store: new Ext.data.SimpleStore({
                                fields: ['title', 'value'],
                                data: [['Less than IELTS 6.5', 'less'],
                                       ['More than IELTS 6.5', 'more'] ]
                            }),
                            displayField: 'title',
                            valueField: 'value',
                            mode: 'local',
                            selectOnFocus: true,
                            typeAhead: true,
                            triggerAction: 'all',
                            editable: false
                        }]
                    }, {
                        xtype: 'quiz.questionset',
                        allowValues: ['toefl'],
                        items: [{
                            xtype: 'combo',
                            name: 'toefl_result',
                            fieldLabel: 'What is your English proficiency test result?',
                            labelStyle: 'font-weight:bold;',
                            labelSeparator: '',
                            listWidth: 164,
                            store: new Ext.data.SimpleStore({
                                fields: ['title', 'value'],
                                data: [['Less than TOEFL 600', 'less'],
                                       ['More than TOEFL 600', 'more'] ]
                            }),
                            displayField: 'title',
                            valueField: 'value',
                            mode: 'local',
                            selectOnFocus: true,
                            typeAhead: true,
                            triggerAction: 'all',
                            editable: false
                        }]
                        
                    }]
                }]
            }]
        }]
    }

    var qualificationLavel = {
        xtype: 'quiz.questionset',
        items: [{
            xtype: 'quiz.question',
            itemId: 'question',
            name: 'qualification_level',
            fieldLabel: 'Have you successfully completed ANY of the following professional qualifications?',
            columns: [100, 100, 50],
            vertical: true,
            items: [{
                boxLabel: 'ACCA Level 1',
                inputValue: 'acca_1'
            }, {
                boxLabel: 'ACCA Level 2',
                inputValue: 'acca_2'
            }, {
                boxLabel: 'ACCA Level 3',
                inputValue: 'acca_3'
            }, {
                boxLabel: 'CIMA Level 1',
                inputValue: 'cima_1'
            }, {
                boxLabel: 'CIMA Level 2',
                inputValue: 'cima_2'
            }, {
                boxLabel: 'CIMA Level 3',
                inputValue: 'cima_3'
            }, {
                boxLabel: 'None',
                inputValue: 'none'
            }]
        }, {
            xtype: 'quiz.questionset',
            allowValues: ['acca_2', 'acca_3'],
            hidden: true,
            items: [{
                xtype: 'quiz.question-yesno',
                fieldLabel: 'Have you successfully passed the ACCA P3 paper?',
                name: 'acca_p3'
            }]
        }, {
            xtype: 'quiz.questionset',
            allowValues: ['cima_2', 'cima_3'],
            hidden: true,
            items: [{
                xtype: 'quiz.question-yesno',
                fieldLabel: 'Have you successfully passed the CIMA P6 paper?',
                name: 'cima_p6'
            }]
        }]
    }

    var workExpitirnce = {
        xtype: 'quiz.questionset',
        items: {
            xtype: 'quiz.question',
            fieldLabel: 'How many years of work experience do you have?',
            name: 'work_experience',
            columns: [60, 120, 80, 120],
            items: [{
                boxLabel: 'None',
                inputValue: '1'
            }, {
                boxLabel: 'Less than 2 years',
                inputValue: '2'
            }, {
                boxLabel: '2-5 years',
                inputValue: '3'
            }, {
                boxLabel: 'More than 5 years',
                inputValue: '4'
            }]
        }
    }

    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: 'combo',
            fieldLabel: 'Intake<b>*</b>',
            hiddenName: 'intake',
            store: new Ext.data.JsonStore({
                fields: ['name', 'title'],
                root: 'result',
                autoLoad: true,
                url: document.baseURI + 'dictionary/intakes'
            }),
            editable: false,
            valueField: 'name',
            displayField: 'title',
            mode: 'local',
            triggerAction: 'all',
            emptyText: 'Select an intake',
            selectOnFocus: true
        }, {
            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 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 + 'guest/verify-quiz',
                        success: function(form, action){
                            document.location = document.baseURI + action.result.location 
                        }
                    })
                    
                    return;
                }
            }
        }],
        initComponent: function(){
            Quiz.superclass.initComponent.call(this);
            
            this.add(languageLevel, qualificationLavel, workExpitirnce, {
                xtype: 'label',
                html: '<h4>Personal Information</h4>'
            }, personalInformation, {
                xtype: 'label',
                html: '<div id="data-protection">'
                     + '<h4>Data Protection</h4>'
                     + '<div>We collect information on this form solely for the purpose of determining your eligibility to apply for your programme of choice and contacting you with relevant information about this programme. Meeting the basic eligibility criteria, however, does not guarantee admission, and you should apply using the full application form.</div>'
                     + '<div>To access and manage your personal information, please follow the instructions given from your confirmation email.</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 + 'guest/quiz',
                method: 'POST',
                success: callback,
                failure: callback,
                scope: this
            })
        }
    });
    
    new Quiz({
        id: 'debug',
        renderTo: 'quiz-form'
    });
});
