/*
 * Ext JS Library 3.3.1
 * Copyright(c) 2006-2007, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

// Reference local blank image to prevent link back to extjs.com
Ext.BLANK_IMAGE_URL = 'http://www.boonsboropharmacy.com/ext-3.3.1/resources/images/default/s.gif';


// Add the additional 'advanced' VTypes
Ext.apply(Ext.form.VTypes, {
    daterange : function(val, field) {
        var date = field.parseDate(val);

        if(!date){
            return;
        }
        if (field.startDateField && (!this.dateRangeMax || (date.getTime() != this.dateRangeMax.getTime()))) {
            var start = Ext.getCmp(field.startDateField);
            start.setMaxValue(date);
            start.validate();
            this.dateRangeMax = date;
        } 
        else if (field.endDateField && (!this.dateRangeMin || (date.getTime() != this.dateRangeMin.getTime()))) {
            var end = Ext.getCmp(field.endDateField);
            end.setMinValue(date);
            end.validate();
            this.dateRangeMin = date;
        }
        /*
         * Always return true since we're only using this vtype to set the
         * min/max allowed values (these are tested for after the vtype test)
         */
        return true;
    }
});

Ext.onReady(function(){

  Ext.QuickTips.init();

  // turn on validation errors beside the field globally
  Ext.form.Field.prototype.msgTarget = 'side';

  /* Note: You dont need a JSON reader because there is one built into Ext.form.
            All you need to do is make sure your fields in the json match the spelling of your field names
             in the field items array for the form.
        */

  //Min AGE is 18 years Old	+ subtract five leap year days	
  var validMaxDate=new Date();
     validMaxDate.setDate(validMaxDate.getDate()-6570-5);
	 
  //Max Age is 95 years Old - 25 leap year days
  var validMinDate=new Date();
     validMinDate.setDate(validMinDate.getDate()-34675-25);
	 
  var fs = new Ext.form.FormPanel({
      frame: true,
      title:'Account Registration',
      labelAlign: 'right',
      labelWidth: 110,
      width:365,
	  //height: 515,
      //waitMsgTarget: true,
      baseParams:{recordID: 1}, // This is actually overridden "on the fly" below when the Load button is clicked.

      items: [
             new Ext.form.FieldSet({
                 title: 'Customer Information',
				 autoHeight: true,
                 defaultType: 'textfield',
				 
                 items: [{
                          fieldLabel: 'First Name',
                          name: 'First',
					      allowBlank:false,
                          width:190
						  //plugins: [new Ext.ux.InputTextMask('ABC', true)],
                    }, {
                          fieldLabel: 'Last Name',
                          name: 'Last',
						  allowBlank:false,
                          width:190
                    },
					new Ext.form.DateField({
                        fieldLabel: '<b>Birthdate</b>',
                        name: 'userBirthDate',
						allowBlank:false,
                        width:190,
						format: 'm/d/Y',
						maxLength: 10,
						emptyText:'Please select a date...',
						vtype: 'daterange',
						defaultType: 'datefield',
						minValue: validMinDate,
						maxValue: validMaxDate,
						showToday: false,
						id: 'userBirthDate'
					}),
					
					{
						 fieldLabel: 'Street Address',
						 name: 'StreetAddress',
						 allowBlank:false,
						 width:190
					},{
						 fieldLabel: 'City',
						 name: 'City',
						 allowBlank:false,
						 width:190					
					},{
						 fieldLabel: 'ZipCode',
						 name: 'ZipCode',
						 allowBlank:false,
						 plugins: [new Ext.ux.InputTextMask('99999', true)],
						 width:190
					},
					new Ext.form.ComboBox({
                        fieldLabel: 'State',
                        hiddenName:'state',
						allowBlank:false,
                        store: new Ext.data.SimpleStore({
                            fields: ['abbr', 'state'],
                            data : Ext.exampledata.states // from states.js 
                        }),
                        valueField:'abbr',
                        displayField:'state',
                        typeAhead: true,
                        mode: 'local',
                        triggerAction: 'all',
                        emptyText:'Select a state...',
                        selectOnFocus:true,
                        width:190
                    }),
					
					{
						 fieldLabel: 'Home Phone',
						 name: 'HomePhone',
						 allowBlank:false,
						 plugins: [new Ext.ux.InputTextMask('999-999-9999', true)],
						 width:190
					},{
						 fieldLabel: 'Mobile Phone',
						 name: 'Mobile',
						 plugins: [new Ext.ux.InputTextMask('999-999-9999', true)],
						 width:190
					},{ 
                         fieldLabel: 'Email',
                         name: 'Email',
                         vtype:'email', // ie Validate as an email field
						 allowBlank:false,
                         width:190					
                    }, { 
                         fieldLabel: '<b>Re-Enter Email</b>',
                         name: 'checkEmail',
                         vtype:'email', // ie Validate as an email field
						 allowBlank:false,
                         width:190					
                    },{
						 fieldLabel: 'Password',
						 name: 'Password',
						 allowBlank:false,
						 inputType: 'password'
					},{
						 fieldLabel: '<b>Re-Enter Password</b>',
						 name: 'checkPassword',
						 allowBlank:false,					
						 inputType: 'password'
					},
					{
						xtype: 'checkbox',
						boxLabel: 'Receive <b>Emails</b> about <b>Pharmacy Diabetic Events?</b>',
						id: 'diabeticID',
						height: 45
					}             
										
                ]
					
            })
        ]
    });
				
	
/*************************************
There are a couple of functions you can use to check the success or failure of
form loads and submits.
* formPanel.onactioncomplete and formPanel.onactionfailed 
* formPanel.form.load.success, formPanel.form.load.failure
* formPanel.form.submit.success, formPanel.form.submit.failure
See how these are implemented below.

All these functions are optional but for robust error checking you should use them and 
take appropriate action. The following should help you understand what to do.

FORM LOADING:    

Successful load : both the formPanel.form.load.success and the formPanel.onactioncomplete fire        

Unsuccessful load:
There are 2 ways to trap load errors - the on.actionfailed and the load.failure.
In all cases except 4 (below) both the load.failure and on.actionfailed are fired.
You have various options for trapping and reporting the folowing errors.

The various possible error conditions I can think of are trapped as follows:
    1. The server script (json-form-getjson.cfm/php in this case) is not found: 
    load.failure is fired, on.actionfailed is fired
    (Presumably other server errors that resulted in no return would result 
    in the same error conditions)
    
    2. The server script (json-form-getjson.cfm/php in this case) is found and the 
    server script itself trapped an error eg the record was not found in the database table.
    Consequently you return success:false in the json. 
    load.failure is fired, on.actionfailed is fired
    
    3. json success field is missing altogether (or misspelt): 
    load.failure fired, on.actionfailed is fired
    
    4. json success field is neither true or false eg a typo - success:tru : 
    neither gets fired, the load function never returns and the wait message keeps displaying.
    (Bug in Ext???)
    
    5. json is an EMPTY string.  
        load.failure is fired, on.actionfailed is fired
        If the string is just spaces, see result 4 above. 


FORM SUBMIT:
Successful submit : both the formPanel.form.submit.success and the formPanel.onactioncomplete fire

Unsuccessful submit:
The various possible error conditions I can think of are trapped as follows:
    1. The server script (json-form-submit.cfm/php in this case) is not found: 
    submit.failure is fired, on.actionfailed is fired
    (Presumably other server errors that resulted in no return would result 
    in the same error conditions)
        
    2. The server script (json-form-submit.cfm/php in this case) is found and the 
    server script itself trapped an error eg saving would create a duplicate record 
        in the database table, or updating a non existing record, etc.
    Consequently you return success:false in the json. 
        
    submit.failure is fired, on.actionfailed is fired
    3. json success field is missing altogether (or misspelt): 
    submit.failure is fired, on.actionfailed is fired
        
    4. json success field is neither true or false eg a typo - success:tru : 
    neither gets fired, the submit function never returns and the wait message keeps displaying.
    (Bug in Ext???)  
    
    5. json is an EMPTY string. Only the on.actioncomplete fires, 
        neither submit.failure is fired nor on.actionfailed is fired.
        This also seems like a bug, but maybe there is some reason for it.  
        If the string is just spaces, see result 4 above.       

So, to sum up for both load and submit, whenever there is some kind of error (apart from the type 
listed at point 4 above), both the failure function AND the actionfailed function fire. 
It then becomes a question of which function you should use to trap the errors (and then not 
declaring the other one so that only one of the 2 functions fire).
Similarly, if you need to take action based upon a successful load or submit, declare either the success or actioncompleted
function.

So, the code below takes the approach that since the actionfailed function is used by both 
load and submit it makes sense (IMO) to locate all the error checking there. There may be other
reasons that I am not aware of so dont take this as gospel. The one exception is where the json contains
an empty string on a submit and Ext doesnt raise an error. In that case you need the check in the actioncomplete 
to pick that up.
********************************************/

  // Define the Cancel button  and the  action required
		 
  var load = fs.addButton({
      text: 'Cancel',
      disabled:false,
      handler: function(){
          fs.form.load({            
				    //Should not enter this code, just re-direct back to main page
					url:'fake-form.php', // PHP
                    //Ext.MessageBox.alert('Message', 'Saved OK');
                failure:function(form, action) {
					window.location = 'http://www.boonsboropharmacy.com'; //Re-Direct user to main page.
                }
             
            });
         }
  });
	
        // Define the Submit button and the action required. This will be enabled if the Load is successful.
    var submit = fs.addButton({
        text: '<b>Submit</b>',
        disabled:false,
        handler: function(){
            fs.form.submit({			  
                url:'/wp/wp-content/themes/boonsboro/register-form-submit.php', // PHP
                waitMsg:'Saving Data...',
                /*  Alternatively, instead of using actionfailed / complete (below) you could use these functions:*/	        
                success: function (form, action) {
                    //Ext.MessageBox.alert('Message', 'Saved OK');
                },
                failure:function(form, action) {                     
                }
            });
         }
    });

	
    fs.render('form-ct');

    fs.on({
        actioncomplete: function(form, action){
            // Only enable the submit button if the load worked
            //if(action.type == 'load'){
                //submit.enable();
                //Ext.MessageBox.alert('fs.actioncomplete', 'All OK.'); // Optional. Just for testing
				//window.location = 'startpage.aspx'; //Re-Direct user to main page.
            //} 
            
            if (action.type == 'submit'){
                        // If the responseText is a null string, Ext doesnt raise an error so trap it here 
                        // as an error because it should be some json.
                if (action.response.responseText == '') 
				{
                  Ext.MessageBox.alert('Message', 'Form submit returned an empty string instead of json');
                } 
				else 
				{
				  //Ext.MessageBox.alert('fs.actioncomplete', 'All OK.'); // Optional. Just for testing
				  window.location = '/wp/registration-complete'; //Re-Direct user to main page.
				}
            }
        },
          // The following code could be rationalised but I did it this way to make it easier
          // to follow and for you to test it yourself.
          // NOTE: the line var result = Ext.decode(action.response.responseText); must be
          // called AFTER you have made sure there wasnt a failureType == "connect" or you 
          // will probably get a JS error in the Ext library.
                            
        actionfailed: function(form,action){
            if(action.type == 'submit') { // Handle the SUBMIT errors
				
                if (action.failureType == "connect") { 
                    Ext.MessageBox.alert('Message', 'Registration Form submit failed. Could not connect to server.');
                } else 
                    if (action.failureType == "server") { 
                        // These arent "errors" as such, they are validation issues trapped by the server script and passed back for the user to correct
                    } else {    
                        var result = Ext.decode(action.response.responseText); 
						//document.write("<br> My result msg " + result + '</br>');
                        if(result && result.msg) {            
                            Ext.MessageBox.alert('Message', 'Registration Form submit failed with error: ' + action.result.msg);
                        } else {
                            Ext.MessageBox.alert('Message', 'Registration Form submit returned unknown error. Action type='+action.type+', failure type='+action.failureType);
                          }
                      }
            }   
            
        } // end actionfailed listener
    }); // end fs.on

});


