Ext.namespace("WCS");

WCS.FormWindow = function(cfg){
    Ext.apply(this, cfg);
    
    formScope = this;
};

Ext.extend(WCS.FormWindow, Ext.util.Observable, {
	formColumns: 1,
	
	formLabelAlign: 'left',
	
	formType: null,
	
	formFields: [],
	
	launchWindow: function(formType, winConfig){
		var winHeight = winConfig.height;
		var winWidth = winConfig.width;
		var winResize = (winConfig.resizable == true) ? true : false;
		
		this.emailRecipient = winConfig.emailRecipient ? winConfig.emailRecipient : WCS.emails.main;
		this.emailBody = winConfig.emailBody ? winConfig.emailBody : "";
		this.emailSubject = winConfig.emailSubject ? winConfig.emailSubject : "";
		
        //check to see if window is already open
        var popup = Ext.getCmp('popup-win');
        if(popup && popup.isVisible()) {
            return;
        }
        var loadMask = new Ext.LoadMask(Ext.getBody(), {
            msg: "Please wait..."
        });
        loadMask.show();

        var mgr = new Ext.WindowGroup();
        mgr.zseed = 10000;

        loadMask.hide();
        
        if(!Ext.getCmp('popup-win'))
        {
        	this.formColumns = 1;
        	this.formLabelAlign = 'left';
        	this.formFields = [];
        	this.formType = formType;
        	
        	this.generateRegistrationDisclaimer();
        	this.generateName();
        	this.generateCompany();
        	this.generateAddress();
        	this.generatePhone();
        	this.generateEmail();
        	this.generatePhotoUpload();
        	this.generateResume();
        	this.generateProductionSelection();
        	this.generateVideoUpload();
        	this.generateWeblink();
        	this.generateRegistrationCheckbox();
        	this.generateAmount();
        	this.generateContactInfo();
        	
        	if (formType == "Registration") {
            	this.formFields.push({
    				layout: 'form',
    				items: [ this.nameField,
    				         this.companyField,
    				         this.streetField,
    				         this.cityField, 
    				         this.stateField,
    				         this.zipField,
    				         this.phoneField,
    				         this.emailField,
    				         this.registrationDisclaimer
    				]
            	});
        	} else if (formType == "Casting") {
            	this.formFields.push({
    				layout: 'form',
    				items: [ this.nameField,
    				         this.companyField,
    				         this.productionField,
    				         this.streetField,
    				         this.cityField, 
    				         this.stateField,
    				         this.zipField,
    				         this.phoneField,
    				         this.emailField,
    				         this.photoField1,
    				         this.photoField2,
    				         this.photoField3,
    				         this.addPhotoLink,
    				         this.resumeSelectRadio,
    				         this.resumeUploadField,
    				         this.resumeTextField,
    				         this.videoField,
    				         this.weblinkField,
    				         this.registrationCheckbox,
    				         this.passwordField,
    				         this.passwordConfirmationField
    				]
            	});
        	} else if (formType == "Contact") {
        		this.formColumns = 2;
        		this.formLabelAlign = 'top';
            	this.formFields.push({
    				layout: 'form',
    				rowspan: 2,
    				height: 410,
    				cellCls: 'wcs-contactForm-left',
    				items: [ this.logo ]
            	});
            	this.formFields.push({
    				cellCls: 'wcs-contactForm-right',
    				layout: 'form',
    				height: 410,
    				items: [ this.toField,
    				         this.nameField,
    				         this.emailField,
    				         this.subjectField,
    				         this.emailBodyField
    				]
            	});
        	}
        	
        	this.formPanel = new Ext.form.FormPanel({
        		id: 'formPanel',
                autoScroll : true,
        		border: false,
    	        fileUpload: true,
                layout:"table",
                layoutConfig:{
        			columns:this.formColumns,
        	        tableAttrs: {
		            	style: {
		            		width: '100%',
		            		background: 'none'
		            	}
		            }
        		},
                labelAlign: this.formLabelAlign,
                items: this.formFields,
                buttons: [{
    		        text: 'Cancel',
    		        handler: function()
    		        {
    		            Ext.getCmp('popup-win').close();
    		        }
    		    },{
    		        text: 'Submit',
    		        handler: this.onSaveClick
    		    }]
    		});
        	
            var popup = new Ext.Window({
                autoScroll : false,
                resizable : winResize,
                id: 'popup-win',
                title: formType + " Form",
                autoShow: true,
                closable: true,
                draggable: false,
                maximizable:false,
                layout: 'fit',
                manager: mgr,
                shadow: false,
                modal: true,
                constrain: true,
                width: winWidth ? winWidth : 500,
                height: (winHeight && winHeight <= Ext.lib.Dom.getViewHeight()) ? winHeight : Ext.lib.Dom.getViewHeight(),
                items: this.formPanel
            });            
        }

        var win = Ext.getCmp('popup-win');
        win.show();
        win.center();
        
        win.on('resize', function(newWidth, newHeight) {
        	win.center();
        });
        
        if (formType == "Casting") {
            this.resumeSelectRadio.items.items[0].setValue(true);
            
	        Ext.get('x-form-el-photoField2').parent().setHeight(0);
	        Ext.get('x-form-el-photoField3').parent().setHeight(0);
	    	Ext.get("x-form-el-passwordField").parent().setHeight(0);
	    	Ext.get("x-form-el-passwordConfirmationField").parent().setHeight(0);
	        
			var addPhotoLink = Ext.get("addPhotoLink");
	        addPhotoLink.on('click', function() {
	        	var photoField2 = Ext.get('x-form-el-photoField2').parent();
	        	var photoField3 = Ext.get('x-form-el-photoField3').parent();
	        	if(photoField2.getHeight() == 0) {
	        		photoField2.setHeight(22);
	        	} else if (photoField3.getHeight() == 0) {
	        		photoField3.setHeight(22);
	        	} else {
	        		alert("You may only upload a maximum of 3 photos.");
	        	}
	        }, this);
	    }

        if (formType !== "Contact") {
			jQuery('#phoneField').mask("(999) 999-9999");
			jQuery('#zipField').mask("99999");
        }
        
        if (formType == "Registration") {
        }
        
        Ext.EventManager.onWindowResize(function(newWidth, newHeight){
        	if (newHeight < win.getHeight()) {
        		win.setHeight(newHeight);
        	}
        });
    },
    
	generateRegistrationDisclaimer: function() {
		this.registrationDisclaimer = new Ext.form.Label ({
		    name: "registrationDisclaimer",
		    id:'registrationDisclaimer',
		    html: '<i>' + WCS.lang.registrationDisclaimer + '</i>'
		});
    },
    
	generateName: function() {
		this.nameField = new Ext.form.TextField ({
		    name: "nameField",
		    id:'nameField',
		    fieldLabel: WCS.lang.name,
		    allowBlank: false,
		    width: 300,
		    value: ''
		});
    },
    
	generateCompany: function() {
		this.companyField = new Ext.form.TextField ({
		    name: "companyField",
		    id:'companyField',
		    fieldLabel: (this.formType == "Casting") ? WCS.lang.agency : WCS.lang.company,
		    allowBlank: true,
		    width: 300,
		    value: ''
		});
    },

	generateAddress: function() {
		this.streetField = new Ext.form.TextField ({
		    name: "streetField",
		    id:'streetField',
		    fieldLabel: WCS.lang.street,
		    allowBlank: true,
		    width: 300,
		    value: ''
		});
    	
		this.cityField = new Ext.form.TextField ({
		    name: "cityField",
		    id:'cityField',
		    fieldLabel: WCS.lang.city,
		    allowBlank: true,
		    width: 150,
		    value: ''
		});

		this.stateField = new Ext.form.ComboBox({
			id: 'stateField',
		    store: new Ext.data.SimpleStore({
			    data: [ ['AL','Alabama'],
			            ['AK','Alaska'],
			            ['AZ','Arizona'],
			            ['AR','Arkansas'],
			            ['CA','California'],
			            ['CO','Colorado'],
			            ['CT','Connecticut'],
			            ['DE','Delaware'],
			            ['DC','District of Columbia'],
			            ['FL','Florida'],
			            ['GA','Georgia'],
			            ['HI','Hawaii'],
			            ['ID','Idaho'],
			            ['IL','Illinois'],
			            ['IN','Indiana'],
			            ['IA','Iowa'],
			            ['KS','Kansas'],
			            ['KY','Kentucky'],
			            ['LA','Louisiana'],
			            ['ME','Maine'],
			            ['MD','Maryland'],
			            ['MA','Massachusetts'],
			            ['MI','Michigan'],
			            ['MN','Minnesota'],
			            ['MS','Mississippi'],
			            ['MO','Missouri'],
			            ['MT','Montana'],
			            ['NE','Nebraska'],
			            ['NV','Nevada'],
			            ['NH','New Hampshire'],
			            ['NJ','New Jersey'],
			            ['NM','New Mexico'],
			            ['NY','New York'],
			            ['NC','North Carolina'],
			            ['ND','North Dakota'],
			            ['OH','Ohio'],
			            ['OK','Oklahoma'],
			            ['OR','Oregon'],
			            ['PA','Pennsylvania'],
			            ['RI','Rhode Island'],
			            ['SC','South Carolina'],
			            ['SD','South Dakota'],
			            ['TN','Tennessee'],
			            ['TX','Texas'],
			            ['UT','Utah'],
			            ['VT','Vermont'],
			            ['VA','Virginia'],
			            ['WA','Washington'],
			            ['WV','West Virginia'],
			            ['WI','Wisconsin'],
			            ['WY','Wyoming']
			        ],
			    fields: ['code', 'stateName']
			}),
			valueField:'code',
			displayField:'stateName',
	        fieldLabel: WCS.lang.state,
		    typeAhead: true,
		    mode: 'local',
		    triggerAction: 'all',
		    selectOnFocus:true,
		    allowBlank:true,
		    forceSelection: true,
		    width: 150
		});
	
		this.zipField = new Ext.form.TextField ({
		    name: "zipField",
		    id:'zipField',
		    fieldLabel: WCS.lang.zip,
		    allowBlank: true,
		    width: 50,
		    value: ''
		});
    },

	generatePhone: function() {
		this.phoneField = new Ext.form.TextField ({
		    name: "phoneField",
		    id:'phoneField',
		    fieldLabel: WCS.lang.phone,
		    allowBlank: true,
		    width: 100,
		    value: ''
		});
    },

	generateEmail: function() {
		this.toField = new Ext.form.TextField ({
		    name: "toField",
		    id:'toField',
		    fieldLabel: WCS.lang.to,
		    allowBlank: false,
		    width: 300,
		    readOnly: true,
		    value: this.emailRecipient
		});    	

		this.emailField = new Ext.form.TextField ({
		    name: "emailField",
		    id:'emailField',
		    fieldLabel: WCS.lang.email,
		    allowBlank: false,
		    width: 300,
		    vtype: 'email'
		});    	

		this.subjectField = new Ext.form.TextField ({
		    name: "subjectField",
		    id:'subjectField',
		    fieldLabel: WCS.lang.subject,
		    allowBlank: false,
		    width: 300,
		    value: this.emailSubject,
		    readOnly: this.emailSubject ? true : false
		});    	

		this.emailBodyField = new Ext.form.TextArea ({
		    id:'emailBodyField',
		    fieldLabel: WCS.lang.body,
		    width: 300,
		    height: 200,
		    value: this.emailBody
		});    	
    },

	generatePhotoUpload: function() {
		this.photoField1 =  new Ext.form.FileUploadField({
			id: 'photoField1',
            fieldLabel: WCS.lang.photo + '(s)',
            emptyText: WCS.lang.selectPhoto,
    		buttonText : '',
            buttonCfg: {
                iconCls: 'upload-icon'
            },
    		width: 250
        });
		
		this.photoField2 =  new Ext.form.FileUploadField({
			id: 'photoField2',
            fieldLabel: '',
            labelSeparator: '',
            emptyText: WCS.lang.selectPhoto,
    		buttonText : '',
            buttonCfg: {
				id: 'photoField2-btn',
                iconCls: 'upload-icon'
            },
            collapsed: true,
    		width: 250
        });
		
		this.photoField3 =  new Ext.form.FileUploadField({
			id: 'photoField3',
            fieldLabel: '',
            labelSeparator: '',
            emptyText: WCS.lang.selectPhoto,
    		buttonText : '',
            buttonCfg: {
				id: 'photoField3-btn',
                iconCls: 'upload-icon'
            },
    		width: 250
        });
		
		this.addPhotoLink = new Ext.form.Label({
			html: "<div id='addPhotoLink'><a href='#'>" + WCS.lang.addPhotoLink + "</a></div>"
		});
    },

	generateResume: function() {
        this.resumeSelectRadio = new Ext.form.RadioGroup({
            id : "resumeSelect",
            columns: 2,
            allowBlank: true,
            fieldLabel: WCS.lang.resume,
            items: [
                {
                	boxLabel: WCS.lang.upload, 
                	name: 'resumeSelectRadio',
                    listeners: {
	                    'check': function(object, isSelected) 
		                    {
                				if(isSelected)
                				{
    	                			Ext.getCmp('resumeUploadField').show();
    	                    		Ext.get('x-form-el-resumeUploadField').show();
    	                    		Ext.getCmp('resumeTextField').hide();
                				}
		                    }
                 	}
        		},
                { 
        			boxLabel: WCS.lang.enterBelow, 
        			name: 'resumeSelectRadio',
                    listeners: {
	                    'check': function(object, isSelected) 
		                    {
                				if(isSelected)
                				{
    	                			Ext.getCmp('resumeUploadField').hide();
    	                    		Ext.get('x-form-el-resumeUploadField').hide();
    	                    		Ext.getCmp('resumeTextField').show();
                				}
		                    }
                 	}
                }
            ]
        });      
        
		this.resumeUploadField =  new Ext.form.FileUploadField({
    		id: 'resumeUploadField',
            name: 'resumeUploadField',
            fieldLabel: '',
            labelSeparator: '',
    	    emptyText:WCS.lang.selectFile,
    		buttonText : WCS.lang.browse,
    		allowBlank: true,
    		width: 275,
    		buttonCfg: {
				id: 'resumeUploadButton'
			}
        });
		
		this.resumeTextField = new Ext.form.TextArea({
			id: 'resumeTextField',
			width: 300,
			height: 200
		});		
    },

	generateProductionSelection: function() {
		this.productionField = new Ext.ux.form.MultiSelect({
            fieldLabel: WCS.lang.productions,
            name: 'productionField',
            width: 300,
            height: 100,
            allowBlank:true,
            store: [['production0', WCS.lang.virgilsLaw],
                    ['production0', WCS.images.future1Title],
                    ['production0', WCS.images.future2Title]],
            ddReorder: false
        });	
    },

	generateVideoUpload: function() {
		this.videoField =  new Ext.form.FileUploadField({
            fieldLabel: WCS.lang.video,
            emptyText: WCS.lang.selectPhoto,
    		buttonText : '',
            buttonCfg: {
                iconCls: 'upload-icon'
            },
    		width: 250
        });
    },

	generateWeblink: function() {
		this.weblinkField = new Ext.form.TextField ({
		    name: "weblinkField",
		    id:'weblinkField',
		    fieldLabel: WCS.lang.weblink,
		    allowBlank: true,
		    width: 300,
		    value: ''
		});    	
    },

	generateRegistrationCheckbox: function() {
        function showPassword(checkbox, checked) {
        	var password = Ext.get("x-form-el-passwordField").parent();
        	var passwordConfirmation = Ext.get("x-form-el-passwordConfirmationField").parent();
        	if (checked) {
        		password.setHeight(22);
        		passwordConfirmation.setHeight(22);
        	} else {
        		password.setHeight(0);
        		passwordConfirmation.setHeight(0);
        	}
        }
        
		this.passwordField = new Ext.form.TextField ({
		    name: "passwordField",
		    id:'passwordField',
		    fieldLabel: WCS.lang.password,
		    allowBlank: true,
		    width: 150
		});
		
		this.passwordConfirmationField = new Ext.form.TextField ({
		    name: "passwordConfirmationField",
		    id:'passwordConfirmationField',
		    fieldLabel: WCS.lang.confirmPassword,
		    allowBlank: true,
		    width: 150
		});
		
		this.registrationCheckbox = new Ext.form.Checkbox({
			id: 'registrationCheckbox',
			fieldLabel: WCS.lang.register,
			handler: showPassword,
			value: true
		});
    },

	generateAmount: function() {
		this.amountField = new Ext.form.NumberField ({
		    name: "amountField",
		    id:'amountField',
		    fieldLabel: WCS.lang.amount,
		    allowBlank: false,
		    width: 100
		});    	
    },

	generateContactInfo: function() {
		this.logo = new Ext.form.Label({
			html: '<div id="wcs-contact-logo"><center><img src="images/contact_page_logo.jpg" height="300px" width="340px"/></center></div>'	
		});
    },

    validateForm: function() {
    	if (formScope.formType == "Registration") {
    		var company = formScope.companyField.getValue();
    		var street = formScope.streetField.getValue();
    		var city = formScope.cityField.getValue();
    		var state = formScope.stateField.getValue();
    		var zip = formScope.zipField.getValue();
    		
    		if (!Ext.isEmpty(company) && 
    				(Ext.isEmpty(street) ||
    	    				 Ext.isEmpty(city) ||
    	    				 Ext.isEmpty(state) ||
    	    				 Ext.isEmpty(zip)
    				)
    			) {
    			Ext.Msg.alert(formScope.formType + " Form Error", "Companies must provide an address.");
    			return false;
    		}    		
    	} 
    	return true;
    },
    
    onSaveClick: function() {
    	var isFormValid = formScope.validateForm();
    	
    	if (isFormValid && formScope.formPanel.getForm().isValid()) 
    	{   
        	var processingUrl = formScope.formType.toLowerCase() + '.php';
        	var postParams = {};
    		if (formScope.formType == "Contact") {
    			postParams["toField"] = formScope.toField.getValue();
    			postParams["nameField"] = formScope.nameField.getValue();
    			postParams["emailField"] = formScope.emailField.getValue();
    			postParams["subjectField"] = formScope.subjectField.getValue();
    			postParams["emailBodyField"] = formScope.emailBodyField.getValue();
	    	} else if(formScope.formType == "Registration") {
    			postParams["nameField"] = formScope.nameField.getValue();
    			postParams["companyField"] = formScope.companyField.getValue();
    			postParams["streetField"] = formScope.streetField.getValue();
    			postParams["cityField"] = formScope.cityField.getValue();
    			postParams["stateField"] = formScope.stateField.getValue();
    			postParams["zipField"] = formScope.zipField.getValue();
    			postParams["phoneField"] = formScope.phoneField.getValue();
    			postParams["emailField"] = formScope.emailField.getValue();
	    	}
        	
        	Ext.Ajax.request({
				url: processingUrl,
				method: 'POST',
				success: function(response){
                	var win = Ext.getCmp('popup-win');
                	win.close();
					alert(response.responseText);
				},
				failure: function(){
					alert("Error submitting form");
				},
				params: postParams
     		});        	
    	} 
    	else 
    	{
        	alert(WCS.lang.invalidFormMsg);
    	}    	
    }
});