/**
 * @author Harimandir
 */
// create KRI namespace
Ext.namespace('KRI');
Ext.apply(Ext.form.VTypes, {
    match: function(value, field){
        if (field.matchField) {
            var matchField = field.findParentByType('form').getForm().findField(field.matchField);
            this.matchText = 'Confirmation does not match the preceding field entry';
            return (value == matchField.getValue());
        }
        
        this.matchText = 'Confirmation field must match the preceding field';
        var hasSpecial = value.match(/[0-9!@#\$%\^&\*\(\)\-_=\+]+/i);
        //            var hasLength = (value.length >= 5);
        //            return (hasSpecial && hasLength);
        return hasSpecial;
    },
    matchText: 'Confirmation field must match the preceding field',
    
    
    url: function(val, field){
        try {
            var regex = new RegExp("^((ht|f)tp(s?)\\:\\/\\/|~/|/)?([\\w]+:\\w+@)?([a-zA-Z]{1}([\\w\\-]+\\.)+([\\w]{2,5}))(:[\\d]{1,5})?((/?\\w+/)+|/?)(\\w+\\.[\\w]{3,4})?((\\?\\w+=\\w+)?(&\\w+=\\w+)*)?");
            val = Ext.util.Format.trim(val);
            if (regex.test(val)) {
                field.setRawValue(val);
                return true;
            }
            return false;
        } 
        catch (e) {
            return false;
        }
    },
    urlText: 'Enter a valid Website URL',
    
    
    email: function(val, field){
        try {
            var regex = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z\-]){2,4}$/;
            val = Ext.util.Format.trim(val);
            if (regex.test(val)) {
                field.setRawValue(val);
                return true;
            }
            return false;
        } 
        catch (e) {
            return false;
        }
    }
});


// UTILITIES MODULE
KRI.util = function(){
    // do NOT access DOM from here; elements don't exist yet
    
    // PRIVATE VARIABLES
    var poppedUpLink;
    
    
    // PRIVATE FUNCTIONS
    
    
    // PUBLIC SPACE
    return {
        // PUBLIC PROPERTIES, e.g. strings to translate
        
        // PUBLIC METHODS
        popupLink: function(aObj, width, height){
            poppedUpLink = window.open(aObj.href, aObj.target ? aObj.target : 'popupLink', 'toolbar=no,location=no,directories=no,status=no,menubar=yes,scrollbars=yes,resizable=yes,copyhistory=yes,width=' + (width ? width : 640) + ',height=' + (height ? height : 480) + ',left=350,top=150,screenX=350,screenY=150');
            poppedUpLink.focus();
            return false;
        }
        
    };
}(); // end of util
// LICENSING MODULE
KRI.licensing = function(){
    // do NOT access DOM from here; elements don't exist yet
    
    // PRIVATE VARIABLES
    var dialog;
    var viewport;
    var formPanel;
    var alertWindow;
    var submitTimeoutTask;
    
    var SERVER_URL = 'http://' + document.domain;
    var DB_PATH = '/kri/kri.nsf';
    var GET_URL = DB_PATH + '/(ResponseHandlerAgent)?OpenAgent';
    var SUBMIT_URL = GET_URL; //GETDB_PATH + '/(RequestHandlerAgent)?OpenAgent';
    var PAYPAL_PROCESSED_URL = SERVER_URL + GET_URL;
    var PAYPAL_CANCEL_URL = 'http://www.kriteachings.org'; // SERVER_URL;
    var PAYPAL_RETURN_URL = 'http://www.kriteachings.org'; // SERVER_URL;
    // PRIVATE FUNCTIONS
    var LicenseRenewalRequest = {
        validationFailureMessages: [],
        
        selectedLicenseLevelIndex: null,
        
        xtype: 'form',
        id: 'license_renewal_request',
        
        autoHeight: true,
        autoWidth: true,
        border: false,
        
        requiredCheckboxIds: ['AgreeTermsOfLicensing'],
        
        defaults: {
            xtype: 'fieldset',
            labelWidth: 150, //200,
            autoHeight: true,
            autoWidth: true
        },
        
        items: [{
            xtype: 'panel',
            id: 'intro_panel',
            border: false,
            contentEl: 'license_renewal_intro'
        }, {
            title: 'License Renewal',
            id: 'start_panel',
            labelWidth: 125,
            
            defaults: {
                xtype: 'textfield',
                msgTarget: 'under'
            },
            
            items: [{
                xtype: 'box',
                autoEl: {
                    tag: 'div',
                    style: 'margin-bottom: 7px;',
                    html: '<strong>Enter your email address and the ID &#35; that was sent to that email address </strong><br/>then click \'Proceed\' to relicense and update your contact information on file'
                }
            }, {
                fieldLabel: 'Email',
                width: 250,
                id: 'LookupEmail',
                name: 'LookupEmail',
                vtype: 'email'
            }, {
                fieldLabel: 'ID #',
                width: 250,
                name: 'MemberID'
            }, {
                xtype: 'button',
                text: 'Proceed',
                style: 'margin-left: 130px; margin-bottom: 11px;',
                handler: function(button, event){
                    KRI.licensing.loadMatch();
                }
            }, {
                xtype: 'box',
                autoEl: {
                    tag: 'div',
                    style: 'margin-bottom: 7px;',
                    html: '<strong style="font-weight: bold;">Don\'t have your ID &#35; handy?</strong> <a href="javascript:KRI.licensing.showLicenseRenewalForm();">click here to enter your information manually and relicense now</a>'
                }
            }]
        }, {
            xtype: 'panel',
            id: 'info_panel',
            cls: 'x-hidden',
            //hidden: true,
            border: false,
            //hideBorders: true,
            
            items: [{
                title: 'Applicant Information',
                id: 'applicant_info',
                xtype: 'fieldset',
                //labelWidth: 200,
                autoWidth: true,
                autoHeight: true,
                
                defaults: {
                    xtype: 'textfield',
                    width: 250,
                    msgTarget: 'under'
                },
                
                items: [{
                    xtype: 'box',
                    autoEl: {
                        tag: 'div',
                        style: 'margin-bottom: 7px; font-weight: bold;',
                        html: 'Please type carefully'
                    }
                }, {
                    fieldLabel: 'Legal Name',
                    name: 'LegalFirstName',
                    allowBlank: false,
                    width: 110,
                    helpText: 'First',
                    append: [{
                        xtype: 'textfield',
                        width: 50,
                        helpText: 'Middle',
                        name: 'LegalMiddleName'
                    }, {
                        xtype: 'textfield',
                        width: 90,
                        helpText: 'Last',
                        name: 'LegalLastName',
                        allowBlank: false
                    }]
                }, {
                    fieldLabel: 'Spiritual Name',
                    name: 'SpiritualFirstName',
                    width: 110,
                    helpText: 'First',
                    append: [{
                        xtype: 'textfield',
                        width: 50,
                        helpText: 'Middle',
                        name: 'SpiritualMiddleName'
                    }, {
                        xtype: 'textfield',
                        width: 90,
                        helpText: 'Last',
                        name: 'SpiritualLastName'
                    }]
                }, {
                    fieldLabel: 'Date Of Birth',
                    name: 'DateOfBirth',
                    xtype: 'datefield',
                    //hideTrigger: true,
                    width: 108,
                    emptyText: 'mm/dd/yyyy',
                    invalidText: 'Enter a valid date in the format mm/dd/yyyy',
                    allowBlank: false,
                    maxValue: new Date(),
                    minValue: new Date('1/1/1868'),
                    format: 'm/d/Y',
                    altFormats: 'n/j/Y|m-d-Y|n-j-Y|n/j/y|m-d-y|n-j-y'
                }, {
                    xtype: 'textarea',
                    fieldLabel: 'Postal Address',
                    name: 'PostalAddress',
                    allowBlank: false,
                    height: 40
                }, {
                    fieldLabel: 'City',
                    name: 'City',
                    allowBlank: false
                }, {
                    fieldLabel: 'State or Province',
                    name: 'State'
                }, {
                    fieldLabel: 'Country',
                    name: 'Country',
                    allowBlank: false
                }, {
                    fieldLabel: 'Postal Code',
                    name: 'Zip'
                }, {
                    fieldLabel: 'Phone Number',
                    name: 'Phone',
                    allowBlank: false
                }, {
                    fieldLabel: 'Skype Address',
                    name: 'SkypeName'
                }, {
                    fieldLabel: 'Website',
                    name: 'Website',
                    vtype: 'url'
                }, {
                    fieldLabel: 'Email',
                    width: 250,
                    id: 'Email',
                    name: 'Email',
                    vtype: 'email',
                    allowBlank: false
                }, {
                    fieldLabel: 'Confirm Email',
                    name: 'EmailConfirm',
                    vtype: 'match',
                    allowBlank: false,
                    matchField: 'Email'
                }]
            
            }, {
                xtype: 'panel',
                bodyStyle: 'border-color: silver; padding: 7px 7px 0px 7px;',
                
                hideBorders: true,
                defaults: {
                    style: 'border-bottom: 1px solid silver; margin-bottom: 11px;'
                },
                
                items: [{
                    contentEl: 'applicant_license'
                }, {
                    contentEl: 'applicant_qualifications'
                }, {
                    xtype: 'fieldset',
                    autoHeight: true,
                    autoWidth: true,
                    
                    items: [{
                        xtype: 'box',
                        autoEl: {
                            tag: 'div',
                            style: 'margin-bottom: 7px;font-weight:bold;',
                            html: 'Trainer Directory'
                        }
                    }, {
                        xtype: 'box',
                        autoEl: {
                            tag: 'div',
                            style: 'margin-bottom: 7px;',
                            html: 'Some of the fields entered above will be included in the Trainers Directory: Legal Name, Spiritual Name, City, State, Country, Website, Email. We need a few more pieces of information from you<br><br><strong>Name Choice:</strong><br>Select which name you would like us to use on the trainer directory page of the website.'
                        }
                    }, {
                        xtype: 'radiogroup',
                        fieldLabel: 'Display Name',
						width: 700,
                        items: [{
                            xtype: 'radio',
                            inputValue: 'Legal',
                            boxLabel: 'Legal Name',
                            name: 'NameChoice'
                        }, {
                            xtype: 'radio',
                            inputValue: 'Spiritual',
                            boxLabel: 'Spiritual Name',
                            name: 'NameChoice'
                        }, {
                            xtype: 'radio',
                            inputValue: 'Both',
                            boxLabel: 'Both',
                            checked: true,
                            name: 'NameChoice'
                        }]
                    }, {
                        xtype: 'box',
                        autoEl: {
                            tag: 'div',
                            style: 'margin-bottom: 7px;',
                            html: '<strong>BIO:</strong><br>Tell us about who you are in 150 words or less. Include where you teach in the world, contact information for administrators and websites in those locations, languages you teach in, specialties etc.'
                        }
                    }, {
                        xtype: 'textarea',
                        hideLabel: true,
                        width: 600,
						height: 250,
                        name: 'TrainerBio',
                        validateValue: function(value){
                            var words = value.split(' ');
                            if (words.length > 150) {
                                Ext.fly('lrr-biowarning').dom.innerHTML = ' Your bio cannot be more than 150 words.';
                            }
                            else {
                                Ext.fly('lrr-biowarning').dom.innerHTML = '';
                            }
                            
                            Ext.getCmp('lrr-biowordcount').setValue(" " + words.length);
                            return true;
                        }
                    }, {
                        xtype: 'displayfield',
                        fieldLabel: 'Word Count',
                        name: 'BioWordCount',
                        id: 'lrr-biowordcount',
                        append: [{
                            xtype: 'box',
                            autoEl: {
                                tag: 'div',
                                id: 'lrr-biowarning',
                                style: 'margin-bottom: 7px;color:red;',
                                html: ''
                            }
                        }]
                    }]
                }, {
                    contentEl: 'applicant_reminders'
                }, {
                    contentEl: 'applicant_terms'
                }]
            }]
        }],
        
        buttons: [{
            text: 'Submit',
            hidden: true,
            id: 'submit_button',
            handler: function(){
                //try {
                Ext.getCmp('license_renewal_request').getForm().submit({
                    url: SUBMIT_URL,
                    
                    params: {
                        requestType: 'docsave',
                        form: 'License Renewal Request'
                    },
                    
                    success: function(me, action){
                        KRI.licensing.cancelTimeoutMsg();
                        
                        //try {
                        //Ext.get('content_panel').mask();
                        
                        var paypalItems = [' * Associates and Specialists: $54', ' * Associates and Specialists: $54', ' * Professionals and Leads: $108', ' * Professionals and Leads: $108', ' * Inactive Member: $22', ' * Late fee (submitted after June 30, 2009): $54'];
                        var payPalItemPrices = [54, 54, 108, 108, 22, 54];
                        
                        if (payPalItemPrices[me.selectedLicenseLevelIndex] > 0) {
                            var id = Ext.util.JSON.decode(action.response.responseText).id;
                            var fieldValues = me.getValues();
                            
                            Ext.Msg.alert('Success', 'Your license renewal application has been received. <br />&nbsp;<br /><strong>You must complete the payment process immediately for your license renewal request to be reviewed.</strong> We will notify you by email once your request has been reviewed and approved. <br />&nbsp; <br />Press OK to complete the payment process now. ', function(){
                                var redirectMask = new Ext.LoadMask(Ext.getBody(), {
                                    msg: "Please wait while you are redirected to the payment processor...",
                                    msgCls: 'x-mask-loading'
                                });
                                redirectMask.show();
                                
                                var paypalForm = Ext.get('payment_form').dom;
                                
                                paypalForm.item_name.value = 'KRI License Renewal Fee' + paypalItems[me.selectedLicenseLevelIndex];
                                paypalForm.amount.value = payPalItemPrices[me.selectedLicenseLevelIndex];
                                
                                // Copy contact details to the PayPal form
                                
                                var postalAddress = fieldValues.PostalAddress.split('\n');
                                if (postalAddress.length > 0) {
                                    paypalForm.address1.value = postalAddress[0];
                                }
                                else 
                                    if (postalAddress.length > 1) {
                                        paypalForm.address2.value = postalAddress[1];
                                    }
                                
                                paypalForm.first_name.value = fieldValues.LegalFirstName;
                                paypalForm.last_name.value = fieldValues.LegalLastName;
                                paypalForm.city.value = fieldValues.City;
                                paypalForm.state.value = fieldValues.State;
                                paypalForm.zip.value = fieldValues.Zip;
                                paypalForm.country.value = fieldValues.Country;
                                
                                paypalForm.email.value = fieldValues.Email;
                                paypalForm.custom.value = id;
                                
                                // Set Url values for Paypal form								
                                paypalForm.notify_url.value = PAYPAL_PROCESSED_URL;
                                paypalForm['return'].value = PAYPAL_RETURN_URL;
                                paypalForm.cancel_return.value = PAYPAL_CANCEL_URL;
                                
                                paypalForm.submit();
                            }, this);
                        }
                        else {
                            Ext.Msg.alert('Success', 'Your license renewal application has been received. <br />&nbsp;<br />We will notify you by email once your request has been reviewed and approved.', function(){
                                window.location.href = PAYPAL_RETURN_URL;
                            });
                        }
                        
                        //} 
                        //catch (e) {
                        //    Ext.Msg.alert('Submit', 'Error: ' + e.error + ' - ' + e.errorMessage);
                        //}
                    },
                    
                    failure: function(me, action){
                        KRI.licensing.cancelTimeoutMsg();
                        
                        if (action.failureType != 'client') {
                            Ext.Msg.alert('Submit', 'Error: ' + action.response.status + ' - ' + action.response.statusText + "<br>There was an error processing your request. <br>Please try again later, or call us at (001) 505-629-0899 to renew your license over the phone.");
                        }
                        else {
                            var msg = 'Before submitting your application: <br />&nbsp;<br />';
                            
                            for (var n = 0; n < me.validationFailureMessages.length; n++) {
                                msg += ' ' + (n + 1) + ') ' + me.validationFailureMessages[n] + ' <br />';
                            }
                            
                            Ext.Msg.alert('Submit', msg);
                            
                        }
                    },
                    
                    clientValidation: true
                });
                
                var waitDlg = Ext.MessageBox.wait('Sending...', 'Submit');
                var timeoutPeriod = Ext.Ajax.timeout;
                
                if (false === submitTimeoutTask instanceof Ext.util.DelayedTask) {
                    submitTimeoutTask = new Ext.util.DelayedTask(function(){
                        this.hide();
                        Ext.Msg.alert('Submit', 'The application timed out attempting to submit to the server<br />&nbsp; <br />Please try again, or contact us for help if the problem persists');
                    }, waitDlg);
                }
                
                submitTimeoutTask.delay(timeoutPeriod);
                
                //} 
                //catch (e) {
                //    Ext.Msg.alert('Submit', 'Error: ' + e.error + ' - ' + e.errorMessage);
                //}
            }
        }],
        
        
        isValid: function(){
            this.validationFailureMessages = [];
            this.selectedLicenseLevelIndex = null;
            
            if (Ext.form.BasicForm.prototype.isValid.call(this) === false) {
                this.validationFailureMessages[this.validationFailureMessages.length] = 'Enter required values for all highlighted fields on the document';
            }
            
            // Check for required KRI license level radio button selections
            var invalidLicenseLevel = true;
            var n;
            
            for (n = 0; n < Ext.getCmp('license_renewal_request').form.el.dom.LevelOneLicense.length; n++) {
                // check to make sure each required checkbox has been selected
                if (Ext.getCmp('license_renewal_request').form.el.dom.LevelOneLicense[n].checked === true) {
                    this.selectedLicenseLevelIndex = n;
                    invalidLicenseLevel = false;
                    break;
                }
            }
            if (invalidLicenseLevel === true) {
                this.validationFailureMessages[this.validationFailureMessages.length] = 'Select your current KRI license level';
            }
            else 
                if (Ext.getCmp('license_renewal_request').form.el.dom.InactiveMember.checked === true) {
                    this.selectedLicenseLevelIndex = 4;
                }
            
            // Check for required LevelTwoRequirementsMetToDate radio button selections
            var invalidL2RequirementsMet = true;
            for (n = 0; n < Ext.getCmp('license_renewal_request').form.el.dom.LevelTwoRequirementsMetToDate.length; n++) {
                // check to make sure each required checkbox has been selected
                if (Ext.getCmp('license_renewal_request').form.el.dom.LevelTwoRequirementsMetToDate[n].checked === true) {
                    this.selectedL2RequirementsMetIndex = n;
                    invalidL2RequirementsMet = false;
                    break;
                }
            }
            if (invalidL2RequirementsMet === true) {
                this.validationFailureMessages[this.validationFailureMessages.length] = 'Select the radio button indicating any Level Two certification requirements you have met to date';
            }
            
            // Check for required agreement checkbox selections
            var invalidAgreements = false;
            for (var i = 0; i < this.requiredCheckboxIds.length; i++) {
                // check to make sure each required checkbox has been selected
                if (!Ext.get(this.requiredCheckboxIds[i]).dom.checked) {
                    invalidAgreements = true;
                    this.markInvalid({
                        id: this.requiredCheckboxIds[i],
                        msg: 'Check here to agree'
                    });
                }
            }
            if (invalidAgreements === true) {
                this.validationFailureMessages[this.validationFailureMessages.length] = 'Check the box indicating your agreement to comply with Aquarian Trainer Academy terms of licensing';
            }
            
            // Check for required IKYTA membership verification checkbox selection
            // check to make sure each required checkbox has been selected
            var invalidMembership = false;
            if (!Ext.get('CurrentIKYTAMember').dom.checked) {
                this.invalidMembership = true;
                this.markInvalid({
                    id: this.requiredCheckboxIds[n],
                    msg: 'Check here to verify your active membership status'
                });
            }
            if (invalidMembership === true) {
                this.validationFailureMessages[this.validationFailureMessages.length] = 'Verify that you are currently a Professional Member of IKYTA or an international affilliate';
            }
            
            return (this.validationFailureMessages.length < 1);
        }
    };
    
    
    // PUBLIC SPACE
    return {
        // PUBLIC PROPERTIES, e.g. strings to translate
        
        // PUBLIC METHODS
        init: function(){
            // Set up the Ext environment
            Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
            Ext.QuickTips.init();
            
            // this extends timeout in case there is a lag in the response
            //Ext.Ajax = Ext.apply(Ext.Ajax, {
            //    timeout: 30000 * 4
            //});
            
            Date.y2kYear = new Date().getYear('y') - 100;
            
            LicenseRenewalRequest = Ext.apply(LicenseRenewalRequest, {
                renderTo: Ext.get('license_renewal_application_form')
            });
            
            formPanel = new Ext.form.FormPanel(LicenseRenewalRequest);
            // formPanel.render('license_renewal_application_form');
        },
        
        loadMatch: function(){
            var form = formPanel.getForm();
            if (Ext.isEmpty(form)) {
                form = this.ownerCt.findParentByType('form');
            }
            
            var memberid = form.findField('MemberID').getValue();
            var email = form.findField('LookupEmail').getValue();
            
            if (Ext.isEmpty(memberid) || Ext.isEmpty(email)) {
                alertWindow = Ext.Msg.show({
                    title: 'Proceed',
                    msg: 'Email and ID &#35; are both required to proceed. <br />&nbsp; <br />If you don\'t have that information available now, <a href="javascript:KRI.licensing.showLicenseRenewalForm();">you can click here to enter your information manually and relicense now</a> <br />&nbsp; <br />If you do have the required information available, please press OK and fill in the fields before you proceed',
                    buttons: Ext.Msg.OK
                });
                return;
            }
            
            var config = {
                url: GET_URL,
                params: {
                    requestType: 'getmemberinfo',
                    memberid: memberid,
                    email: email
                },
                callback: function(options, success, response){
                    var responseObj = Ext.decode(response.responseText);
                    
                    if (responseObj.success) {
                        //Return any response the server sends
                        if (typeof responseObj.reason == 'string') {
                            //Ext.ux.NotificationAlert(responseObj.reason, 'Success');
                        }
                    }
                    else {
                        if (responseObj.reason) {
                            Ext.MessageBox.alert('Failure', responseObj.reason);
                        }
                        if (responseObj.id && responseObj.id === 'Error') {
                            // should we alert the user with error info?
                            Ext.Msg.alert(responseObj.error, responseObj.errorMessage);
                        }
                        
                        return false;
                    }
                    
                    // populate field values accordingly, or whatever
                    var fieldList = ['LegalFirstName', 'LegalMiddleName', 'LegalLastName', 'SpiritualFirstName', 'SpiritualMiddleName', 'SpiritualLastName', 'DateOfBirth', 'PostalAddress', 'City', 'State', 'Country', 'Zip', 'Phone', 'SkypeAddress', 'Website', 'Email'];
                    
                    Ext.each(fieldList, function(item, index, allItems){
                        var field = form.findField(item);
                        if (Ext.type(field)) {
                            field.setValue(responseObj.data[item]);
                        }
                    }, this);
                    
                    KRI.licensing.showLicenseRenewalForm();
                },
                waitTitle: '',
                waitMsg: '',
                clientValidation: false,
                scope: this
            };
            
            Ext.Ajax.request(config);
        },
        
        
        cancelTimeoutMsg: function(){
            if (true === submitTimeoutTask instanceof Ext.util.DelayedTask) {
                submitTimeoutTask.cancel();
            }
        },
        
        
        showLicenseRenewalForm: function(){
            if (Ext.type(alertWindow)) {
                alertWindow.hide();
            }
            Ext.getCmp('start_panel').hide();
            //Ext.getCmp('info_panel').show();
            Ext.get('info_panel').removeClass('x-hidden');
            Ext.get('info_panel').removeClass('x-hide-display');
            Ext.getCmp('submit_button').show();
            window.scrollTo('top', 0);
        }
        
        
    };
}(); // end of licensing
// end of file
