// JavaScript Document
Ext.onReady(function(){
	 Ext.QuickTips.init();
	 	//blank image link needed**	
Ext.BLANK_IMAGE_URL = '../ext-2.0/resources/images/default/s.gif';  

    // turn on validation errors beside the field globally
    Ext.form.Field.prototype.msgTarget = 'side';
	var form = new Ext.form.FormPanel({
		frame: true,
        bodyStyle:'padding:10px 5px 5px 5px',
		waitMsgTarget: true,
		renderTo: 'form',
		labelWidth: 380,
		title: 'Take the survey!',
		autoWidth: true,
        url:'includes/survey_process.php',
        defaultType: 'textfield',
         items: [{
            xtype:'fieldset',
            checkboxToggle:true,
			id: 'overpaid',
            title: 'Yes - I think I\'ve overpaid tax on my income?',
            autoHeight:true,
            defaults: {width: 150, labelSeparator: ''},
            defaultType: 'textfield',
			labelWidth: 380,
            collapsed: true,
            items :[{
                    fieldLabel: 'This is because of',
                    xtype: 'combo',
        store: new Ext.data.SimpleStore({
        fields: ['userval', 'value'],
        data : Ext.exampledata.overreasons // from data.js
    }),
        displayField:'value',
		valueField: 'userval',
        typeAhead: true,
        mode: 'local',
		hiddenName: 'over_reason',
        triggerAction: 'all',
		editable: false,
        emptyText:'please select...',
        selectOnFocus:true
    },
				{
                    fieldLabel: 'This relates to tax paid',
                    xtype: 'combo',
        store: new Ext.data.SimpleStore({
        fields: ['userval', 'value'],
        data : Ext.exampledata.overpaid // from data.js
    }),
        displayField:'value',
		valueField: 'userval',
        typeAhead: true,
        mode: 'local',
		editable: false,
		hiddenName: 'over_paid',
        triggerAction: 'all',
        emptyText:'please select...',
        selectOnFocus:true
    },{
                    fieldLabel: 'How much did you earn in this tax year? (all jobs)(£)',
                    name: 'over_earn'
                },{
                    fieldLabel: 'How much did you pay? (all jobs)(£)',
                    name: 'over_total'
                },{
                    fieldLabel: 'Did any of your tax codes contain...',
                    xtype: 'combo',
        store: new Ext.data.SimpleStore({
        fields: ['userval', 'value'],
        data : Ext.exampledata.overcodes // from data.js
    }),
        displayField:'value',
		valueField: 'userval',
        typeAhead: true,
        mode: 'local',
		editable: false,
		hiddenName: 'over_codes',
        triggerAction: 'all',
        emptyText:'please select...',
        selectOnFocus:true
    }
            ]
        },{
            xtype:'fieldset',
            checkboxToggle:true,
			id: 'carset',
            title: 'Yes - I have used my own car to carry out my job, not including travelling to/from work?',
            autoHeight:true,
            defaults: {width: 150, labelSeparator: ''},
			labelWidth: 380,
            defaultType: 'textfield',
            collapsed: true,
            items :[{
                    fieldLabel: 'How many years',
                    name: 'car_years'
                },
				{
                    fieldLabel: 'Does your employer reimburse you? How much?',
                    name: 'car_remb'
                },{
                    fieldLabel: 'Approximately how many miles each year?',
                    name: 'car_miles'
                }
            ]
        },{
            xtype:'fieldset',
			id: 'tools-set',
            checkboxToggle:true,
            title: 'Yes - I have bought tools, equipment or incurred costs necessary to do my job?',
            autoHeight:true,
            defaults: {width: 150, labelSeparator: ''},
			labelWidth: 380,
            defaultType: 'textfield',
            collapsed: true,
            items :[{
                    fieldLabel: 'What have you bought?',
                   xtype: 'combo',
        store: new Ext.data.SimpleStore({
        fields: ['userval', 'value'],
        data : Ext.exampledata.toolsbought // from data.js
    }),
        displayField:'value',
		valueField: 'userval',
        typeAhead: true,
		editable: false,
        mode: 'local',
		hiddenName: 'tools_bought',
        triggerAction: 'all',
        emptyText:'please select...',
        selectOnFocus:true
    },{
                    fieldLabel: 'Are you a?',
                  xtype: 'combo',
        store: new Ext.data.SimpleStore({
        fields: ['userval', 'value'],
        data : Ext.exampledata.toolsjob // from data.js
    }),
        displayField:'value',
		valueField: 'userval',
        typeAhead: true,
        mode: 'local',
		editable: false,
		hiddenName: 'tools_job',
        triggerAction: 'all',
        emptyText:'please select...',
        selectOnFocus:true
    },{
                    fieldLabel: 'How much have you spent in the last 6 years? (£)',
                    name: 'tools_amount'
                },{
                    fieldLabel: 'When did you start buying these things?',
                    xtype: 'combo',
        store: new Ext.data.SimpleStore({
        fields: ['userval', 'value'],
        data : Ext.exampledata.toolstart // from data.js
    }),
        displayField:'value',
		valueField: 'userval',
        typeAhead: true,
        mode: 'local',
		editable: false,
		hiddenName: 'tools_start',
        triggerAction: 'all',
        emptyText:'please select...',
        selectOnFocus:true
    },{
                    fieldLabel: 'How much of this amount has your employer reimbursed you?',
                    name: 'tools_emp'
                },{
					xtype: 'checkbox',
                    fieldLabel: 'Do other people doing the same job as you also have to buy these things?',
                    name: 'tools_other',
					boxLabel: 'Yes'
                }
            ]
        },{
            xtype:'fieldset',
			id: 'loss-set',
            checkboxToggle:true,
            title: 'Yes - I have lost money in business?',
            autoHeight:true,
            defaults: {width: 150, labelSeparator: ''},
			labelWidth: 380,
            defaultType: 'textfield',
            collapsed: true,
            items :[{
                    fieldLabel: 'How much money was lost? (£)',
                    name: 'loss_total'
                },{xtype: 'datefield',
                    fieldLabel: 'When was this lost?',
                    name: 'loss_date',
					format: 'd-m-Y'
                },{
                    fieldLabel: 'Have you told the taxman yet?',
                   xtype: 'combo',
        store: new Ext.data.SimpleStore({
        fields: ['userval', 'value'],
        data : Ext.exampledata.losstold // from data.js
    }),
        displayField:'value',
		valueField: 'userval',
        typeAhead: true,
        mode: 'local',
		editable: false,
		hiddenName: 'loss_told',
        triggerAction: 'all',
        emptyText:'please select...',
        selectOnFocus:true
    }
            ]
        },{
                    fieldLabel: 'What is your job title?',
                    name: 'job_title',
                    allowBlank:false,
					width: 150, 
					labelSeparator: ''
                },{
                    fieldLabel: 'What is your employment status?',
                    xtype: 'combo', 
					labelSeparator: '',
        store: new Ext.data.SimpleStore({
        fields: ['userval', 'value'],
        data : Ext.exampledata.status // from data.js
    }),
        displayField:'value',
		valueField: 'userval',
        typeAhead: true,
        mode: 'local',
		editable: false,
		hiddenName: 'job_status',
        triggerAction: 'all',
        emptyText:'please select...',
        selectOnFocus:true,
		allowBlank: false
    },{
                    fieldLabel: 'Indicate your annual income?',
                    xtype: 'combo',
					labelSeparator: '',
        store: new Ext.data.SimpleStore({
        fields: ['userval', 'value'],
        data : Ext.exampledata.income // from data.js
    }),
        displayField:'value',
		valueField: 'userval',
        typeAhead: true,
        mode: 'local',
		hiddenName: 'job_income',
        triggerAction: 'all',
		editable: false,
        emptyText:'please select...',
        selectOnFocus:true,
		allowBlank: false
    },{
                    fieldLabel: 'How do you currently pay tax?',
                    xtype: 'combo',
        store: new Ext.data.SimpleStore({
        fields: ['userval', 'value'],
        data : Ext.exampledata.tax // from data.js
    }),
        displayField:'value',
		valueField: 'userval',
        typeAhead: true,
        mode: 'local',
		hiddenName: 'job_tax',
        triggerAction: 'all',
		editable: false,
        emptyText:'please select...',
        selectOnFocus:true,
		allowBlank: false, 
		labelSeparator: ''
    }],
		        buttons: [{
            text: 'Have I got a refund?',
			handler: function(){
				if(form.form.isValid()){  
				Ext.MessageBox.show({
            title: 'Please wait',
           msg: 'Saving Survey Data...',
           progressText: 'Collecting items...',
           width:300,
           wait:true,
           waitConfig: {interval:200},
		   closable: false
       });
			form.form.submit({
				params:{
					action:'submit'
					},
					success:function(form, action){  
	   var uid = action.result.msg;
				  // this hideous block creates the bogus progress
       var f = function(v){
            return function(){
                if(v == 12){
                    Ext.MessageBox.hide();
					window.location = "http://www.payeright.co.uk/survey/stage2.php?uid="+uid; 
                }else{
                    var i = v/11;
                    Ext.MessageBox.updateProgress(i, Math.round(100*i)+'% completed');
                }
           };
       };
       for(var i = 1; i < 13; i++){
           setTimeout(f(i), i*200);
       }
    
					    },
					failure:function(form, action){
						if(action.result.errors.length > 0){
						 Ext.MessageBox.show({
           title: 'Survey Error',
		   msg: action.result.errors,
           width:300,
		   buttons: Ext.MessageBox.OK,
           icon: 'ext-mb-warning'
       });
						}
					}
			});
		}else{
			Ext.MessageBox.show({
           title: 'Survey Error',
		   msg: 'Please correct the indicated errors',
           width:300,
		   buttons: Ext.MessageBox.OK,
           icon: 'ext-mb-warning'
       });
		}
        }
		}]
    });
 //setup the validation on toggle
 var fieldsets = form.items.items;
 //for each items
 Ext.each(fieldsets, function(Node, Index, AllItems){
 	//check its a fieldset
 	if(Node.isXType('fieldset')){
		//on expand
		Node.on('expand', function(){
			//get the items inside the fieldset
		Ext.each(Node.items.items, function(Node, Index, AllItems){
			if(Node.isXType('combo') || Node.isXType('textfield')){
			//add the config options
				Ext.apply(Node, {allowBlank: false});
			}
		})
})
//on collapse
		Node.on('collapse', function(){
			//get the items inside the fieldset
		Ext.each(Node.items.items, function(Node, Index, AllItems){
			if(Node.isXType('combo') || Node.isXType('textfield')){
				//clear any invalid styles
				Node.clearInvalid();
				//clear any values
				if (Node.isXType('combo')) {
					Node.clearValue();
				}else{
					Node.reset();
				}
			//add the config options
				Ext.apply(Node, {allowBlank: true});
			}
		})
		})
	}
 });
 //check for checked fieldsets before submit
 var myForm = form.getForm();
myForm.on('beforeaction', function(Form, Action){
	//check for the collapsed ones
var check = Ext.query('fieldset.x-panel-collapsed');
//if theres 6, then send error and stop submit 
if(check.length == 6){
	Ext.MessageBox.show({
           title: 'Survey Error',
		   msg: 'You must answer <b>Yes</b> to at least one question before we can help you',
           width:300,
		   buttons: Ext.MessageBox.OK,
           icon: 'ext-mb-warning'
       });
	return false;
	}else{
		//go for it
		return true;
	}
}); 
 });
