/**
 * @author Ramalingesha ML
 */
Tp.ui.view.user.CompanyRegView = Class
		.create( {

			/**
			 * default constructor
			 * 
			 * @param handlers = {
			 *            onProjectSelection: <BR>
			 *            onNewProjectCreation: <BR>}
			 */
			initialize : function(projectConfig, handlers) {
				Ext.QuickTips.init();
				this.config = projectConfig;
				this.handlers = handlers;
				this.logoPath = projectConfig.filePath;
				this.initView();
			},

			initView : function() {
				this.initForm();
				this.projectPanel = new Ext.Window( {
					layout :'anchor',
					title :'Company Registration',
					modal :true,
					stateful :false,
					closable :true,
					loadMask :true,
					maximizable :false,
					draggable :false,
					resizable :false,
					width :750,
					autoScroll :false,
					autoHeight :true,
					items : [ this.companyRegForm ]
				});
				this.projectPanel.show();
				this.initUploadFramework();
				this.loadDropDown();
				// this.companyRegForm.getForm().findField("companyName").focus();
			},

			loadDropDown : function() {

				var localObj = this;

				Tp.service.GeneralService.getIndustryTypes(null, {
					onSuccess : function(industries) {
						localObj.industryTypeStore.loadData(industries);
					}
				});
				Tp.service.GeneralService.getCountries(null, {
					onSuccess : function(countires) {
						localObj.countryStore.loadData(countires);
					}
				});
			},

			initUploadFramework : function() {

				var localObj = this;

			},

			initForm : function() {
				var localObject = this;

				
				var myValidFn = function(v) {
					   var myRegex = /(^(((http{1}|https{1}|ftp{1}|ftps{1})(\:\/\/{1})+w{3})|w{3})\.+(\w+)\.((\w+){2,3}|((\w+){2,3}\.(\w+){2,3}))+(\/[\w\- \.\/\?%&=]*)?)/;
					   return myRegex.test(v);
					}

					Ext.apply(Ext.form.VTypes, {
					    urlOnly     : myValidFn,
					    urlOnlyText : 'This field should be a URL in the format "http://www.example.com"'
					});
				
				this.otherIndustryType = new Ext.form.TextField( {
					id :'industryOther',
					fieldLabel :'Others',
					labelSeparator :':',
					disabled :true,
					allowBlank :false,
					blankText :'Other Industry Type is required',
					// cls :'qualificationOther',
					msgTarget :'side',
					maxLength :50,
					width :170,
					height :20
				});

				var keyPairModelRecord = Ext.data.Record.create( [ {
					name :'key'
				}, {
					name :"value"
				} ]);

				// create the Data Store to load nationality
				this.industryTypeStore = new Ext.data.Store( {
					reader :new Ext.data.JsonReader( {
						idProperty :"key"
					}, keyPairModelRecord)
				});

				this.countryStore = new Ext.data.Store( {
					reader :new Ext.data.JsonReader( {
						idProperty :"key"
					}, keyPairModelRecord)
				});
				this.companyRegForm = new Ext.FormPanel(
						{
							padding :'10px',
							frame :true,
							id :'regCompany',
							width :735,
							height :450,
							autoHeight :false,
							autoScroll :true,
							fileUpload :true,
							items : [
									this.createTextField('Company Name', 200,
											20, "companyName", false,
											'Company name is required', 50,
											/^[a-zA-Z\s.]*$/),
									this.createEmail('Email', 200, 20, "email",
											false, 'Email is required'),
									{
										items : [ {
											layout :'column',
											items : [
													{
														columnWidth :.52,
														layout :'form',
														items : [ {
															xtype :'combo',
															id :'industryType',
															fieldLabel :'<span class="mandatory">*</span>' + 'Industry Type',
															msgTarget :'side',
															emptyText :'Select',
															triggerAction :'all',
															blankText :'Industry Type is required',
															height :20,
															forceSelection :true,
															allowBlank :false,
															mode :'local',
															store :this.industryTypeStore,
															valueField :'key',
															displayField :'value',
															listeners : {
																select : function(
																		f, r, i) {
																	if (r.data.key == 9999) {
																		localObject.otherIndustryType
																				.setDisabled(false);
																		localObject.otherIndustryType
																				.validate()
																	} else {
																		localObject.otherIndustryType
																				.reset();
																		localObject.otherIndustryType
																				.setDisabled(true)
																	}
																}
															}
														} ]
													},
													{
														columnWidth :.48,
														itemCls :'comp-other',
														layout :'form',
														items : [ this.otherIndustryType ]
													} ]
										} ]
									},
									
							        this.createEditor(
											'Brief About The Company', 522,
											150, "aboutCompany", 300),
									this
											.createUrlField(
													'Company Website URL', 200,
													20, "website", true, '',
													100,
													''),
									this.createTextField('Contact Person', 200,
											20, "contactPerson", false,
											'Contact person is required', 30,
											/^[a-zA-Z\s.]*$/),
									this.createComboBox('Country', 200, 20,
											"country", this.countryStore, '',
											false, 'Country is required'),
									this.createTextField('Mobile', 200, 20,
											"mobileNo", true, '', 13,
											/^[0-9-]*$/),
									this.createTextField('Telephone', 200, 20,
											"telNo", true, '', 20, /^[0-9-]*$/),
									{

										fieldLabel :'Company Logo',
										inputType :'file',
										id :'form-file',
										cls :'CompanyLogo',
										name :'file',
										xtype :'textfield',
										autoShow :true,
										// anchor :'54%'
										height :25
									/*
									 * layout :'column', border :false, items : [ {
									 * columnWidth :.4, border :false, items : [ {
									 * xtype :'panel', html :'Company Logo' } ] }, {
									 * columnWidth :.6, border :false, items : [ {
									 * id :'form-file', inputType :'file', name
									 * :'file', blankText :'Please choose a
									 * file', anchor :'59%', autoShow :true,
									 * xtype :'textfield' } ] } ]
									 */},

									{
										xtype :'label',
										fieldLabel :'Terms And Conditions',
										labelStyle :'width:150px;',
										labelSeparator :'',
										id :'tnc'
									},
									this
											.createCheckBox(
													'I have read, understood and agree to the <a href="terms.jsp"  target="_blank">Terms & Conditions</a> that govern the use of www.talentbridge.co.in',
													200, 40, "tnc", "") ],
							buttons : [ {
								text :'Register',
								handler : function(btn) {

									localObject.onFormDataEntered(btn);
								}
							}, {
								text :'Reset',
								handler : function() {
									localObject.onDataCleared();
								}
							} ]
						});
				localObject.onDataCleared();
			},

			onFileUploaded : function(fileName) {
				this.uploadedFileId = fileName;
			},

			onFormDataEntered : function(btn) {

				var localObj = this;
				if (!this.companyRegForm.getForm().isValid()) {
					return;
				}
				if (document.getElementById("form-file").value) {

					if (this.companyRegForm.getForm().findField("tnc")
							.getValue()) {
						btn.disable();
						localObj.companyRegForm
								.getForm()
								.submit(
										{
											url :'commonupload/upload.do',
											enctype :'multipart/form-data',
											params :'folderPath=' + localObj.logoPath,
											waitMsg :'Uploading your file...',
											success : function(form, action) {
												var imageFile = action.result.object;												
												
												
												if (imageFile
														.substring(
																(imageFile
																		.lastIndexOf(".") + 1),
																imageFile.length) == 'jpg'
														|| imageFile
																.substring(
																		(imageFile
																				.lastIndexOf(".") + 1),
																		imageFile.length) == 'JPG' 
														|| imageFile
														.substring(
																(imageFile
																		.lastIndexOf(".") + 1),
																imageFile.length) == 'PNG'
														|| imageFile
														.substring(
																(imageFile
																		.lastIndexOf(".") + 1),
																imageFile.length) == 'png'
														|| imageFile
														.substring(
																(imageFile
																		.lastIndexOf(".") + 1),
																imageFile.length) == 'TIF'
														|| imageFile
														.substring(
																(imageFile
																		.lastIndexOf(".") + 1),
																imageFile.length) == 'tif'	
														|| imageFile
														.substring(
																(imageFile
																		.lastIndexOf(".") + 1),
																imageFile.length) == 'GIF'	
														|| 	imageFile
														.substring(
																(imageFile
																		.lastIndexOf(".") + 1),
																imageFile.length) == 'gif'		
														|| imageFile
														.substring(
																(imageFile
																		.lastIndexOf(".") + 1),
																imageFile.length) == 'BMP'		
														|| imageFile
														.substring(
																(imageFile
																		.lastIndexOf(".") + 1),
																imageFile.length) == 'bmp'				) {

													localObj
															.onFilesUploadedSuccessfully(action.result.object);
												} else {
													Ext.Msg
															.alert('Failure',
																	'You can upload JPG,PNG,TIF,GIF,BMP (.jpg,.png,.tif,.gif,.bmp) file only');
												}
											},
											failure : function(form, action) {
												Ext.Msg
														.alert('Failure',
																'Unable to upload company Logo');
											}
										});
					} else {
						Ext.MessageBox.show( {
							title :'Error',
							msg :"Please accept terms and conditions",
							buttons :Ext.MessageBox.OK,
							animEl :'mb9',
							icon :Ext.MessageBox.ERROR
						});
					}

				} else {

					if (this.companyRegForm.getForm().findField("tnc")
							.getValue()) {
						btn.disable();
						localObj.companyRegForm
								.getForm()
								.submit(
										{
											url :'commonupload/upload.do',
											enctype :'multipart/form-data',
											params :'folderPath=' + localObj.logoPath,
											success : function(form, action) {
                                               
												localObj
														.onFilesUploadedSuccessfully(action.result.object);

											},
											failure : function(form, action) {
												Ext.Msg
														.alert('Failure',
																'Unable to upload company Logo');
											}
										});
					} else {
						Ext.MessageBox.show( {
							title :'Error',
							msg :"Please accept terms and conditions",
							buttons :Ext.MessageBox.OK,
							animEl :'mb9',
							icon :Ext.MessageBox.ERROR
						});
					}

				}

			},

			onFilesUploadedSuccessfully : function(uploadedFileId) {
				var userObj = {
					roleId :"5",
					email :this.companyRegForm.getForm().findField("email")
							.getValue(),
					companyName :this.companyRegForm.getForm().findField(
							"companyName").getValue(),
					aboutCompany :this.companyRegForm.getForm().findField(
							"aboutCompany").getValue(),
					industryType :this.companyRegForm.getForm().findField(
							"industryType").getValue(),
					industryOther :this.companyRegForm.getForm().findField(
							"industryOther").getValue(),
					website :this.companyRegForm.getForm().findField("website")
							.getValue(),
					contactPerson :this.companyRegForm.getForm().findField(
							"contactPerson").getValue(),
					country :this.companyRegForm.getForm().findField("country")
							.getValue(),
					mobileNo :this.companyRegForm.getForm().findField(
							"mobileNo").getValue(),
					telNo :this.companyRegForm.getForm().findField("telNo")
							.getValue(),
					logo :uploadedFileId
				}
                  
				var u = this.projectPanel;
				Tp.service.user.UserService
						.registerCompany(
								{

									userObj :userObj

								},
								{

									onSuccess : function() {
										u.close();
										Ext.MessageBox
												.show( {
													title :'Registration',
													msg :"Welcome to TalentBridge.<BR/>Your registration has been sucessful and your user details has been sent to your provided email id.",
													buttons :Ext.MessageBox.OK,
													animEl :'mb9',
													icon :Ext.MessageBox.INFO
												});
									},
									onBusinessFailure : function(errors) {

										if (errors != null && errors.length) {
											Ext.MessageBox.show( {
												title :'Error',
												msg :errors[0].value,
												buttons :Ext.MessageBox.OK,
												animEl :'mb9',
												icon :Ext.MessageBox.ERROR
											});

										}
									}
								});
			},

			onDataCleared : function() {
				this.companyRegForm.getForm().reset();
				this.otherIndustryType.setDisabled(true);
			},

			createTextField : function(label, labelWidth, labelHeight, id,
					allowBlank, blankText, maxLength, nameExp) {
				var fieldLabel = label;
				if (!allowBlank) {
					fieldLabel = '<span class="mandatory">*</span>' + label;
				}

				return textVar = new Ext.form.TextField( {
					id :id,
					allowBlank :allowBlank,
					blankText :blankText,
					maxLength :maxLength,
					msgTarget :'side',
					fieldLabel :fieldLabel,
					labelSeparator :':',
					width :labelWidth,
					height :labelHeight,
					regex :nameExp
				});
			},

			createUrlField : function(label, labelWidth, labelHeight, id,
					allowBlank, blankText, maxLength, nameExp) {
				var fieldLabel = label;
				if (!allowBlank) {
					fieldLabel = '<span class="mandatory">*</span>' + label;
				}

				return textVar = new Ext.form.TextField( {
					id :id,
					allowBlank :allowBlank,
					 vtype : 'urlOnly',
					regex :nameExp,
					blankText :blankText,					
					maxLength :maxLength,
					msgTarget :'side',
					fieldLabel :fieldLabel,
					labelSeparator :':',
					width :labelWidth,
					height :labelHeight
				});
			},

			createEmail : function(label, labelWidth, labelHeight, id,
					allowBlank, blankText) {
				var fieldLabel = label;
				if (!allowBlank) {
					fieldLabel = '<span class="mandatory">*</span>' + label;
				}

				return textVar = new Ext.form.TextField( {
					id :id,
					vtype :'email',
					allowBlank :allowBlank,
					maxLength :50,
					blankText :blankText,
					msgTarget :'side',
					fieldLabel :fieldLabel,
					labelSeparator :':',
					width :labelWidth,
					height :labelHeight
				});
			},

			createLabel : function(label, labelWidth, labelHeight, id) {
				return textVar = new Ext.form.Label( {
					id :id,
					fieldLabel :label,
					labelSeparator :':',
					width :labelWidth,
					height :labelHeight
				});
			},

			createComboBox : function(label, labelWidth, labelHeight, id,
					store, selectedValue, allowBlank, blankText) {
				var fieldLabel = label;
				if (!allowBlank) {
					fieldLabel = '<span class="mandatory">*</span>' + label;
				}

				return textVar = new Ext.form.ComboBox( {
					typeAhead :true,
					id :id,
					fieldLabel :fieldLabel,
					labelSeparator :':',
					allowBlank :allowBlank,
					msgTarget :'side',
					blankText :blankText,
					forceSelection :true,
					emptyText :'Select',
					width :labelWidth,
					height :labelHeight,
					triggerAction :'all',
					mode :'local',
					value :selectedValue,
					store :store,
					valueField :'key',
					displayField :'value'
				});
			},

			createCheckBox : function(label, labelWidth, labelHeight, id) {
				return textVar = new Ext.form.Checkbox( {
					id :id,
					boxLabel :label,
					width :labelWidth,
					height :labelHeight
				});
			},

			createEditor : function(label, labelWidth, labelHeight, id,
					maxLength) {
				Ext.QuickTips.init();
				return textVar = new Ext.form.HtmlEditor( {
					fieldLabel :label,
					id :id,
					msgTarget :'side',
					itemCls :'jrf-editor',
					width :labelWidth,
					maxLength :maxLength,
					height :labelHeight,
					hideLabel :false,
					frame :true,
					enableColors :true,
					enableAlignments :true
				});

			}

		});
