var SUBMIT_HOTSPOT_FORM = function ()
{
    Ext.QuickTips.init();

    var returnObj = {};
    var submitForm;
    var submitFormHandler;

    // html elements.
    var moreInfoHtml            = {html : "<div style='height: 40px; padding-bottom: 4px;"+
                                           " margin-bottom: 4px; background-image: "+
                                           "url(/images/questionmark.gif); "+
                                           "background-position: 0px 20px; "+
                                           "background-repeat: no-repeat;'>&nbsp;</div>"};
    var reqHtml                 = {html : "<div style='height: 40px; padding-bottom: 4px; "+
                                            "margin-bottom: 4px; background-image: "+
                                            "url(/images/arrow_required_form_text.png); "+
                                            "background-position: 0px 20px; "+
                                            "background-repeat: no-repeat;'>&nbsp;</div>"};
    var nonReqHtml              = {html : "<div style='height: 40px; padding-bottom: 4px; "+
                                           "margin-bottom: 4px; '>&nbsp;</div>"};
    var nonReqHidden            = {html : "<div style='display:none;'></div>"};
    var accessPointDetailsHtml  = {html : "<div style='color: #999999; font-size: 14px; "+
                                          "padding-bottom: 4px; margin-bottom: 4px; " +
                                          "margin-top:24px;'>Access Point Details</div>"};
    var addressDetailsHtml      = {html : "<div style='color: #999999; font-size: 14px; "+
                                           "padding-bottom: 4px; margin-bottom: 4px; "+
                                           "margin-top:24px;'>Address Details</div>"};
    var contactInfoHtml         = {html : "<div style='color: #999999; font-size: 14px; "+
                                          "padding-bottom: 4px; margin-bottom: 4px; "+
                                          "margin-top:24px;'>Contact Information</div>"};
    var spacerHtml              = {html : "<div style='color: #999999; font-size: 14px; "+
                                          "padding-bottom: 4px; margin-bottom: 4px; "+
                                          "margin-top:24px;'>&nbsp;</div>"};
    var captchaImage            = '<img src="/captcha.php?width=235&height=90&chars=5" '+
                                  'width="235" height="90" style="border: 1px solid #666;'+
                                  ' margin-right: 15px;" />';
    var noErrMessage            = '<div class="form-no-error-msg"></div>';
    var errMessage              = '<a name="ER"></a><div class="form-error-msg">Errors were found in your '+
                                  'information. Please mouse over the tip icons '+
                                  '<img src="js/ext/resources/images/default/form/exclamation.gif"> for help.</div>';

    // data stores for the location type and access point
    //   comboBoxes
    simpleReader = new Ext.data.JsonReader(
    {
        totalProperty: 'total_records',
        root:          'record_set',
        id:            'id'
    },
    [{name: 'id', type:'int'}, 'name']);

    var astore = new Ext.data.Store({
        url:        '/ajax.php',
        baseParams: {func:'get_access_points', dumpcache: 1},
        reader:     simpleReader 
    });
    astore.load();
    
    var lstore = new Ext.data.Store({
        url:        '/ajax.php',
        baseParams: {func:'get_location_types'},
        reader:     simpleReader 
    });
    lstore.load();
    // end datastores

    var storeC = new Ext.data.SimpleStore(
    {
        fields: ['country'],
        data: Ext.jiwire.countries
    });


    var publicAccessCheck = function(v)
    {
        alert("checking public access");
        return (v.indexOf("@") < 0) ? false : true;
    };

    var validEmail = function(v)
    {
        return (v.indexOf("@") < 0) ? false : true;
    };

    var emailMatch = function(str_value)
    {
        return (str_value == submitForm.getForm().findField('email_address1').getValue());
    };

    var buildQuickTip = function()
    {
        var target = captchaDiv.getEl();

        new Ext.ToolTip(
        {
            target:     target,
            html:       'Click to refresh image',
            trackMouse: true
        });

        target.on('click', reloadCaptcha);
    };



    var buildHandlers = function()
    {
        reloadCaptcha = function()
        {
            var num      = Math.random();
            captchaImage = '<img src="/captcha.php?width=235&height=90&chars=5&num='+
                           num+'" width="235" height="90" style="border: 1px solid #666; '+ 
                           'margin-right: 15px;" />';

            captchaDiv.getEl().update(captchaImage, false, buildQuickTip);
        };
        
        showErrorMsg = function()
        {
            errorMsgDiv.getEl().update(errMessage,false)
        }

        clearErrorMsg = function()
        {
            errorMsgDiv.getEl().update(noErrMessage,false)
        }
         
        moveToErrorMsg = function()
        {
            window.location = window.location + "#ER";
        };

        submitFormHandler = function()
        {
            var theForm  = submitForm.getForm();     

            // This is the panel that's displayed when there's a successful form submit.
		    var success_html = '<div id="success-msg"><h1>Thanks for Sharing!</h1><p>We\'ve received your feedback and routed'+
				' it to the appropriate person on the<br/>JiWire team. As appropriate, a member of our team will respond within'+
				' one to<br/>three business days.</p></div>';
							   
            if (!theForm.isValid())
            {
                showErrorMsg();
                moveToErrorMsg();
                return false;
            }
            
            var processResponse = function(options, success, response)
            {
                if (!success)
                {
                    Ext.Msg.alert('Error', 'There was an error submitting the form.<br />'+
                                           'The server is unavailable.');
                    return false;
                }

                var data = Ext.decode(response.responseText);

                if (data.err_msg == 'bad_captacha')
                {
                    reloadCaptcha();
                    showErrorMsg();
                    moveToErrorMsg();
                    theForm.findField('security_code').markInvalid('Verification did not match.'+
                        ' Please enter the new verification text on left:');
                    submitForm.enable();
                }
                else
                {
                    theForm.reset();
                    submitForm.enable();
                    Ext.get('form-submit-hotspot').update(success_html);
                    return true;
                }
            };
            
            var form_vals = theForm.getValues();

            // Convert the checkbox from "on" / "off" to 1 and 0 respectively
            if (form_vals.public_access_check == "on")
                form_vals.public_access_check = 1;
            else
                form_vals.public_access_check = 0;

            // Create the submit structure that will make
            //  a json object out of the form values 
            //  pass it to ajax.php
            var submitParams = { values: Ext.encode(form_vals) };

            submitForm.disable();

            Ext.Ajax.request(
            {
                url:        '/email.php',
                params:     submitParams,
                callback:   processResponse
            });
 
        }

    } 

    var buildForm = function()
    {
        var  hiddenRefererField = new Ext.form.Hidden(
        {
            name: 'referer',
            value: 'JiWire'
        });
        var  hiddenFeeField = new Ext.form.Hidden(
        {
            name: 'public_access',
            value: 'free'
        });
        var  hiddenIdField = new Ext.form.Hidden(
        {
            name: 'page_id',
            value: 'SH'
        });

        var imgButtonTpl = new Ext.Template(
            '<table border="0" cellpadding="0" cellspacing="0" width="59"><tbody><tr>' +
            '<td align="left"><button type="button"><img src="{0}"></button></td>' +
            '</tr></tbody></table>');

        var submitBtn = new Ext.Button(
        {
            template:imgButtonTpl,
            text: '/images/btn_submit_hotspot.png',
            handler: submitFormHandler
        });

        var locationName = new Ext.form.TextField(
        {
            fieldLabel:      'Location Name',
            name:            'location_name',
            allowBlank:      false,
            validateOnBlur:  false,
            validationEvent: 'submit', 
            width:           250
        });
        var countryCB = new Ext.form.ComboBox(
        {
            fieldLabel:      'Country',
            hiddenName:      'country',
            valueField:      'country',
            store:           storeC,
            displayField:    'country',
            typeAhead:       true,
            minChars:        1,
            mode:            'local',
            triggerAction:   'all',
            emptyText:       'Select Country',
            selectOnFocus:   true,
            forceSelection:  true,
            allowBlank:      false,
            validateOnBlur:  false,
            validationEvent: 'submit',
            width:          250
        })

        var locationType = new Ext.form.ComboBox({
            fieldLabel:      'Location Type',
            hiddenName:      'location_type',
            valueField:      'id',
            store:           lstore,
            displayField:    'name',
            typeAhead:       true,
            minChars:        1,
            mode:            'local',
            triggerAction:   'all',
            emptyText:       'Select location type',
            selectOnFocus:   true,
            forceSelection:  true,
            allowBlank:      false,
            validateOnBlur:  false,
            validationEvent: 'submit',
            width:           250
        });
        var publicAccess = new Ext.form.Checkbox({
            fieldLabel:      'Public Access',
            boxLabel:        'This location is a publicly-accessible' +
                             ' place (not a residence).',
            name:            'public_access_check',
            validator:       publicAccessCheck,
                             invalidText: 'This location must be publicly-accessible.',
            validateOnBlur:  false,
            validationEvent: 'submit',
            width:           250
        });
        var phoneNumber = new Ext.form.TextField(
        {
            fieldLabel: 'Phone Number',
            name:       'phone_number',
            width:      250
        });
        var webSite = new Ext.form.TextField(
        {
            fieldLabel: 'Web Site',
            name:       'web_site',
            width:      250
        });
        var accessPoint = new Ext.form.ComboBox({
            fieldLabel:    'Access Point Model',
            hiddenName:    'access_point_model',
            valueField:     'id',
            store:          astore,
            displayField:   'name',
            typeAhead:      true,
            minChars:       1,
            mode:           'local',
            triggerAction:  'all',
            emptyText:      'Select model',
            selectOnFocus:  true,
            forceSelection: true,
            width:          250
        });
        var ssid = new Ext.form.TextField(
        {
            fieldLabel: 'Access Point SSID',
            name:       'access_point_ssid',
            width:      250
        });
        var streetAddress1 = new Ext.form.TextField(
        {
            fieldLabel:      'Street Address 1',
            name:            'street_address_1',
            allowBlank:      false,
            validateOnBlur:  false,
            validationEvent: 'submit',
            width:           250
        });
        var streetAddress2 = new Ext.form.TextField(
        {
            fieldLabel: 'Street Address 2',
            name:       'street_address_2',
            width:      250
        });
        var city = new Ext.form.TextField(
        {
            fieldLabel:      'City',
            name:            'city',
            allowBlank:      false,
            validateOnBlur:  false,
            validationEvent: 'submit',
            width:           250
        });
        var region = new Ext.form.TextField(
        {
            fieldLabel:      'State or Region',
            name:            'region',
            allowBlank:      false,
            validateOnBlur:  false,
            validationEvent: 'submit',
            width:           250
        });
        var postalCode = new Ext.form.TextField(
        {
            fieldLabel:      'ZIP or Postal Code',
            name:            'postal_code',
            allowBlank:      false,
            validateOnBlur:  false,
            validationEvent: 'submit',
            width:           250
        });

        var email1 = new Ext.form.TextField(
        {
            fieldLabel:      'Email Address',
            name:            'email_address1',
            validator:       validEmail,
            validateOnBlur:  false,
            validationEvent: 'submit',
            width:           250
        });

        var email2 = new Ext.form.TextField(
        {
            fieldLabel:      'Re-type Email Address',
            name:            'email_address2',
            validator:       emailMatch,
                             invalidText: 'Email addresses do not match',
            validateOnBlur:  false,
            validationEvent: 'submit',
            width:           250
        });
        var captchaValidation = new Ext.form.TextField(
        {
            fieldLabel:      'Validation Text',
            name:            'security_code',
            allowBlank:      false,
            validateOnBlur:  false,
            validationEvent: 'submit',
            width:           220
        });
        var captchaText = new Ext.form.Label({
               text: 'To submit your hotspot, type the characters exactly as they appear in the '+
                     'box on the left, then click the Submit Hotspot button. Thanks for sharing!',
               id:   'captchaText'
        });
        var footerText = new Ext.form.Label({
            html : 'Information submitted through this form is subject to JiWire\'s '+
                   '<a href="/privacy">Privacy Policy</a> and <a href="/terms">Terms of Use</a>',
            id:    'formFooterText'
        });

        errorMsgDiv = new Ext.Panel(
        {
            plain:      true,
            border:     false,
            bodyBorder: false,
            html:       noErrMessage
        });


        captchaDiv = new Ext.Panel(
        {
            plain:      true,
            border:     false,
            bodyBorder: false,
            html:       captchaImage,
            listeners:  {'render': buildQuickTip}
        });
 

        submitForm = new Ext.form.FormPanel({
            labelAlign:  'top',
            url:         'submit-hotspot.php',
            title:       'Submit a Free-Access Wi-Fi Hotspot Location',
            bodyStyle:   'padding:0px 15px 15px 15px',
            labelWidth:  100,
            width:       590,
            layout:      'table',
            frame:       'true',
            defaults:    { plain: true, border:false, bodyBorder:false },
            layoutConfig:{ columns:2 },
          
            items:
             [
                {
                    colspan:  2,
                    layout:   'column',
                    width:    590,
                    items:    [errorMsgDiv]
                },{
                    layout:   'form',
                    width:    270,
                    defaults: {msgTarget:'side',invalidClass:'frame-error'},
                    items:    [locationName]
                },{
                    layout: 'form',
                    items: [reqHtml],
                    width: 300
                },{
                    layout:   'form',
                    width:    270,
                    defaults: {msgTarget:'side',invalidClass:'frame-error'},
                    items:    [locationType]
                },{
                    layout: 'form',
                    items: [reqHtml],
                    width: 300
                },{
                    layout:   'form',
                    width:    270,
                    defaults: {msgTarget:'side',invalidClass:'frame-error'},
                    items:    [publicAccess]
                },{
                    layout: 'form',
                    items: [reqHtml],
                    width: 300
                },{
                    layout:   'form',
                    width:    270,
                    defaults: {msgTarget:'side',invalidClass:'frame-error'},
                    items:    [phoneNumber]
                },{
                    layout: 'form',
                    items: [nonReqHtml],
                    width: 300
                },{
                    layout:   'form',
                    width:    270,
                    defaults: {msgTarget:'side',invalidClass:'frame-error'},
                    items:    [webSite]
                },{
                    layout: 'form',
                    items: [nonReqHtml],
                    width: 300
                },{
                    colspan:  2,
                    layout:   'column',
                    width:    590,
                    items:    [accessPointDetailsHtml]
                },{
                    layout:   'form',
                    width:    270,
                    defaults: {msgTarget:'side',invalidClass:'frame-error'},
                    items:    [accessPoint]
                },{
                    layout: 'form',
                    items: [nonReqHtml],
                    width: 300
                },{
                    layout:   'form',
                    width:    270,
                    defaults: {msgTarget:'side',invalidClass:'frame-error'},
                    items:    [ssid]
                },{
                    layout: 'form',
                    items: [nonReqHtml],
                    width: 300
                },{
                    colspan:  2,
                    layout:   'column',
                    width:    590,
                    items:    [addressDetailsHtml]
                },{
                    layout:   'form',
                    width:    270,
                    defaults: {msgTarget:'side',invalidClass:'frame-error'},
                    items:    [streetAddress1]
                },{
                    layout: 'form',
                    items: [reqHtml],
                    width: 300
                },{
                    layout:   'form',
                    width:    270,
                    defaults: {msgTarget:'side',invalidClass:'frame-error'},
                    items:    [streetAddress2]
                },{
                    layout: 'form',
                    items: [nonReqHtml],
                    width: 300
                },{
                    layout:   'form',
                    width:    270,
                    defaults: {msgTarget:'side',invalidClass:'frame-error'},
                    items:    [city]
                },{
                    layout: 'form',
                    items: [reqHtml],
                    width: 300
                },{
                    layout:   'form',
                    width:    270,
                    defaults: {msgTarget:'side',invalidClass:'frame-error'},
                    items:    [region]
                },{
                    layout: 'form',
                    items: [reqHtml],
                    width: 300
                },{
                    layout:   'form',
                    width:    270,
                    defaults: {msgTarget:'side',invalidClass:'frame-error'},
                    items:    [postalCode]
                },{
                    layout: 'form',
                    items: [reqHtml],
                    width: 300
                },{
                    layout:   'form',
                    width:    270,
                    defaults: {msgTarget:'side',invalidClass:'frame-error'},
                    items:    [countryCB]
                },{
                    layout: 'form',
                    items: [reqHtml],
                    width: 300
                },{
                    colspan:  2,
                    layout:   'column',
                    width:    590,
                    items:    [contactInfoHtml]
                },{
                    layout:   'form',
                    width:    270,
                    defaults: {msgTarget:'side',invalidClass:'frame-error'},
                    items:    [email1]
                },{
                    layout: 'form',
                    items: [nonReqHtml],
                    width: 300
                },{
                    layout:   'form',
                    width:    270,
                    defaults: {msgTarget:'side',invalidClass:'frame-error'},
                    items:    [email2]
                },{
                    layout: 'form',
                    items: [nonReqHtml],
                    width: 300
                },{
                    colspan:  2,
                    layout:   'column',
                    width:    590,
                    items:    [spacerHtml]
                },{                              
                    rowspan: 2,
                    items: [captchaDiv]
                },{
                    items: [captchaText]
                },{
                    layout: 'form',
                    defaults: {msgTarget:'side',invalidClass:'frame-error'},
                    items: [captchaValidation,hiddenIdField,hiddenFeeField,hiddenRefererField]
                },{
                    colspan:2,
                    layout: 'form',
                    items: [{
                        layout: 'form', 
                        buttonAlign: 'left', 
                        buttons: [submitBtn]
                    }]
                },{
                    colspan:2,
                    layout: 'form',
                    items: [footerText]
                }
               
            ]
        }); 
        submitForm.render('form-submit-hotspot');
    }

    var initFunction = function()
    {
        buildHandlers();
        buildForm();
    }
    
    returnObj.init = initFunction;
    return returnObj;
}

Ext.onReady(
    function()
    {
        var jw_submit_hotspot_form = new SUBMIT_HOTSPOT_FORM();
        jw_submit_hotspot_form.init();
    }
);
