/**
 * Members register js
 * 
 * This file contains all the js code required on members/register page
 * This file mainly draws the registration form using extjs
 * @author Abbas Ali <abbas@sanisoft.com>
 * @version 1.0
 * @package kanari
 */
 
Ext.onReady(function() {    
    Ext.QuickTips.init();
    
    var fs;
    
    var terms_check_box;
    var submit_button;  
    
    // Now the default is to have it be a guest
    var isGuest = true;
    
    var memberInfoFieldset;   
    
    // From: http://www.mediacollege.com/internet/javascript/number/random.html
    var randomString = function(string_length) {
        var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";        
        var str = '';
        for (var i=0; i<string_length; i++) {
            var rnum = Math.floor(Math.random() * chars.length);
            str += chars.substring(rnum,rnum+1);
        }
        return str;
    }

    
    Ext.get('register_member').on('click', function() {               
        updateValuesForGuest();
    });
    
    var updateValuesForGuest = function() {
        var wasGuestBefore = isGuest;
        isGuest = Ext.get('register_guest').dom.checked;
        
        if (wasGuestBefore && !isGuest) {
            fs.getForm().suspendEvents();
            Ext.getCmp('first_name').setValue('');
            Ext.getCmp('last_name').setValue('');
            Ext.getCmp('password').setValue('');
            Ext.getCmp('confirm_password').setValue('');
            Ext.getCmp('email').setValue('');
            fs.getForm().resumeEvents();
            fs.getForm().clearInvalid();
        }
        
        memberInfoFieldset.setVisible(!isGuest);
        if (isGuest) {
            submit_button.setText('Log in as guest');
        } else {
        submit_button.setText('Register');
        }
    }
        
    
    Ext.get('register_guest').on('click', function() {               
        updateValuesForGuest();
    });
    
	// If cookies are not enabled then show the error message and return without doing anything
	if (true == js_vars.cookie_error)
	{
		Ext.get('register_cookie_error_message').show();
		return;
	}                       
        
    //add_message(messages.register_here, 'information');
   
    // turn on validation errors beside the field globally
    Ext.form.Field.prototype.msgTarget = 'side';      
    
	// Function to submit the form
	var submit_form = function() 
	{                   
        Ext.form.Field.prototype.clearInvalid.call(terms_check_box);
        if (!terms_check_box.checked) {            
            var msg = 'You must agree to the terms of service.';            
            terms_check_box.msgTarget = 'under';            
            Ext.form.Field.prototype.markInvalid.call(terms_check_box, msg);            
            return;
        }
    
        if (isGuest) {
            var randStr = randomString(6);
            Ext.getCmp('first_name').setValue('Guest');
            Ext.getCmp('last_name').setValue('User');
            Ext.getCmp('password').setValue(randStr);
            Ext.getCmp('confirm_password').setValue(randStr);
            Ext.getCmp('email').setValue('draff8660+wagmuguest_' + randStr + '@gmail.com');
        }
    
        // Check it twice, because in IE, there is an issue with the check box for agreeing to the terms not updating the validation state.
        if (fs.getForm().isValid()) {   
            add_message(messages.loading, 'information indicator');
            submit_button.disable();  
            
            //var vals = eval(uneval(fs.getForm().getValues()));
            var vals = fs.getForm().getValues();
            vals['pregnancy_status'] = (vals['female_options'] == 'pregnant' ? 1 : 0);
            vals['lactation_status'] = (vals['female_options'] == 'lactating' ? 1 : 0);            
            delete vals['female_options'];
        
            Ext.Ajax.request({
                url: base_url + 'members/register'
                , params: vals
                , success: function(response) {		
                    var response_data = decodeJsonCheckErr(response.responseText);                    
                    remove_indicator_messages();
                    
                    // It's possible that it should have more error handling logic here than it does, but this is a start.
                    if (!response_data.success) {
                        //add_message(response_data.errors[0].msg, 'caution');
                        fs.getForm().markInvalid(response_data.errors);
                        //add_message(response_data.errors[0].msg, 'caution indicator');   
                        
                        submit_button.enable();
                    } else {                                                            
                        if (isGuest) {
                            add_message(messages.register_success_guest, 'information indicator');   
                        } else {
                            add_message(messages.register_success_member, 'information indicator');   
                        }

                        Ext.get('auto_login_email_input').dom.value = fs.getForm().getValues().email;
                        Ext.get('auto_login_password_input').dom.value = fs.getForm().getValues().password;                				
                        Ext.get('auto_login_form').dom.submit();				                                                          
                        
                        // Reset the form
                        //fs.getForm().reset();
                        // Hide the form and show the success message in the page
                        //fs.hide();                        
                    }
                }
                , failure: function(response) {                
                     // If member creation failed then show the error in message panel
                     remove_indicator_messages();
                     add_message(messages.register_fail, 'error indicator');
                     submit_button.enable();
                }
            });
        } else {
            remove_indicator_messages();
        }
	}
	
	var dates = new Array();
	var months;
	var years;
	for (i = 1;i <=31; i++)
	{
		dates[i-1] = [i];
	}

	// Set up the requirement to check the user agreement.
    /*
    Ext.form.Checkbox.prototype.validate = function(){        
        if (this.validateField) {
            // other values as 'under' do not work
            this.msgTarget = 'under';
            if (this.checked) {
                Ext.form.Field.prototype.clearInvalid.call(this); // use implementation from Field as function is deactivated for Checkbox
                return true;
            }
            else {
                Ext.form.Field.prototype.markInvalid.call(this, this.validateMessage);  // use implementation from Field as function is deactivated for Checkbox
                return false;
            }
        }
        return true;
    };*/


	// Create a form panel
    
    submit_button = new Ext.Button({
        // Form submit button
        text: 'Register'
        , handler: submit_form
    });
    
    terms_check_box = new Ext.form.Checkbox({
        hideLabel: true
        , name: 'accept_terms'
        , boxLabel: 'I agree to the&nbsp;'
        //, validateMessage: messages.must_agree_to_terms
        //, validateField: true
        , change: function () {            
            Ext.form.Field.prototype.clearInvalid.call(terms_check_box);
        }
    });    
        
    var registerBoxWidth = Ext.get('register_box').getWidth();
    var controlsWidth = registerBoxWidth * 0.3;
    
    memberInfoFieldset = new Ext.form.FieldSet({
        title: 'Member information'
        , autoHeight: true
        , id: 'member_fieldset'
        , itemCls: 'left-align'
        , defaultType: 'textfield'        
        , items: [{
                fieldLabel: 'First Name'
                , id: 'first_name'
                , name: 'first_name'
                , width: controlsWidth
                , allowBlank: false
                , blankText: messages.empty_first_name
            }, {
                fieldLabel: 'Last Name'
                , id: 'last_name'
                , name: 'last_name'
                , width: controlsWidth
                , allowBlank: false
                , blankText: messages.empty_last_name
            }, {
                fieldLabel: 'Password'
                , id: 'password'
                , name: 'password'
                , inputType: 'password'
                , width: controlsWidth
                , allowBlank: false
                , blankText: messages.empty_password
            }, {
                fieldLabel: 'Confirm Password'
                , id: 'confirm_password'
                , name: 'confirm_password'
                , inputType: 'password'
                , width: controlsWidth
                , allowBlank: false
                , blankText: messages.empty_password
                // Function to validate confirm password field
                , validator: function(value) {
                    // Check if both password fields are equal or not. Return error if they are not.
                    if (fs.getForm().getValues().password == value)
                    {
                        return true;
                    }
                    
                    return messages.pw_match_error;
                }
            }, {
                fieldLabel: 'Email'
                , id: 'email'
                , name: 'email'
                , width: controlsWidth
                , allowBlank: false
                , blankText: messages.empty_email
                //, vtype:'email'
            }]
    });
    
    var birth_day_combo = new Ext.form.ComboBox({
        fieldLabel: 'Birthdate'
        , name:'birth_day'
        , store: new Ext.data.SimpleStore({
            data : get_dates()
            , fields: ['date']
        })
        , displayField: 'date'
        , valueField: 'date'
        , typeAhead: true
        , mode: 'local'
        , triggerAction: 'all'
        , selectOnFocus:true
        , width: 40
        , listWidth: 40
        , value: 4
    });
    
    var birth_month_combo = new Ext.form.ComboBox({
        hideLabel: true
        , hiddenName:'birth_month'
        , store: new Ext.data.SimpleStore({
            data : get_months()
            , fields: ['month', 'name']
        })
        , displayField: 'name'
        , valueField: 'month'
        , typeAhead: true
        , mode: 'local'
        , triggerAction: 'all'
        , selectOnFocus:true
        , width: 60
        , listWidth: 60
        , value: 7
    });
    
    var birth_year_combo = new Ext.form.ComboBox({
        hideLabel: true
        , name:'birth_year'
        , store: new Ext.data.SimpleStore({
            data : get_years()
            , fields: ['year']
        })
        , displayField: 'year'
        , valueField: 'year'
        , typeAhead: true
        , mode: 'local'
        , triggerAction: 'all'
        , selectOnFocus:true
        , width: 60
        , listWidth: 60
        , value: 1976
    });
    
    var showOrHideImperialPanel = function(el, status) {
        // If imperial is checked then show the imperial panel and hide the metric panel
        if (status)
        {					                                                                                                         
            if (isNaN(parseFloat(Ext.getCmp('weight_metric').getValue()))) {
                Ext.getCmp('weight_imperial').setValue('');
            } else {
                var weight_imperial_val = Math.round(parseFloat(
                    Ext.getCmp('weight_metric').getValue()) * POUNDS_PER_KG * 1000.0) / 1000.0;
                Ext.getCmp('weight_imperial').setValue(weight_imperial_val);
            }
                                                    
            if (isNaN(parseFloat(Ext.getCmp('height_metric').getValue()))) {
                Ext.getCmp('height_imperial_feet').setValue('');
                Ext.getCmp('height_imperial_inches').setValue('');
            } else {
                var totalInches = 
                    Math.round(parseFloat(Ext.getCmp('height_metric').getValue()) /
                    CMS_PER_INCH * 1000.0) / 1000.0;
                var inchesPart = Math.round((totalInches % 12) * 1000.0) / 1000.0;
                var feetPart = (totalInches - inchesPart) / 12;
                Ext.getCmp('height_imperial_feet').setValue(feetPart);
                Ext.getCmp('height_imperial_inches').setValue(inchesPart);
            }
                                  
            //CMS_PER_INCH;
            //Ext.getCmp('height_metric').getValue();
            //Ext.getCmp('height_imperial_feet').getValue();
            //Ext.getCmp('height_imperial_inches').getValue();
            
            fs.getComponent('personal_fieldset').getComponent('imperial_panel').show();
            fs.getComponent('personal_fieldset').getComponent('metric_panel').hide();
        }
        else
        {
            if (isNaN(parseFloat(Ext.getCmp('weight_imperial').getValue()))) {
                Ext.getCmp('weight_metric').setValue('');
            } else {
                var weight_metric_val = Math.round(parseFloat(
                    Ext.getCmp('weight_imperial').getValue()) / POUNDS_PER_KG * 1000.0) / 1000.0;
                Ext.getCmp('weight_metric').setValue(weight_metric_val);
            }
            
            if (isNaN(parseFloat(Ext.getCmp('height_imperial_feet').getValue()))
                || isNaN(parseFloat(Ext.getCmp('height_imperial_inches').getValue()))) {
                Ext.getCmp('height_metric').setValue('');
            } else {
                var totalInches = parseFloat(Ext.getCmp('height_imperial_feet').getValue()) * 12.
                    +  parseFloat(Ext.getCmp('height_imperial_inches').getValue());
                Ext.getCmp('height_metric').setValue(Math.round(totalInches * CMS_PER_INCH * 1000.0) / 1000.0);  
            }                                        
            
            // Else if metric is checked then show the metric panel and hide the imperial panel
            fs.getComponent('personal_fieldset').getComponent('imperial_panel').hide();
            fs.getComponent('personal_fieldset').getComponent('metric_panel').show();
        }
    };
    
    var nutrient_profile_fieldset = new Ext.form.FieldSet({
        title: 'Nutrient requirements information'
        , autoHeight: true
        , id: 'personal_fieldset'
        , itemCls: 'left-align'
        , defaultType: 'textfield'
        , items: [{
                layout:'column'
                , xtype: 'panel'
                , items:[{
                    //columnWidth:.5
                    layout: 'form'
                    , items: [birth_day_combo]
                }, {
                    //columnWidth:.2
                    layout: 'form', items: [birth_month_combo]
                }, {
                    //columnWidth:.2
                    layout: 'form'
                    , items: [birth_year_combo]
                }]
            },
            {
                fieldLabel: 'Gender'
                , name: 'gender'
                , xtype: 'ux-radiogroup'
                , horizontal: true
                , radios: [{
                    value: 'male'
                    , boxLabel: 'Male'
                    , checked: true
                } , {
                    value: 'female'
                    , boxLabel: 'Female'
                    , listeners: {
                        // Handler to show/hide the female options
                        check: function(el, status)
                        {
                            // If female is checked then show the female options else hide them
                            if (status)
                            {
                                fs.getComponent('personal_fieldset').getComponent('female_options').show();
                            }
                            else
                            {
                                fs.getComponent('personal_fieldset').getComponent('female_options').hide();
                            }
                        }
                    }
                }]
            }, {
                xtype: 'panel'
                , layout: 'form'
                , id: 'female_options'
                , items: [{
                    fieldLabel: 'Pregnant/Lactating'
                    , name: 'female_options'
                    , xtype: 'ux-radiogroup'
                    , horizontal: true
                    , radios: [
                    {
                        value: 'neither'
                        , boxLabel: 'Neither'
                        , checked: true
                    }
                    ,{
                        value: 'pregnant'
                        , boxLabel: 'Pregnant'
                    }                            
                    , {
                        value: 'lactating'
                        , boxLabel: 'Lactating'
                    }]
                }]
            }, {
                fieldLabel: 'Preferred Units'
                , name: 'units'
                , xtype: 'ux-radiogroup'
                , horizontal: true
                , radios: [{
                    value: 'metric'
                    , boxLabel: 'Metric'                    
                } , {
                    value: 'imperial'
                    , boxLabel: 'Imperial (US)'
                    , checked: true
                    , listeners: {
                        // Handler to show/hide the metric/imperial panel
                        check: showOrHideImperialPanel
                    }
                }]
            }, {
                xtype: 'panel'
                , layout: 'form'
                , id: 'metric_panel'
                , defaultType: 'textfield'
                , items: [{
                        fieldLabel: 'Height (cms)'
                        , id: 'height_metric'
                        , name: 'height_metric'
                        , width: 50
                    },{
                        fieldLabel: 'Weight (kgs)'
                        , id: 'weight_metric'
                        , name: 'weight_metric'
                        , width: 50
                    }
                ]
            }, {
                xtype: 'panel'
                , layout: 'form'
                , id: 'imperial_panel'
                , defaultType: 'textfield'
                , items: [{
                        layout:'column'
                        , xtype: 'panel'
                        , items:[{
                            width:220
                            , layout: 'form'
                            , items: [{
                                xtype:'textfield'
                                , fieldLabel: 'Height'
                                , id: 'height_imperial_feet'
                                , name: 'height_imperial_feet'
                                , value:  5
                                , width: 50
                                , emptyText: 'feet'
                            }]
                        },{
                            width:105
                            , layout: 'form'
                            , items: [{
                                xtype:'textfield'
                                , hideLabel: true
                                , id: 'height_imperial_inches'
                                , name: 'height_imperial_inches'
                                , value: 11
                                , width: 50
                                , emptyText: 'inches'
                                , validator: function(value) {
                                    // Inches should be less than 12
                                    if (12 > value)
                                    {
                                        return true;
                                    }
                                    
                                    return messages.inches_error;
                                }
                            }]
                        }]
                    },{
                        fieldLabel: 'Weight (lbs)'
                        , id: 'weight_imperial'
                        , name: 'weight_imperial'
                        , value: 190
                        , width: 50
                    }
                ]
            }
        ]
    });     
    
    var activity_level_fieldset = new Ext.form.FieldSet({
        title: 'What activity level matches your lifestyle?'
        , autoHeight: true
        , itemCls: 'left-align'
        , defaultType: 'textfield'
        , validateField: false
        , items: [{
                hideLabel: true
                , name: 'activity_level'
                , xtype: 'radio'
                , boxLabel: 'Sedentary'
                , inputValue: 'sedentary'                
                , validateField: false
            }, {
                hideLabel: true
                , name: 'activity_level'
                , xtype: 'radio'
                , boxLabel: 'Light Activity'
                , checked: true
                , inputValue: 'light'
                , validateField: false
            }, {
                hideLabel: true
                , name: 'activity_level'
                , xtype: 'radio'
                , boxLabel: 'Moderate Activity'
                , inputValue: 'moderate'
                , validateField: false
            }, {
                hideLabel: true
                , name: 'activity_level'
                , xtype: 'radio'
                , boxLabel: 'High Activity'
                , inputValue: 'high'
                , validateField: false
            }
        ]
    });
    
    fs = new Ext.FormPanel({
        frame: true
		// Title of the form
        //, title:'New member registration'
		, labelAlign: 'right'
		, labelWidth: 125		
		, width: registerBoxWidth * 0.95
		, waitMsgTarget: true
		// Form elements
        , items: [
            memberInfoFieldset
            ,
            nutrient_profile_fieldset
            , 
            activity_level_fieldset
            /*
            {xtype: 'panel'
            , layout:'column'             
            , items:[
                {columnWidth:0.55, items: [nutrient_profile_fieldset]}
                , {columnWidth:0.05, items: [{xtype:'panel', html:'&nbsp;'}]}
                , {columnWidth:0.4, items: [activity_level_fieldset]}
            ]}*/
			,
            {xtype:'panel', 
             html:
                '<div style="width:100%; padding-bottom: 2.5em; padding-left: 0px;" class="x-form-element">'
                +  '<div style="width:50%; float:left; padding-left:0px; margin-bottom: 0.5em;">'
                  + '<div id="terms_check_box_div" style="float:right;"></div>'
                + '</div>'
                + '<div style="width:50%; float:right; margin-bottom: 0.5em;">'
                  + '<div style="float:left;"><a target="_blank" href="../files/Wagmu_User_Agreement.htm">Wagmu User Agreement</a>.</div>'
                + '</div>'
                + '</div>'
             }
            
        ]
		, buttons: [submit_button]
    });	    
    
	// By default we will hide the female options (i.e. pregnant and lactating)
	Ext.getCmp('female_options').hide();
	// By default we will hide the imperial units panel (i.e. height in feet and weight in lbs)
	Ext.getCmp('metric_panel').hide();
	// Render the registration form        
	fs.render('register');
    
    Ext.get('height_imperial_feet').insertHtml('afterEnd', ' feet &nbsp;');
    Ext.get('height_imperial_inches').insertHtml('afterEnd', ' inches. &nbsp;');
    
    terms_check_box.render('terms_check_box_div');
        
    updateValuesForGuest();    
	
	// Bind the enter key to the form submit action
	var nav = new Ext.KeyNav
	(
		fs.getForm().getEl()
		, {
			// Handle the Enter key press
			enter: function(e)
			{
				// Submit the form
				submit_form();
			}
		}
	);

    Ext.get('register').setStyle('visibility', '');
    Ext.get('register_container').setStyle('height', 'auto');    
});
