/*
 * Ext JS Library 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 = 'ext-3.1/resources/images/default/s.gif';

Ext.onReady(function(){

  
    Ext.QuickTips.init({
	target: 'login-box',
    title: 'My Tooltip',
    text: 'This tooltip was added in code',
    width: 100,
    dismissDelay: 20});
   
   
	/*
	//SETUP THE COOKIE PROVIDER TO DETERMINE THE INITIAL STATE OF THE BUTTONS
	var cp = new Ext.state.CookieProvider({
				path: "/",
				//(1000*60*60*24*30))
				expires: new Date(new Date().getTime()+(1000*60*30)), //30 Minutes
				domain: "www.boonsboropharmacy.com",
				secure: true
			});
	Ext.state.Manager.setProvider(cp);					
	*/
	
    // 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.
                        */
						
function myHandler() {

//Ext.MessageBox.alert('Message', '<b>Caught Enter Key</b>');

}

    var fs = new Ext.form.FormPanel({
        frame: true,
        title:'',
        labelAlign: 'left',
        labelWidth: 75,
        width:292,
		keys:[{
			key: 13, // or Ext.EventObject.ENTER
			fn: function(){
            
			rememberMeIDCheck = Ext.getCmp('rememberMeID').getValue();
		
			 /**
			 ** Handler for SetCookie
			 **/ 
			function setCookieKeyPress(btn) {
			
					if (btn == 'no')
					{
					  Ext.getCmp('rememberMeID').setValue("off");
			        }
			  				
					fs.form.submit({
						url:'http://www.boonsboropharmacy.com/login-form.php', // PHP
						waitMsg:'Logging In...',
						timeout: 10,
						/*  Alternatively, instead of using actionfailed / complete (below) you could use these functions:*/	
						
						success: function (form, action) {
						   // Ext.MessageBox.alert('Message', 'Login OK');
						},
						failure:function(form, action) {
							if(action.response.responseText == '{success: false, errors:{Email:"User account has not been activated. Please check your email."} }')
							{
								Ext.MessageBox.alert('Message','<b>Account not Activated. Please check your email for activation email.</b>');
							}
						}//END FAILURE STATEMENT
             
					}); //END FORM SUBMIT
					
			} //END setCookieKeyPress
			  
				if (rememberMeIDCheck != "")
				{
					var dlg = Ext.Msg.confirm('Message','<b>Stay logged-in for 2 weeks?</b>',setCookieKeyPress).getDialog();
					dlg.defaultButton = 2;
					dlg.focus();	
				}
				else
				{
				    //DO REGULAR USER LOGIN
					fs.form.submit({
					url:'http://www.boonsboropharmacy.com/login-form.php', // PHP
					waitMsg:'Logging In...',
					timeout: 10,
					/*  Alternatively, instead of using actionfailed / complete (below) you could use these functions:*/	
					
					success: function (form, action) {
					   // Ext.MessageBox.alert('Message', 'Login OK');
					},
					failure:function(form, action) {
					//var result = Ext.decode(action.response.responseText); 
					//document.write("Result " + result +'<br>');
					//Ext.MessageBox.alert('Login', 'Invalid Username / Password Combination');
						if(action.response.responseText == '{success: false, errors:{Email:"User account has not been activated. Please check your email."} }')
						{
							Ext.MessageBox.alert('Message','<b>Account not Activated. Please check your email for activation email.</b>');
						}
					}
				 
				  }); //END FORM SUBMIT
		
				}//END ELSE STATEMENT
		
            }//END FUNCTION FOR ENTER KEY PRESSED
		}],
        items: [
            new Ext.form.FieldSet({
              title: 'Customer Login',
			   autoHeight: true,
               defaultType: 'textfield',
                items: [{
                        fieldLabel: '<b>Email ID</b>',
                        name: 'Email',
                        vtype:'email', // ie Validate as an email field
						allowBlank:false,
                        width:160,
						id: 'login-box'
	
                    },{
						fieldLabel: '<b>Password</b>',
						name: 'Password',
						allowBlank:false,
						width:160,
						inputType: 'password'
					},{
						xtype: 'checkbox',
						//labelAlign: 'left',
						height:15,
						boxLabel: 'Remember me for 2 weeks?',
						id: 'rememberMeID'
					}
				    
                ]
            })
        ]
    });
		
    // Define the Submit button and the action required. This will be enabled if the Load is successful.
	var submit = fs.addButton({
        text: '<b>Sign-In</b>',
		id: 'loginButton',
        disabled:false,
        handler: function(){
		
		rememberMeIDCheck = Ext.getCmp('rememberMeID').getValue();
		
		 /**
         * Handler for SetCookie
         */ 
		 function setCookie(btn) {
		 
					if (btn == 'no')
					{
					  Ext.getCmp('rememberMeID').setValue("off");
			        }
			           fs.form.submit({
						url:'http://www.boonsboropharmacy.com/login-form.php', // PHP
						waitMsg:'Logging In...',
						timeout: 10,
						/*  Alternatively, instead of using actionfailed / complete (below) you could use these functions:*/	
						
						success: function (form, action) {
						   // Ext.MessageBox.alert('Message', 'Login OK');
						},
						failure:function(form, action) {
						//var result = Ext.decode(action.response.responseText); 
					
						if(action.response.responseText == '{success: false, errors:{Password:"Cannot contain special characters"} }') 
						{
							Ext.MessageBox.alert('Message','<b>Password cannot contain special characters</b>');
						}
						else if(action.response.responseText == '{success: false, errors:{Email:"Invalid Email Account"} }')
						{
						   Ext.MessageBox.alert('Message','<b>Invalid Email Account.</b>');
						}
						else if(action.response.responseText == '{success: false, errors:{Email:"User account has not been activated. Please check your email."} }')
						{
							Ext.MessageBox.alert('Message','<b>Account not Activated. Please check your email for activation email.</b>');
						}
						else if(action.response.responseText == '{success:false,errors:{Email: "Invalid UserName / Password Combination"} }')
						{
							Ext.MessageBox.alert('Message','<b>Invalid Username / Password Combination</b>');
						}
					}
             
					}); //END FORM SUBMIT BRACKETT
              }
			  
				if (rememberMeIDCheck != "")
				{
					var dlg = Ext.Msg.confirm('Message','<b>Stay logged-in for 2 weeks?</b>',setCookie).getDialog();
					dlg.defaultButton = 2;
					dlg.focus();	
				}
				else
				{
				
				 fs.form.submit({
						url:'http://www.boonsboropharmacy.com/login-form.php', // PHP
						waitMsg:'Logging In...',
						timeout: 10,
						/*  Alternatively, instead of using actionfailed / complete (below) you could use these functions:*/	
						
						success: function (form, action) {
						   // Ext.MessageBox.alert('Message', 'Login OK');
						},
						failure:function(form, action) {
						//var result = Ext.decode(action.response.responseText); 
							
							if(action.response.responseText == '{success: false, errors:{Password:"Cannot contain special characters"} }') 
							{
							    Ext.MessageBox.alert('Message','<b>Password cannot contain special characters</b>');
							}
							else if(action.response.responseText == '{success: false, errors:{Email:"Invalid Email Account"} }')
							{
							    Ext.MessageBox.alert('Message','<b>Invalid Email Account.</b>');
							}
							else if(action.response.responseText == '{success: false, errors:{Email:"User account has not been activated. Please check your email."} }')
							{
								Ext.MessageBox.alert('Message','<b>Account not Activated. Please check your email for activation email.</b>');
							}
							else if(action.response.responseText == '{success:false,errors:{Email: "Invalid UserName / Password Combination"} }')
							{
								Ext.MessageBox.alert('Message','<b>Invalid Username / Password Combination</b>');
							}
							else if(action.response.responseText == '{success: false,errors:{Email: "Could not access customer database"} }')
							{
								Ext.MessageBox.alert('Message','<b>Could not access Database</b>');
							}
						}
             
					}); // END SUBMIT
					
				} // END ELSE STATEMENT
				
         }//END HANDLER FUNCTION
    });

	
	 // Define the customer registration button  and the  action required
		 
    var load = fs.addButton({
        text: 'Register',
        disabled:false,
        handler: function(){
            fs.form.load({ 
				url:'fake-form.php', // This is to satisft the ext-js code to prevent button issues
               		
				    //Should not enter this code, just re-direct back to main page
                    //Ext.MessageBox.alert('Message', 'Saved OK');
                failure:function(form, action) {
					//window.location = 'register-form.aspx'; //Re-Direct user to the registration process.
					window.location = 'https://www.boonsboropharmacy.com/register-form.php'; //Re-Direct user to the registration process.
                }
            });
         }
    });
	
    fs.render('login-form');

    fs.on({
        actioncomplete: function(form, action){
                            // Only enable the submit button if the load worked
      
            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.
						//document.write("Result " + action.response.responseText +'<br>');
                if(action.response.responseText == '') {
				//Ext.getCmp('login-box').setValue('');
                    //Ext.MessageBox.alert('Invalid User', 'Customer Not Found.');
					//Ext.MessageBox.alert('Invalid UserName/Password', 'Invalid UserName / Password Combination');
                } 
				else 
				{
				  window.location = 'http://www.boonsboropharmacy.com/'; //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") { 
					//document.write("FAILURE 2 " + '<br>');						
                    Ext.MessageBox.alert('Message', 'Login 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("actionfailed Result value: " + result +'<br>');
                        if(result && result.msg) {          
							//document.write("FAILURE 3 " + '<br>');						
                            Ext.MessageBox.alert('Message', 'Login Form submit failed with error: ' + action.result.msg);
                        } else {
						    //document.write("FAILURE 4 " + action.failureType +'<br>');
                            Ext.MessageBox.alert('Message', 'Login Form submit returned unknown error. Action type='+action.type+', failure type='+action.failureType);
                          }
                      }
            }   
        } // end actionfailed listener
    }); // end fs.on

});