/*
 * @category Java Script Module Pattern
 * @version $Rev$
 * @author Joel Bair <joelb@baseltd.biz>
 *
 */


// reference local blank image
Ext.BLANK_IMAGE_URL = '../extjs/resources/images/default/s.gif';

// create namespace
Ext.ns('captcha', 'emailform');

// create application
captcha.loader = function() {
    // do NOT access DOM from here; elements don't exist yet

    // private variables

        var defaultImageDomId = 'captcha_img';

    // private functions

    // public space
    return {
        // public properties, e.g. strings to translate
        // methods and varibles defined in here always preface w/ "this."

        // myvar: "true",

        // public methods
        init_captcha_img: function(imageDomId) {

            var mask = new Ext.LoadMask(Ext.get((imageDomId||defaultImageDomId)+'-area'), { removeMask: true });
            mask.show();

            Ext.Ajax.request({
                    url: '/comm/captchaimg',
                    success: function(o){
                        if(Ext.decode(o.responseText).success){
                            captcha.captcha_img_src = Ext.decode(o.responseText).captcha_img_src;
                            captcha.captcha_id = Ext.decode(o.responseText).captcha_id;
                            var img = Ext.get(imageDomId||defaultImageDomId);
                            img.on('load', function() {
                                mask.hide();
                            });
                            img.dom.src = captcha.captcha_img_src;
                            img.update();
                        }
                    },
                    failure: function(){
                        mask.hide();
                        Ext.MessageBox.alert('Error', 'Server connection broken.');
                    },
                    scope: this
            });
        }
    };

}();


// create application
emailform = function() {
    // do NOT access DOM from here; elements don't exist yet

    // Add some custom form validation methods.
    Ext.apply(Ext.form.VTypes, {
        formalname:  function(v) {
            return (/^[a-zA-Z\s\-\'\.]+$/).test(v);
        },
        formalnameText: 'Formal names only!',

        markup:  function(v) {
            if ((/<([a-zA-Z0-9]+).*>[\0\n\f\r\t\v\w\W\d\D\S\s]*<\/\1>/).test(v)) {
                return false;
            }
            if ((/<([a-zA-Z0-9]+).*>/).test(v)) {
                return false;
            }
            return true;
        },
        markupText: 'HTML formatting is not allowed!'
    });

    // private variables
    var textareatxt = "Hello, \n"+
        "\n"+
        "My name is Sue Somebody.  "+
        "I am interested in attending your service on May 4th, 2006.\n"+
        "\n"+
        "I have attended other similar services and enjoy meeting and getting to know "+
        "other like minded believers.\n"+
        "\nI look forward to hearing from your organization. \n\nThank You!";

    var emailfp = new Ext.FormPanel({
        id: 'mail_form',
        title: '<b>New Message...</b>',
        url: '/comm/sendmail',
        frame: true,
        shadow: false,
        bodyBorder:true,
        monitorValid:true,
        baseCls: 'emailform-panel',
        width: 440,
        height: 450,
        bodyStyle:'padding:5px 5px 0 0',
        autoWidth: true,
        items: [{
            xtype:'textfield',
            fieldLabel: 'Your Full Name',
            id: 'name-field',
            tabindex: 1,
            name: 'fullname',
            allowBlank:false,
            vtype:'formalname',
            emptyText: 'Joe Somebody',
            anchor:'100%'
        },{
            xtype:'textfield',
            fieldLabel: 'Email Address',
            id: 'email-field',
            tabindex: 2,
            name: 'emailaddress',
            allowBlank:false,
            vtype:'email',
            emptyText: 'JoeS@somedomain.com',
            anchor:'100%'
        },{
            xtype:'textarea',
            fieldLabel:'Message',
            id: 'message-field',
            tabindex: 3,
            name:'message',
            allowBlank:false,
            vtype: 'markup',
            height:200,
            anchor:'100%',
            emptyText: textareatxt
        },{
            xtype:'box',
            autoEl:{
                tag:'div',
                id: 'captcha_img-area',
                style:'margin: 10px 0px 10px 105px; width: 442px; border:1px solid #B5B8C8; background-color:#FFFFFF; text-align:center',
                children:[{
                    tag:'img',
                    id: 'captcha_img',
                    width: 335,
                    height: 60,
                    style: 'margin: 0px auto;',
                    waitMsgTarget: true,
                    src: '/images/captcha_null_img.png'
                }]
            }
        },{
            xtype:'textfield',
            id: 'captcha-field',
            fieldLabel: 'Validation Code',
            name: 'captcha[input]',
            allowBlank: false,
            tabindex: 4,
            anchor:'50%'
        }],
        buttons: [{
            text: 'Send Message',
            tooltip: 'Send this message now.',
            handler: function() { var fm = emailfp.getForm(); doSubmit(fm); }
        },{
            text: 'Cancel',
            tooltip: 'Clear everything and close this window.',
            handler: function() { emailwin.hide(); }
        },{
            text: 'New Validation Code',
            tooltip: 'Having trouble deciphering the Validation Code?  Generate a new one... ',
            handler: function() { captcha.loader.init_captcha_img(); }
        }]
    });

    var emailwin = new Ext.Window({
        id: 'email-form-win',
        title: 'Mail Compose',
        layout: 'fit',
        width: 600,
        height: 475,
        closeAction: 'hide',
        hidden: true,
        constrainHeader: true,
        items: emailfp
    });

    emailwin.on('beforehide', function(event, target, opts) {
        emailfp.getForm().reset();
    });

    var formParams = {};

    // private functions
    var doSubmit = function(form) {
        if(!form.isValid()) {
            form.markInvalid();
            return;
        }
        formParams['captcha[id]'] = captcha.captcha_id;
        form.submit({
            url:emailfp.url,
            params: formParams,
            success: function(form, action) {doSuccess(form, action);},
            failure: function(form, action) {doFailure(form, action);},
            waitMsg:'Sending eMail...'
        });
    };

    var doSuccess = function(form, action){
        emailwin.hide();
        utils.flashMessage('Complete...','You message has been sent...');
    };

    var doFailure = function(form, action){
        form.markInvalid(action.result.errors);
        utils.flashMessage('Error...', action.result.msg);
        captcha.loader.init_captcha_img();
    };


    // public space
    return {
        // public properties, e.g. strings to translate
        // methods and varibles defined in here always preface w/ "this."

        // myvar: "true",
        fpTitle: emailfp.title,

        // public methods
        init: function() {
            emailwin.render(Ext.getBody());
            var pageContent = Ext.get("contentframe").getUpdater();
            pageContent.on('update', function() {
                emailform.setup_button();
            });
        },

        setup_button: function() {
            var btns = Ext.query('div.email_btn');

            Ext.each(btns, function(itm, idx, arr) {
               var btn = Ext.get(itm.id);
               btn.on('click', function(event, target, opts) {
                    formParams.mailkey = this.id.replace("mail-target-", "");
                    var btxt = this.first().dom.innerHTML;
                    if(!btxt.match("eMail Us...")) {
                        var append = btxt.replace("eMail ", "&nbsp;&nbsp;&nbsp;&nbsp;<b><i>(To:&nbsp;");
                        append = append.replace("...",")</i></b>");
                        emailfp.setTitle(emailform.fpTitle+append);
                    }
                    emailform.render(target);
                });
            });
        },

        render: function(target,action) {
            emailwin.setAnimateTarget(target);
            emailwin.show();
            Ext.QuickTips.init();
            captcha.loader.init_captcha_img(); //default id
        }
    };
}();
