/*
 * @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


    // 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() {

            var mask = new Ext.LoadMask(Ext.get('captcha-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('captcha_img');
                            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

    // private variables
    var textareatxt = "Hello, \n"
    +"\n"
    +"My name is Joe Somebody with SomeBigCo.com\n"
    +"I am interested in a price quote for staging on May 4th, 2006.\n"
    +"\n"
    +"Please call me at you earliest convenience to discuss the details.\n"
    +"\n"
    +"office: 555-555-5555 ext. 123\n"
    +"cell: 555-555-5551\n"
    +"\nThank You";

    var ctform;

    var ctform_cfg = {
        id: 'mail_form',
        title: '<b>New Message...</b>',
        url: '/comm/sendmail',
        frame: true,
        shadow: false,
        bodyBorder:false,
        monitorValid:true,
        baseCls: 'emailform-panel',
        width: 440,
        height: 470,
        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:'95%'
        },{
            xtype:'textfield',
            fieldLabel: 'Email Address',
            id: 'email-field',
            tabindex: 2,
            name: 'emailaddress',
            allowBlank:false,
            vtype:'email',
            emptyText: 'JoeS@somedomain.com',
            anchor:'95%'
        },{
            xtype:'textarea',
            fieldLabel:'Message',
            id: 'message-field',
            tabindex: 3,
            name:'message',
            allowBlank:false,
            vtype: 'markup',
            height:200,
            anchor:'95%',
            emptyText: textareatxt
        },{
            xtype:'box',
            autoEl:{
                tag:'div', id: 'captcha-area', style:'position:relative; left:105px; width:340px; clear:both; padding:8px 0px', children:[{
                    tag:'div',
                    html:'Verification Code'
                },{
                    tag:'img',
                    id: 'captcha_img',
                    width: 335,
                    height: 60,
                    waitMsgTarget: true,
                    src: '/images/captcha_null_img.png'
                },{
                    tag:'div',
                    style:'margin:12px 0 0 0; color: red; ',
                    html:'<i>(enter the code from the image above)</i>'
                }]
            }
        },{
            xtype:'textfield',
            id: 'captcha-field',
            hideLabel: true,
            tabindex: 4,
            style: 'position:relative; left:105px;',
            name: 'captcha[input]'
        }],

        buttons: [{
            text: 'Send Message',
            formBind:true,
            handler: function() { submitfm(); }
        },{
            text: 'Re-generate Verification Code',
            handler: function() { captcha.loader.init_captcha_img(); }
        }]
    };

    // private functions
    var submitfm = function() {
            ctform.getForm().submit({
                url:ctform.url,
                params:{ 'captcha[id]': captcha.captcha_id },
                success: function() {doSuccess();},
                failure: function() {doFailure();},
                waitMsg:'Sending Mail...'
            });
        };

        var doSuccess = function(){
            utils.flashMessage('Complete...','You message has been sent...');

            myPage.name = 'contact';
            redirect.defer(2000);
        };

        var redirect = function() {
            myPage.name = 'contact';
            content.load();
        };

        var doFailure = function(){
            Ext.Msg.show({
                title: 'Sorry...',
                msg: 'You must enter a valid code.  Please try again.',
                modal: true,
                buttons: Ext.Msg.OK,
                fn: function() {
                    captcha.loader.init_captcha_img();
                    var captchaFld = Ext.getCmp('mail_form').getComponent('captcha-field');
                    captchaFld.reset();
                    captchaFld.markInvalid('You must enter the code exactly as it appears above!!!');
                },
                icon: Ext.MessageBox.ERROR
            });
        };

    // 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: function() {
            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;
                    else if (/<([a-zA-Z0-9]+).*>/.test(v))
                        return false;
                    else
                        return true;
                },
                markupText: 'HTML formatting is not allowed!'
            });
        },

        render: function() {
            var cnt = Ext.get("email_form");
            Ext.QuickTips.init();
            // turn on validation errors beside the field globally
            Ext.form.Field.prototype.msgTarget = 'side';
            ctform = new Ext.FormPanel(ctform_cfg);
            ctform.render(cnt);
            captcha.loader.init_captcha_img();
        }
    };
}();

