// JavaScript Document
function getDateObject(dateString,dateSeperator)
{
	//This function return a date object after accepting 
	//a date string ans dateseparator as arguments
	var curValue=dateString;
	var sepChar=dateSeperator;
	var curPos=0;
	var cDate,cMonth,cYear;
	var sPayment="payment";
	var sChecked="false";

	//extract day portion
	curPos=dateString.indexOf(sepChar);
	cDate=dateString.substring(0,curPos);
	
	//extract month portion				
	endPos=dateString.indexOf(sepChar,curPos+1);			cMonth=dateString.substring(curPos+1,endPos);

	//extract year portion				
	curPos=endPos;
	endPos=curPos+5;			
	cYear=curValue.substring(curPos+1,endPos);
	
	//Create Date Object
	dtObject=new Date(cYear,cMonth,cDate);	
	return dtObject;
}
Ext.namespace('Ext.exampledata');
Ext.exampledata.titles = [
						  	['Mr'],
							['Mrs'],
							['Miss'],
							['Ms'],
							['Other']
						  ];
Ext.exampledata.sex = [
						  	['Male'],
							['Female']
						  ];

Ext.exampledata.marital = [
						  	['Unmarried'],
							['Married'],
							['Divorced'],
							['Widowed']
						  ];
Ext.exampledata.income_band = [
						  	['<7K'],
							['7-15K'],
							['15-25K'],
							['25-35K'],
							['35-50K'],
							['>50K']
						  ];
Ext.exampledata.ethnicity = [
						  	['White'],
							['Asian'],
							['Black'],
							['Other']
						  ];
Ext.exampledata.roles = [
						  	['MWP'],
							['Minister'],
							['Editor'],
							['Expert'],
							['Lobby Group Leader'],
							['Elector'],
							['Pollster'],
							['Non Elector'],
							['Support Staff'],
							['Superuser']
						  ];
Ext.exampledata.email_noti = [
						  	['1','Yes'],
							['0','No']
						  ];
Ext.exampledata.pay_method = [
							  ['Beta']
//							  ['Paypal']
							  ];
Ext.apply(Ext.form.VTypes, {
  password: function(val, field) {
    if (field.initialPassField) {
      var fs = Ext.getCmp(field.initialPassField);
      return (val == fs.getValue());
    }
    return true;
  },
  title: function(val, field) {
    if (field.initialPassField) {
      var fs = Ext.getCmp(field.initialPassField);
      return ('Other' != fs.getValue());
    }
    return true;
  },user_name: function(val, field) {
    var username = val;
		if(username.length<5)
			return false;
		var temp;
	
		if(!(username.charAt(0)>="A" && username.charAt(0)<="z"))
			return false;
		if((username.charAt(username.length-1)>="A" && username.charAt(username.length-1)<="z") || (username.charAt(username.length-1)>="0" && username.charAt(username.length-1)<="9"))
			temp="";
		else
			return false;
			
		for(var i=0;i<username.length;i++){
			temp=username.charAt(i);
			
			if((temp>="0" && temp<="9") || (temp>="A" && temp<="z") || (temp=="_") || (temp=="-"))
				temp="";
			else
				return false;
			
		}
		return true;
  },
  postcode: function(val, field) {
    var alphaPattern=/^([A-Z]$)/;
	var numericPattern=/^([0-9]$)/;
	//field.setValue(field.getValue().toUpperCase());
	val=val.replace(" ","");
	val=val.toUpperCase();
	var postcode_formats=Array(4);
	postcode_formats[0]="ANNNAA";
	postcode_formats[1]="ANNAA";
	postcode_formats[2]="AANNNAA";
	postcode_formats[3]="AANNAA";
	var value_length=val.length;
	var is_valid=false;
	for(var i=0;i<4;i++) {
		if(is_valid) continue;
		var format_len=postcode_formats[i].length;
		if(value_length==format_len) {
			var temp=1;
			for(var k=0;k<format_len;k++) {
				if(temp==0) continue;
				if(postcode_formats[i].charAt(k)=='A') {
					if(!alphaPattern.test(val.charAt(k)))  temp=0;
				} else if(postcode_formats[i].charAt(k)=='N') {
					if(!numericPattern.test(val.charAt(k)))  temp=0;
				}
			}
			if(temp==1) is_valid=true;
		}
	}
	return is_valid;
  },
  dob_date: function(val,field) {
	  if(val!="") {
	  	org_date=getDateObject(today_dob,"/");
	  	selected_date=getDateObject(val,"/");
	  	return org_date>selected_date;
	  } else {
		return true;  
	  }
  },
  dob_dateText: 'Invalid Date of Birth. It should be a past date.',
  postcodeText: 'Invalid Postcode',
  user_nameText: 'Invalid Username',
  passwordText: 'Passwords do not match',
  passwordText: 'Please enter title'
});
Ext.onReady(function(){

    Ext.QuickTips.init();

    // turn on validation errors beside the field globally
    Ext.form.Field.prototype.msgTarget = 'under';

    var fs = new Ext.FormPanel({
        frame: false,
        title:'',
        labelAlign: 'right',
        labelWidth: 150,
        width:880,
        waitMsgTarget: true,

        // configure how to read the XML Data
        reader : new Ext.data.XmlReader({
            record : 'contact',
            success: '@success'
        }, [
            {name: 'txtusername', mapping: 'username'},
			{name: 'txtemail', mapping: 'email'},
			{name: 'txttitle', mapping: 'title'},
			{name: 'txtgiven_name', mapping: 'given_name'},
			{name: 'txtfamily_name', mapping: 'family_name'},
			{name: 'txtaddress_1', mapping: 'address1'},
			{name: 'txtaddress_2', mapping: 'address2'},
			{name: 'txttown', mapping: 'town'},
			{name: 'txtcounty', mapping: 'county'},
			{name: 'txtpostcode', mapping: 'postcode'},
			{name: 'txtcountry', mapping: 'country'},
			{name: 'txtgender', mapping: 'gender'},
			{name: 'txtmarital', mapping: 'marital_status'},
			{name: 'txtincome_band', mapping: 'income_band'},
			{name: 'txtethnicity', mapping: 'ethnicity'},
			{name: 'txtparty', mapping: 'party'},
			{name: 'txtconstituency', mapping: 'constituency'},
			{name: 'txtemail_notification', mapping: 'send_mail'},
			{name: 'dob', type:'date', dateFormat:'d/m/Y', mapping: 'date_of_birth'} // custom data types
        ]),

        // reusable eror reader class defined at the end of this file
        errorReader: new Ext.form.XmlErrorReader(),

        items: [
            new Ext.form.FieldSet({
                title: 'Account Information',
                autoHeight: true,
                defaultType: 'textfield',
				
				
                items: [
					{
						inputType: 'hidden',
                        name: 'server_action',
						value: 'signup_form'
                    },
						{
                        fieldLabel: 'Username',
                        name: 'txtusername',
						allowBlank:false,
						minLength: '5',
						vtype: 'user_name',
						maxLength: '25',
                        width:190
                    }, {
                        fieldLabel: 'Password',
                        name: 'txtpassword',
						id: 'txtpassword',
						inputType: 'password',
						allowBlank:false,
						minLength: '6',
						maxLength: '10',
                        width:190
                    }, {
                        fieldLabel: 'Re-type Password',
                        name: 'txtrpassword',
						inputType: 'password',
						allowBlank:false,
						vtype: 'password',
						minLength: '6',
                        width:190,
						initialPassField: 'txtpassword'
                    }, {
                        fieldLabel: 'Email',
                        name: 'txtemail',
						maxLength: '255',
                        vtype:'email',
                        width:190
                    }
                ]
            }),
			new Ext.form.FieldSet({
                title: 'Contact Information',
                autoHeight: true,
                defaultType: 'textfield',
                items: [ 
					new Ext.form.ComboBox({
                        fieldLabel: 'Title',
                        hiddenName:'txttitle',
                        store: new Ext.data.SimpleStore({
                            fields: ['val'],
                            data : Ext.exampledata.titles // from titles array above
                        }),
                        valueField:'val',
                        displayField:'val',
                        typeAhead: true,
                        mode: 'local',
						editable: false,
                        triggerAction: 'all',
                        emptyText:'Select a Title...',
                        selectOnFocus:true,
						forceSelection: true,
						allowBlank:false,
                        width:110,
						listeners: { select: function() {
							if(this.getValue()=='Other') {
								Ext.getCmp('txtother_title').show();
								Ext.getCmp('txtother_title').setValue("");
								Ext.getCmp('txtother_title').focus();
							} else {
								Ext.getCmp('txtother_title').hide();
								Ext.getCmp('txtother_title').setValue("--No Value--");
							}
						}}
                    }), {
                        fieldLabel: '',
						allowBlank:false,
						value: '--No Value--',
						labelSeparator: '',
						minLength: '1',
						hideMode: 'display',
						hidden: true,
                        name: 'txtother_title',
						id: 'txtother_title',
						maxLength: '50',
                        width:190
                    },{
                        fieldLabel: 'Given Name',
						allowBlank:false,
						minLength: '1',
                        name: 'txtgiven_name',
						maxLength: '50',
                        width:190
                    }, {
                        fieldLabel: 'Family Name',
						allowBlank:false,
						minLength: '1',
						maxLength: '25',
                        name: 'txtfamily_name',
                        width:190
                    },{
                        fieldLabel: 'Address 1',
						allowBlank:false,
						minLength: '1',
						maxLength: '50',
                        name: 'txtaddress_1',
                        width:190
                    },
					{
                        fieldLabel: 'Address 2',
						minLength: '1',
						maxLength: '50',
                        name: 'txtaddress_2',
                        width:190
                    },{
                        fieldLabel: 'Town',
						allowBlank:false,
						minLength: '1',
						maxLength: '50',
                        name: 'txttown',
                        width:190
                    },{
                        fieldLabel: 'County',
						maxLength: '50',
                        name: 'txtcounty',
                        width:190
                    },{
                        fieldLabel: 'Postcode',
						allowBlank:false,
						minLength: '1',
						maxLength: '50',
						vtype: 'postcode',
						listeners: {'change':function(form){
							this.setValue(this.getValue().toUpperCase());
						}},
                        name: 'txtpostcode',
                        width:190
                    },
					new Ext.form.ComboBox({
                        fieldLabel: 'Country',
                        hiddenName:'txtcountry',
                        store: new Ext.data.SimpleStore({
                            fields: ['val','text'],
                            data : Ext.tabledata.countries 
                        }),
                        valueField:'val',
                        displayField:'text',
                        typeAhead: true,
                        mode: 'local',
                        triggerAction: 'all',
                        emptyText:'Select a Country...',
                        selectOnFocus:true,
						editable: true,
						forceSelection: true,
						allowBlank:false,
                        width:190
                    }) 
                ]
            }),
			new Ext.form.FieldSet({
                title: 'Personal Information',
                autoHeight: true,
                defaultType: 'textfield',
                items: [ 
					new Ext.form.DateField({
                        fieldLabel: 'Date of Birth',
                        name: 'dob',
                        width:190,
						format: 'd/m/Y',
						vtype: 'dob_date',
                        allowBlank:false,
						value: default_dob ? default_dob : undefined
                    }),
                    new Ext.form.ComboBox({
                        fieldLabel: 'Gender',
                        hiddenName:'txtgender',
                        store: new Ext.data.SimpleStore({
                            fields: ['val'],
                            data : Ext.exampledata.sex // from titles array above
                        }),
                        valueField:'val',
                        displayField:'val',
                        typeAhead: true,
                        mode: 'local',
						editable: false,
                        triggerAction: 'all',
                        emptyText:'Select a Gender...',
                        selectOnFocus:true,
						allowBlank:true,
                        width:125
                    }),
					 new Ext.form.ComboBox({
                        fieldLabel: 'Marital Status',
                        hiddenName:'txtmarital',
                        store: new Ext.data.SimpleStore({
                            fields: ['val'],
                            data : Ext.exampledata.marital // from titles array above
                        }),
                        valueField:'val',
                        displayField:'val',
                        typeAhead: true,
                        mode: 'local',
                        triggerAction: 'all',
						editable: false,
                        emptyText:'Select a Marital Status...',
                        selectOnFocus:true,
						allowBlank:true,
                        width:150
                    }),
					 new Ext.form.ComboBox({
                        fieldLabel: 'Income Band',
                        hiddenName:'txtincome_band',
                        store: new Ext.data.SimpleStore({
                            fields: ['val'],
                            data : Ext.exampledata.income_band // from titles array above
                        }),
                        valueField:'val',
                        displayField:'val',
                        typeAhead: true,
                        mode: 'local',
						editable: false,
                        triggerAction: 'all',
                        emptyText:'Select a Income Band...',
                        selectOnFocus:true,
						allowBlank:true,
                        width:150
                    }),
					 new Ext.form.ComboBox({
                        fieldLabel: 'Ethnicity',
                        hiddenName:'txtethnicity',
                        store: new Ext.data.SimpleStore({
                            fields: ['val'],
                            data : Ext.exampledata.ethnicity // from titles array above
                        }),
                        valueField:'val',
                        displayField:'val',
                        typeAhead: true,
                        mode: 'local',
                        triggerAction: 'all',
						editable: false,
                        emptyText:'Select a Ethnicity...',
                        selectOnFocus:true,
						allowBlank:true,
                        width:125
                    }),{
                        fieldLabel: 'Party',
						maxLength: '20',
                        name: 'txtparty',
                        width:190
                    },
					 
					 new Ext.form.ComboBox({
                        fieldLabel: 'Email Notification',
                        hiddenName:'txtemail_notification',
                        store: new Ext.data.SimpleStore({
                            fields: ['val','text'],
                            data : Ext.exampledata.email_noti // from titles array above
                        }),
                        valueField:'val',
                        displayField:'text',
                        typeAhead: true,
                        mode: 'local',
						editable: false,
                        triggerAction: 'all',
                        emptyText:'Select',
                        selectOnFocus:true,
						allowBlank:true,
                        width:125
                    }),
                    
			new Ext.form.Label({
				style: 'font-weight:bold; font-size:12px;padding:15px;',
				text: 'Note: Except for membership notifications which will still be sent to your email address.\n '
			})

                ]
            }),
			new Ext.form.FieldSet({
                title: 'Payment Information',
                autoHeight: true,
				 disabled: false,
                defaultType: 'textfield',
                items: [ 
			new Ext.form.ComboBox({
                        fieldLabel: 'Payment Method',
                        hiddenName:'txtpaymethod',
                        store: new Ext.data.SimpleStore({
                            fields: ['val'],
                            data : Ext.exampledata.pay_method 
                        }),
                        valueField:'val',
                        displayField:'val',
                        typeAhead: true,
                        mode: 'local',
			editable: false,
                        triggerAction: 'all',
                        emptyText:'Select a Payment Method',
                        selectOnFocus:true,
			forceSelection: true,
			allowBlank:false,
						listeners: { select: function() {
							if(this.getValue()=='Beta') {
								sPayment="payment_beta";
							} else {
								sPayment="payment";
							}
						}},
                        width:110
                    }),
					new Ext.form.Label({
						style: 'font-weight:bold; font-size:12px;padding:15px;',
						text: 'Note: Address declared MUST match with the credit card address.\n     '
					})
                ]

            }),
		new Ext.form.FieldSet({
                title: 'Terms and Conditions',
                autoHeight: true,
		        disabled: false,
                //defaultType: 'textfield',
                items: [
                {
                    layout: 'column',
                    border: false,
                    defaults:
                    {
                        border: false
                    },
                    items:
                    [{
                        columnWidth: '0.03',
                        layout: 'form',
                        items:
                        [
                            new Ext.form.Checkbox({
		       	                  name:'chkterms',
			                      allowBlank: false,
			                      hideLabel: true,
			                      boxLabel: '',
			                      listeners:
			                      {
			                          check: function()
			                          {
			                              if(this.getValue())
			                              {
			                                  Ext.getCmp('txttermsmess').hide();
			                                  sChecked="true";
			                              }
			                              else
			                              {
			                                  Ext.getCmp('txttermsmess').show();
			                                  Ext.getCmp('txttermsmess').focus();
			                                  sChecked="false";
			                              }
			                          }
			                      },
			                      checked: false
                            })
                        ]
                    },
                    {
                        columnWidth: '0.97',
                        layout: 'form',
                        items:
                        [
                            new Ext.form.Label({
                                html: 'I agree to the <a href="../../terms_and_conditions/" target="_blank">Terms and Conditions (click here to read)</a>'
                            })
                        ]
                    }]
                },
                new Ext.form.Label({
	                hideMode: 'display',
	                hidden: false,
	                            name: 'txttermsmess',
	                id: 'txttermsmess',
	                style: 'font-weight:bold; color:red; font-size:12px;padding:15px;',
	                text: 'Note: Read the Terms and Conditions and Check the box above to agree.\n     '
                })
                ]
			})
        ]
    });




    // explicit add
    var submit = fs.addButton({
        text: 'Submit',
        handler: function()
        {
			if(sChecked == 'true'){
				fs.getForm().submit({url: SITE_URL+'register/add/', waitMsg:'Please Wait...'});
			} else {
				fs.getForm().submit({url: SITE_URL+'register/check/', waitMsg:'Please Wait...'});
			}
        }
    });

    fs.render('form_registration');
	if(retry==1) {
		fs.getForm().load({url: SITE_URL+'register/index/retreive/', waitMsg:'Loading..'});	
	}
    fs.on({	
        actioncomplete: function(form, action){
            if(action.type == 'submit'){
		if(sChecked == 'true'){
			Ext.MessageBox.show({
			   title: 'Please wait',
			   msg: 'Processing Membership Application...',
			   progressText: 'Initializing...',
			   width:300,
			   progress:true,
			   closable:false,
			   animEl: 'mb6'
			});
			
			// this hideous block creates the bogus progress
			var f = function(v){
				return function(){
					if(v == 12){
						window.location=SITE_URL+"register/"+sPayment+"/";
					}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);
			}
		}
            }
	    
	    if(action.type=='load') {
		var titleobj = Ext.getCmp('txttitle_id');
		if(titleobj.getValue()=='Other') {
			Ext.getCmp('txtother_title').show();
		} else {
			Ext.getCmp('txtother_title').hide();
		}	
	    }
        },
	actionfailed: function(form, action){
		if(action.type == 'submit'){
			Ext.MessageBox.alert('Error', 'Please correct the errors specified in Red.');
		}
	}
    });
});

// A reusable error reader class for XML forms
Ext.form.XmlErrorReader = function(){
    Ext.form.XmlErrorReader.superclass.constructor.call(this, {
            record : 'field',
            success: '@success'
        }, [
            'id', 'msg'
        ]
    );
};
Ext.extend(Ext.form.XmlErrorReader, Ext.data.XmlReader);