var CONTACT_US_FORM = function()
{
    Ext.QuickTips.init();
        
    var returnObj = {};
    var contactUsForm;
    var submitFormHandler;
    var captchaDiv;
    var reloadCaptcha;
    
    var req_html = 
    {
        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;&nbsp;&nbsp;&nbsp;</div>"
    };
	var req_html_TA = 
    {
        html: "<div style='height: 100px; ; padding-bottom: 4px; margin-bottom: 4px; background-image: "+
              "url(/images/arrow_required_form_text.png); background-position: 0px 12px; background-repeat: " +
			  "no-repeat;'>&nbsp;&nbsp;&nbsp;&nbsp;</div>"
    };	
	var more_info_html = 
	{
		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 non_req_html   = {
		html: "<div style='height: 40px; padding-bottom: 4px; margin-bottom: 4px; '>&nbsp;</div>"
	};
    var non_req_hidden = {
		html: "<div style='display:none;'></div>"
	};
    var captchaImage   = '<img src="/captcha.php?width=248&height=70&chars=6" height="70" width="248" style="border:'+
	'1px solid #666"  />';
	var submitImage   = '<img src="/images/btn_contact_us.png" height="60" width="201"/>';
    var noErrMessage   = '<div class="form-no-error-msg"></div>';
    var errMessage     = '<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.png"> for help.<a name="ER">&nbsp;'+
		'</a></div>';
    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>';
	var storeC = new Ext.data.SimpleStore(
    {
        fields: ['country'],
        data: Ext.jiwire.countries
    });

    var validEmail = function(v)
    {
        return (v.indexOf("@") < 0) ? false : true;
    };
    
    var emailMatch = function(str_value)
    {
        return (str_value == contactUsForm.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=248&height=70&chars=6&num='+num+'" height="70" width="248" '+
			' style="border: 1px solid #666" />';
            
            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";
		};
		moveToTop = function()
		{
			window.location = window.location + "#TOP";
		};
        // handle the submit button request.
        submitFormHandler = function()
        {
            var theForm = contactUsForm.getForm();
            
            // This is the panel that's displayed when there's a successful form submit.

            
            // before submitting the form to the server, make sure the data
            // entered by the user is valid.
            if (!theForm.isValid()) 
            {	
				showErrorMsg();
				moveToErrorMsg();
                return false;
            }
            
            // Process the ajax response.  This will contain success or failure information
            // that we can use to display a status of the create_simple or update_simple requests
            // for adding or updating records in the database.
            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();
					contactUsForm.getForm().findField('security_code').markInvalid('Verification did not match.'+
					' Please enter the new verification text on left.');
					moveToErrorMsg();
					contactUsForm.enable();				
				}
                else
                {				
	                contactUsForm.getForm().reset();
	                contactUsForm.enable();
	                Ext.get('contact_us_form').update(success_html);
					moveToTop();
	                return true;
				}                
            };
            
            var form_vals    = theForm.getValues();
            var submitParams = {values: Ext.encode(form_vals)};
            
            contactUsForm.disable();
            
            Ext.Ajax.request(
            {
                url:        '/email.php',
                params:     submitParams,
                callback:   processResponse
            });
        };
    };
    
    var buildForm = function()
    {	
		var imgButtonTpl = new Ext.Template(
        '<table border="0" cellpadding="0" cellspacing="0" ><tbody><tr>' +
        '<td align="left"><button type="button"><img src="{0}"></button></td>' +
        '</tr></tbody></table>');

        var submitBtn = new Ext.Action(
        {
            text: 'Submit Message',
            handler: submitFormHandler
        });
		var submitBtn2 = new Ext.Button(
		{
			template:imgButtonTpl,
	        text: '/images/btn_submit_message.png',
			handler: submitFormHandler
		});		        
        var firstNameField = new Ext.form.TextField(
        {
            fieldLabel: 'First Name',
            name: 'first_name',
            allowBlank: false,
			autoCreate : {tag: 'input', type: 'text', maxlength: '64', autocomplete: 'off'},
            width: 250
        });
        
        var lastNameField = new Ext.form.TextField(
        {
            fieldLabel: 'Last Name',
            name: 'last_name',
            allowBlank: true,
			autoCreate : {tag: 'input', type: 'text', maxlength: '64', autocomplete: 'off'},
            width: 250
        });
        
        var titleField = new Ext.form.TextField(
        {
            fieldLabel: 'Title',
            name: 'title',
            allowBlank: true,
			autoCreate : {tag: 'input', type: 'text', maxlength: '64', autocomplete: 'off'},
            width: 250
        });
        
        var companyField = new Ext.form.TextField(
        {
            fieldLabel: 'Company',
            name: 'company',
            allowBlank: true,
			autoCreate : {tag: 'input', type: 'text', maxlength: '64', autocomplete: 'off'},
            width: 250
        });
        
        var websiteField = new Ext.form.TextField(
        {
            fieldLabel: 'Web Site',
            name: 'website',
			emptyText:	'http:\/\/',
            allowBlank: true,
			autoCreate : {tag: 'input', type: 'text', maxlength: '128', autocomplete: 'off'},
            width: 250
        });
        
        var phoneField = new Ext.form.TextField(
        {
            fieldLabel: 'Phone Number',
            name: 'phone_main',
            allowBlank: true,
			autoCreate : {tag: 'input', type: 'text', maxlength: '32', autocomplete: 'off'},
            width: 250
        });
        
        var emailField1 = new Ext.form.TextField(
        {
            fieldLabel: 'Email Address',
            name: 'email_address1',
            allowBlank: false,
            validator: validEmail,
            validationDelay: 750,
			autoCreate : {tag: 'input', type: 'text', maxlength: '64', autocomplete: 'off'},
            width: 250
        });
        
        var emailField2 = new Ext.form.TextField(
        {
            fieldLabel: 'Re-type Email Address',
            name: 'email_address2',
            allowBlank: false,
            validator: emailMatch,
			invalidText: 'Email addresses do not match',
            validationDelay: 750,
			autoCreate : {tag: 'input', type: 'text', maxlength: '64', autocomplete: 'off'},
            width: 250
        });
        
        var countryCB = new Ext.form.ComboBox(
        {
            fieldLabel: 'Country',
            store: storeC,
			name: 'country',
            displayField: 'country',
            valueField: 'country',
            minChars: 1,
            typeAhead: true,
            mode: 'local',
            forceSelection: true,
            triggerAction: 'all',
            emptyText: '-Select Country-',
            selectOnFocus: true,
            width: 250
        });
        
        var regionField = new Ext.form.TextField(
        {
            fieldLabel: 'State or Region',
            name: 'region',
            allowBlank: true,
			autoCreate : {tag: 'input', type: 'text', maxlength: '64', autocomplete: 'off'},
            width: 250
        });
        
        var messageTA = new Ext.form.TextArea(
        {
            id: 'message',
            height: 100,
            fieldLabel: 'Enter Your Message Below',
            width: 250,
			maxLength : 1000,
            allowBlank: false
        });
        
        var captchaText = new Ext.form.Label(
        {
			html : "<div style=' "+
              	"padding-bottom: 2px; margin-bottom: 2px; "+
             	"padding-top: 4px; margin-top: 4px; '>To vailidate your submission, please type the characters<br>"+
				"exactly as they appear in the box on the left.</div>",
            id: 'captchaText',
			cls: 'left mb-5'
        });
        
        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: 'footerText'
        });
        
        var captchaField = new Ext.form.TextField(
        {
            fieldLabel: 'Validation Text',
            name: 'security_code',
            allowBlank: false,
			autoCreate : {tag: 'input', type: 'text', maxlength: '12', autocomplete: 'off'},
			invalidText: 'Verification did not match. Please enter the new verification text on left\:',
            width: 150
        });
		
		hiddenIdField = new Ext.form.Hidden(
        {
            name: 'page_id',
			value: '18'
        });
        
		errorMsgDiv = new Ext.Panel(
        {
            plain: true,
            border: false,
            bodyBorder: false,
            html: noErrMessage
        });
		
	 	successMsgDiv = new Ext.Panel(
        {
            plain: true,
            border: false,
            bodyBorder: false,
            html: success_html
        });
		
        captchaDiv = new Ext.Panel(
        {
            plain: true,
            border: false,
            bodyBorder: false,
            cls: 'left mr-20',
            html: captchaImage,
            listeners: {'render': buildQuickTip}
        });
		submitDiv = new Ext.Panel(
        {
            plain: true,
            border: false,
            bodyBorder: false,
            cls: 'left mr-20',
            html: submitImage,
            handler: submitFormHandler
        });
        
        contactUsForm = new Ext.form.FormPanel(
        {
            labelAlign: 'top',
            id: 		'contact_us_form_ext',
            url:        '/email.php',
            title: 		'How Can We Help You?',
            bodyStyle: 	'padding: 0 15px 15px 15px;',
            labelWidth: 	100,
			layout: 	'table',
            frame: 		true,
            width: 		590,
			defaults:	{plain: true,border:false,bodyBorder:false},
			layoutConfig:{
				columns:2
			},
			items: [{//col1
				colspan:2,
				layout: 'column',
				width: 590,											         	
			    items: [errorMsgDiv]		  				 
			},{//col2
				layout: 'form',
				width: 270,
				defaults: 
				{ 
					msgTarget: 'side',
					invalidClass: 'frame-error',
					validateOnBlur: false,
					validationEvent: 'submit'
				}, 
			    items: [firstNameField]				
			},{
				layout: 'form',
			    items: [req_html],
				width: 300
			},{//col3
				layout: 'form',				
				defaults: 
				{ 
					msgTarget: 'side',
					invalidClass: 'frame-error',
					validateOnBlur: false,
					validationEvent: 'submit'
				},
			    items: [lastNameField]			
			},{				
			    items: [non_req_html]				
			},{//col4
				layout: 'form',				
				defaults: 
				{ 
					msgTarget: 'side',
					invalidClass: 'frame-error',
					validateOnBlur: false,
					validationEvent: 'submit'
				},
			    items: [titleField]				
			},{				
			    items: [non_req_html]				
			},{//col5
				layout: 'form',				
				defaults: 
				{ 
					msgTarget: 'side',
					invalidClass: 'frame-error',
					validateOnBlur: false,
					validationEvent: 'submit'
				},
			    items: [companyField]			
			},{				
			    items: [non_req_html]			
			},{//col6
				layout: 'form',				
				defaults: 
				{ 
					msgTarget: 'side',
					invalidClass: 'frame-error',
					validateOnBlur: false,
					validationEvent: 'submit'
				},
			    items: [websiteField]				
			},{				
			    items: [non_req_html]				
			},{//col7
				layout: 'form',				
				defaults: 
				{ 
					msgTarget: 'side',
					invalidClass: 'frame-error',
					validateOnBlur: false,
					validationEvent: 'submit'
				},
			    items: [phoneField]				
			},{				
			    items: [non_req_html]			
			},{//col8
				layout: 'form',				
				defaults: 
				{ 
					msgTarget: 'side',
					invalidClass: 'frame-error',
					validateOnBlur: false,
					validationEvent: 'submit'
				},
			    items: [emailField1]				
			},{				
			    items: [req_html]			
			},{//col9
				layout: 'form',				
				defaults: 
				{ 
					msgTarget: 'side',
					invalidClass: 'frame-error',
					validateOnBlur: false,
					validationEvent: 'submit'
				},
			    items: [emailField2]				
			},{				
			    items: [req_html]			
			},{//col10
				layout: 'form',				
				defaults: 
				{ 
					msgTarget: 'side',
					invalidClass: 'frame-error',
					validateOnBlur: false,
					validationEvent: 'submit'
				},
			    items: [countryCB]	
			},{				
			    items: [non_req_html]			
			},{//col11
				layout: 'form',				
				defaults: 
				{ 
					msgTarget: 'side',
					invalidClass: 'frame-error',
					validateOnBlur: false,
					validationEvent: 'submit'
				},
			    items: [regionField]				
			},{				
			    items: [non_req_html]			
			},{//col12
				layout: 'form',				
				defaults: 
				{ 
					msgTarget: 'side',
					invalidClass: 'frame-error',
					validateOnBlur: false,
					validationEvent: 'submit'
				},
			    items: [messageTA]				
			},{				
			    items: [req_html_TA]				
			},{//col13				
				rowspan: 2,			
	            items: [captchaDiv]  				
			},{				
	            items: [captchaText]				
			},{				
				layout: 'form',	
				defaults: 
				{ 
					msgTarget: 'side',
					invalidClass: 'frame-error',
					validationEvent: null,
					validateOnBlur: false,
					validationEvent: 'submit'
				},
	            items: [captchaField,hiddenIdField]				
			},{//col14
				colspan:2,				
				layout: 'form',
			//	items:[submitDiv]	
				items: [{
                	layout: 'form',
					buttonAlign: 'left',
                	buttons: [submitBtn2]
				}]		
			},{//col15
				colspan:2,				
				layout: 'form',			
	            items: [footerText]			
			}
			],
            renderTo: 'contact_us_form'
        });
    };
    
    if (!Ext.get('contact_us_form_ext')) 
    {
        buildHandlers();
        buildForm();
    }
};

Ext.onReady(CONTACT_US_FORM);