/*****************************************************************************************************/
/*                                                                                                   */
/*                                     'REGISTER PANEL' CLASS                                        */          
/*                                                                                                   */
/*****************************************************************************************************/

function REGISTER(){
	
	var JSObject = this;
	
	this.type = "register"; 
	this.arr_inputs = [];
						
	this.form;
	this.DOMDoc; //document object from thickbox window
	
	this.send_btn;
	
	this.sendingValues = false;
	
	this.tb_identifier;
	
	/*****************************************************************************************************/
	/*                                                                                                   */
	/*                                      FUNCTION INIT                                                */          
	/*                                                                                                   */
	/*****************************************************************************************************/
	this.init = function(){
		/*****************************************************************************************************/
		/*                                                                                                   */
		/*                                          INFORMATION                                              */          
		/*                                                                                                   */
		/*****************************************************************************************************/
		
		this.send_btn = $('#'+this.type+'_send_btn',this.DOMDoc).get(0);
		
		this.form = this.DOMDoc.getElementById(this.type+'_email').form;
		$("#"+this.form.id,this.DOMDoc).bind("submit",function(){return false;});
		
		this.initCreate();
		this.enableButton(this.send_btn);

	}
	
	
	/*****************************************************************************************************/
	/*                                                                                                   */
	/*                                  FUNCTION CREATE PANEL                                            */          
	/*                                                                                                   */
	/*****************************************************************************************************/
	this.initCreate = function(){
		
		
		/*****************************************************************************************************/
		/*                                                                                                   */
		/*                                    INPUT 'PASSWORD' ACTIONS                                       */          
		/*                                                                                                   */
		/*****************************************************************************************************/
		var $Password = $('#'+this.type+'_password',this.DOMDoc);
		$Password.val("");
		this.arr_inputs.push($Password);
		$Password.inputvalidate({
				type: 				"password",
				required: 			"yes",
				valid: 				false,
				errors:  			["This information is required.",
					 				"Capitalization matters.<br>Use 6 to 32 characters, and don't use your email address."],
				AfterBlurFunction: 	function(){ $RetypePassword.GetOptions().AfterBlurFunction(); },
				DOMDoc: 			JSObject.DOMDoc
		});
		
		
		
		/*****************************************************************************************************/
		/*                                                                                                   */
		/*                                    INPUT 'RETYPEPASSWORD' ACTIONS                                 */          
		/*                                                                                                   */
		/*****************************************************************************************************/
		var $RetypePassword = $('#'+this.type+'_retypepassword',this.DOMDoc);
		$RetypePassword.val("");
		this.arr_inputs.push($RetypePassword);
		$RetypePassword.inputvalidate({
				type: 				"retypepassword",
				required: 			"yes",
				valid: 				false,
				errors:  			["This information is required.",
					 				"Please verify your password again."],
				AfterBlurFunction: 	function(){ 
										
										if ($RetypePassword.val().length == 0) return;
										
										if ($Password.val() != $RetypePassword.val()){
											$RetypePassword.ShowError(1);
										}
										else{
											$RetypePassword.HideError();	
										}
									},
				DOMDoc: 			JSObject.DOMDoc
		});
		
		
		
		/*****************************************************************************************************/
		/*                                                                                                   */
		/*                                      INPUT 'EMAIL' ACTIONS                                        */          
		/*                                                                                                   */
		/*****************************************************************************************************/
		var $Email = $('#'+this.type+'_email',this.DOMDoc);
		this.arr_inputs.push($Email);
		$Email.inputvalidate({
				type: 				"email",
				required: 			"yes",
				valid: 				false,
				errors:  			["This information is required.",
					 				"Only letters, numbers, underscores, dots(.) and one @ are allowed.<br>Ex: name@domain.com",
					  				"Email already registered!"],
			
				ServerFunction: 	function(){
										$Email.SetOptions({ serverResponse: false });
										
										$.ajax({
											type: "POST",
											url: JSInterface.localpath+"users/ajax/checkemail",
											cache: false,
											async: true,
											data: "email="+$Email.val(),
											success: function(response){
												
												var response = Boolean(Number(String(response)));
												(response == true) ? $Email.ShowError(2) : $Email.HideError();
												
												$Email.SetOptions({ serverResponse: true });
											},
											error: function(){
												alert("Our server is busy. Please try again later");
												JSObject.sendingValues = false;
											}
										})
									},
				DOMDoc: 			JSObject.DOMDoc
		});
		
		
				
		/*****************************************************************************************************/
		/*                                                                                                   */
		/*                                      INPUT 'FIRSTNAME' ACTIONS                                    */          
		/*                                                                                                   */
		/*****************************************************************************************************/
		var $FirstName = $('#'+this.type+'_firstname',this.DOMDoc);
		this.arr_inputs.push($FirstName);
		$FirstName.inputvalidate({
				type: 				"alpha",
				required: 			"yes",
				valid: 				($FirstName.val().length > 0) ? true : false,
				extendedChars:		" -.",
				errors:  			["This information is required.",
					 				"Only letters, spaces, hyphens(-) and dots(.) are allowed."],
				DOMDoc: 			JSObject.DOMDoc
		});
		
		
		
		/*****************************************************************************************************/
		/*                                                                                                   */
		/*                                      INPUT 'LASTNAME' ACTIONS                                     */          
		/*                                                                                                   */
		/*****************************************************************************************************/
		var $LastName = $('#'+this.type+'_lastname',this.DOMDoc);
		this.arr_inputs.push($LastName);
		$LastName.inputvalidate({
				type: 				"alpha",
				required: 			"yes",
				valid: 				($LastName.val().length > 0) ? true : false,
				extendedChars:		" -.",
				errors:  			["This information is required.",
					 				"Only letters, spaces, hyphens(-) and dots(.) are allowed."],
				DOMDoc: 			JSObject.DOMDoc
		});
		
		
		/*****************************************************************************************************/
		/*                                                                                                   */
		/*                                      INPUT 'BIRTH DATE' ACTIONS                                   */          
		/*                                                                                                   */
		/*****************************************************************************************************/
		var $BirthDate = $('#'+this.type+'_birthdate',this.DOMDoc);
		this.arr_inputs.push($BirthDate);
		$BirthDate.inputvalidate({
				type: 				"date",
				required: 			"yes",
				valid: 				($BirthDate.val().length > 0) ? true : false,
				extendedChars:		"/",
				dateFormat:			new String('mmddyyyy'),
				errors:  			["This information is required.",
					 				"Please provide the following format: MM/DD/YYYY"],
				DOMDoc: 			JSObject.DOMDoc
		});
		
		
		/*****************************************************************************************************/
		/*                                                                                                   */
		/*                                     INPUT RADIO 'GENDER' ACTIONS                                  */          
		/*                                                                                                   */
		/*****************************************************************************************************/
		var $Gender = $('input[name="'+this.type+'_gender"]',this.DOMDoc);
		this.arr_inputs.push($Gender);
		$Gender.inputvalidate({
				required: 			"yes",
				valid:				false,
				errorParams:		{
										container: $("#"+JSObject.type+"_gender_container",JSObject.DOMDoc).get(0)
									},
				errors:  			["This information is required."],
				extraParams:		{
										value: null
									},
				DOMDoc: 			JSObject.DOMDoc
		});
		for (var i=0; i<$Gender.get().length; i++){
			
			$($Gender.get(i)).click(function(){
				$Gender.HideError();
				$Gender.SetOptions({ valid: true, extraParams: {value : this.value} });
			});
			
			if ($Gender.get(i).checked){
				$Gender.SetOptions({ valid: true, extraParams: {value : $Gender.get(i).value} });
			}
		}
		
		
		/*****************************************************************************************************/
		/*                                                                                                   */
		/*                                      INPUT 'OCCUPATION' ACTIONS                                   */          
		/*                                                                                                   */
		/*****************************************************************************************************/
		var $Occupation = $('#'+this.type+'_occupation',this.DOMDoc);
		this.arr_inputs.push($Occupation);
		$Occupation.inputvalidate({
				type: 				"alphanumeric",
				required: 			"yes",
				valid: 				($Occupation.val().length > 0) ? true : false,
				extendedChars:		" -.",
				errors:  			["This information is required.",
					 				"Only letters, numbers, spaces, hyphens(-) and dots(.) are allowed."],
				DOMDoc: 			JSObject.DOMDoc
		});
		
		
		/*****************************************************************************************************/
		/*                                                                                                   */
	    /*                                      INPUT 'ADDRESS' ACTIONS                           	         */          
		/*                                                                                                   */
		/*****************************************************************************************************/
		var $Address = $('#'+this.type+'_address',this.DOMDoc);
		this.arr_inputs.push($Address);
		$Address.inputvalidate({
				type: 				"alphanumeric",
				required: 			"yes",
				valid: 				($Address.val().length > 0) ? true : false,
				extendedChars:		" -.",
				errors:  			["This information is required.",
					 				"Only letters, numbers, spaces, hyphens(-) and dots(.) are allowed."],
				DOMDoc: 			JSObject.DOMDoc
		});
		
		
		/*****************************************************************************************************/
		/*                                                                                                   */
	    /*                                      INPUT 'CITY' ACTIONS                           	         	 */          
		/*                                                                                                   */
		/*****************************************************************************************************/
		var $City = $('#'+this.type+'_city',this.DOMDoc);
		this.arr_inputs.push($City);
		$City.inputvalidate({
				type: 				"alpha",
				required: 			"yes",
				valid: 				($City.val().length > 0) ? true : false,
				extendedChars:		" -.",
				errors:  			["This information is required.",
					 				"Only letters, spaces, hyphens(-) and dots(.) are allowed."],
				DOMDoc: 			JSObject.DOMDoc
		});

		
		/*****************************************************************************************************/
		/*                                                                                                   */
	    /*                                      INPUT 'DISTRICT' ACTIONS                           	      	 */          
		/*                                                                                                   */
		/*****************************************************************************************************/
		var $District = $('#'+this.type+'_district',this.DOMDoc);
		this.arr_inputs.push($District);
		$District.inputvalidate({
				type: 				"alpha",
				required: 			"yes",
				valid: 				($District.val().length > 0) ? true : false,
				extendedChars:		" -.",
				errors:  			["This information is required.",
					 				"Only letters, spaces, hyphens(-) and dots(.) are allowed."],
				DOMDoc: 			JSObject.DOMDoc
		});
		
		
		/*****************************************************************************************************/
		/*                                                                                                   */
	    /*                                      INPUT 'COUNTRY' ACTIONS                           	      	 */          
		/*                                                                                                   */
		/*****************************************************************************************************/
		var $Country = $('#'+this.type+'_country',this.DOMDoc);
		this.arr_inputs.push($Country);
		$Country.inputvalidate({
				type: 				"alpha",
				required: 			"yes",
				valid: 				($Country.val().length > 0) ? true : false,
				extendedChars:		" -.",
				errors:  			["This information is required.",
					 				"Only letters, spaces, hyphens(-) and dots(.) are allowed."],
				DOMDoc: 			JSObject.DOMDoc
		});

		
		/*****************************************************************************************************/
		/*                                                                                                   */
	    /*                                      INPUT 'POSTAL CODE' ACTIONS                           	     */          
		/*                                                                                                   */
		/*****************************************************************************************************/
		var $PostalCode = $('#'+this.type+'_postalcode',this.DOMDoc);
		this.arr_inputs.push($PostalCode);
		$PostalCode.inputvalidate({
				type: 				"alphanumeric",
				required: 			"yes",
				valid: 				($PostalCode.val().length > 0) ? true : false,
				extendedChars:		" -.",
				errors:  			["This information is required.",
					 				"Only letters, numbers, spaces, hyphens(-) and dots(.) are allowed."],
				DOMDoc: 			JSObject.DOMDoc
		});


		/*****************************************************************************************************/
		/*                                                                                                   */
	    /*                                      INPUT 'HOME PHONE' ACTIONS                           	     */          
		/*                                                                                                   */
		/*****************************************************************************************************/
		var $HomePhone = $('#'+this.type+'_homephone',this.DOMDoc);
		this.arr_inputs.push($HomePhone);
		$HomePhone.inputvalidate({
				type: 				"numeric",
				required: 			"yes",
				valid: 				($HomePhone.val().length > 0) ? true : false,
				errors:  			["This information is required.",
					 				"Only numbers are allowed."],
				DOMDoc: 			JSObject.DOMDoc
		});
		
		
		/*****************************************************************************************************/
		/*                                                                                                   */
	    /*                                      INPUT 'WORK PHONE' ACTIONS                           	     */          
		/*                                                                                                   */
		/*****************************************************************************************************/
		var $WorkPhone = $('#'+this.type+'_workphone',this.DOMDoc);
		this.arr_inputs.push($WorkPhone);
		$WorkPhone.inputvalidate({
				type: 				"numeric",
				required: 			"yes",
				valid: 				($WorkPhone.val().length > 0) ? true : false,
				errors:  			["This information is required.",
					 				"Only numbers are allowed."],
				DOMDoc: 			JSObject.DOMDoc
		});
				
		
		/*****************************************************************************************************/
		/*                                                                                                   */
	    /*                                      INPUT 'ALT PHONE' ACTIONS                           	     */          
		/*                                                                                                   */
		/*****************************************************************************************************/
		var $AltPhone = $('#'+this.type+'_altphone',this.DOMDoc);
		this.arr_inputs.push($AltPhone);
		$AltPhone.inputvalidate({
				type: 				"numeric",
				required: 			"yes",
				valid: 				($AltPhone.val().length > 0) ? true : false,
				errors:  			["This information is required.",
					 				"Only numbers are allowed."],
				DOMDoc: 			JSObject.DOMDoc
		});
				
		
		/*****************************************************************************************************/
		/*                                                                                                   */
		/*                                     INPUT CHECKBOX 'JOIN UNION' ACTIONS                           */          
		/*                                                                                                   */
		/*****************************************************************************************************/
		var $JoinUnion = $('#'+this.type+'_joinunion',this.DOMDoc);
		this.arr_inputs.push($JoinUnion);
		$JoinUnion.inputvalidate({
				required: 			"yes",
				valid:				false,
				errorParams:		{
										container: $("#"+JSObject.type+"_joinunion_container",JSObject.DOMDoc).get(0)
									},
				errors:  			["This information is required."],
				extraParams:		{
										value: null
									},
				DOMDoc: 			JSObject.DOMDoc
		});
		
		$($JoinUnion.click(function(){
			$JoinUnion.HideError();
			$JoinUnion.SetOptions({ valid: true, extraParams: {value : this.value} });
		}));
		
		if ($JoinUnion.get(0).checked){
			$JoinUnion.HideError();
			$JoinUnion.SetOptions({ valid: true, extraParams: {value : $JoinUnion.get(0).value} });
		}
		
		
		/*****************************************************************************************************/
		/*                                                                                                   */
		/*                                     INPUT CHECKBOX 'TERMS' ACTIONS                           	 */          
		/*                                                                                                   */
		/*****************************************************************************************************/
		var $Terms = $('#'+this.type+'_terms',this.DOMDoc);
		this.arr_inputs.push($Terms);
		$Terms.inputvalidate({
				required: 			"yes",
				valid:				false,
				errorParams:		{
										container: $("#"+JSObject.type+"_terms_container",JSObject.DOMDoc).get(0)
									},
				errors:  			["This information is required."],
				extraParams:		{
										value: null
									},
				DOMDoc: 			JSObject.DOMDoc
		});
		
		$($Terms.click(function(){
			$Terms.HideError();
			$Terms.SetOptions({ valid: true, extraParams: {value : this.value} });
		}));
		
		if ($Terms.get(0).checked){
			$Terms.HideError();
			$Terms.SetOptions({ valid: true, extraParams: {value : $Terms.get(0).value} });
		}
		
		
		/*****************************************************************************************************/
		/*                                                                                                   */
		/*                                    INPUT BUTTON 'SEND' ACTIONS                                    */          
		/*                                                                                                   */
		/*****************************************************************************************************/
		var send_mouseDown = false;
		$(this.send_btn).mousedown(function(){
										
										if (JSObject.sendValues == true) return;
										
										send_mouseDown = true;
										$(JSObject.DOMDoc.body).mouseup(function(){
																		 
											 if (JSObject.sendValues == true) return;
											 
											 if (send_mouseDown == true){
												send_mouseDown = false;
												$(JSObject.send_btn).unbind("mouseleave");
												$(JSObject.DOMDoc.body).unbind("mouseup");
												JSObject.sendValues = true;
												JSObject.validate();
											 }
										})
									});
		
		$(this.send_btn).mouseup(function(){
										if (JSObject.sendValues == true) return;
										
										if (send_mouseDown == true){
											send_mouseDown = false;
											$(this).unbind("mouseleave");
											$(JSObject.DOMDoc.body).unbind("mouseup");
											JSObject.sendValues = true;
											JSObject.validate();
										}
									});
		
	}
	
	
	/*****************************************************************************************************/
	/*                                                                                                   */
	/*                                 FUNCTION ENABLE BUTTON                                            */          
	/*                                                                                                   */
	/*****************************************************************************************************/
	this.enableButton = function(btn){
		JSObject.sendValues = false;
		
//		$(btn).css('cursor','pointer');
//		$(btn).animate({opacity:1},100);
	}
	
	
	/*****************************************************************************************************/
	/*                                                                                                   */
	/*                                 FUNCTION DISABLE BUTTON                                           */          
	/*                                                                                                   */
	/*****************************************************************************************************/
	this.disableButton = function(btn){
		JSObject.sendValues = true;
		
//		$(btn).animate({opacity:0.4},100);
//		$(btn).css('cursor','default');
	}
	
	
	/*****************************************************************************************************/
	/*                                                                                                   */
	/*                               FUNCTION SERVER VALIDATE(AJAX - Email)                     		 */          
	/*                                                                                                   */
	/*****************************************************************************************************/
	this.initServerValidate = function(){
		
		var $Email = $('#'+this.type+'_email',this.DOMDoc);
		
		$Email.trigger("blur");
		
		clearInterval(interval);
		
		//wait until Email are verified on the server with AJAX
		var interval = setInterval(function(){
			
			if ($Email.GetOptions().serverResponse == true){
				
				clearInterval(interval);
				
				//if responses from the server are true for all requested fields, then do submit
				if ($Email.GetOptions().valid == true){
					JSObject.sendData();
				}
				else{
					JSObject.sendValues = false;
				}
			}
			
		},100);
		
	}
	
	
	/*****************************************************************************************************/
	/*                                                                                                   */
	/*                                 FUNCTION VALIDATE INFORMATION                                     */          
	/*                                                                                                   */
	/*****************************************************************************************************/
	this.validate = function(){
		
		var countErrors = 0;
				
		// y coordinates of error inputs
		var arr_errorsYCoord = [];
		
		// find how many errors are in the form
		for (var i=0; i<this.arr_inputs.length; i++){
			
			var $input = this.arr_inputs[i];
			var options = $input.GetOptions();
			
			// requirement field error
			if (($input.val().length == 0 || (options.extraParams.value == null && typeof options.extraParams.value == 'object')) && options.required == "yes"){
				$input.ShowError(0);
				countErrors++;
			}
			// error which is already displayed on screen
			else if (options.valid == false){ 
				countErrors++;
			}
			
			// save y coordinate of the error input
			if ($input.GetOptions().valid == false){
				arr_errorsYCoord.push($input.offset().top);	
			}
		}
		
		
		// if there are no errors from syntax point of view, then do SERVER Validation (for AJAX fields)
		if (countErrors == 0){
			this.initServerValidate();
		}
		//move container(div) scroll to the first error
		else{
			arr_errorsYCoord.sort(function(a, b){ return (a-b); });
			
			var container = $('#container', JSObject.DOMDoc);
			var scrollTop = parseInt(container.scrollTop());
			var containerHeight = container.get(0).clientHeight;
			var top = parseInt(container.offset().top);
			
			if (arr_errorsYCoord[0] < top){
				$(container).animate({scrollTop: scrollTop - (top - arr_errorsYCoord[0]) }, 1000);	
			}
			else if (arr_errorsYCoord[0] > top + containerHeight){
				$(container).animate({scrollTop: scrollTop + (arr_errorsYCoord[0] - top) }, 1000);		
			}
			
			JSObject.sendValues = false;
		}
	}
	
	
	/*****************************************************************************************************/
	/*                                                                                                   */
	/*                                      FUNCTION SUBMIT FORM                                         */          
	/*                                                                                                   */
	/*****************************************************************************************************/
	this.submitForm = function(){
		
		return JSInterface.AjaxUpload.dosubmit(JSObject.form, {'onStart' : JSObject.startUploadingData, 'onComplete' : JSObject.completeUploadingData});
		
	}
	
	
	/*****************************************************************************************************/
	/*                                                                                                   */
	/*                                      FUNCTION SEND DATA                                           */          
	/*                                                                                                   */
	/*****************************************************************************************************/
	this.sendData = function(){
		
		$("#"+this.form.id,this.DOMDoc).unbind("submit");
		$("#"+this.form.id,this.DOMDoc).bind("submit",function(){JSObject.submitForm();});
		$("#"+this.form.id,this.DOMDoc).submit();
		
		JSObject.disableButton(JSObject.send_btn);
	}
	
	
	/*****************************************************************************************************/
	/*                                                                                                   */
	/*                                FUNCTION START UPLOADING DATA                                      */          
	/*                                                                                                   */
	/*****************************************************************************************************/
	this.startUploadingData = function(){
		// make something useful before submit (onStart)
		
		//add loader
		var msg = 'Sending data...';
		JSInterface.Preloader.start({message: msg});
		
		//disable form elements
		setTimeout(function(){
						var aElems = JSObject.form.elements;
						nElems = aElems.length;
						
						for (j=0; j<nElems; j++) {
							aElems[j].disabled = true;
						}
					},300);
		
		$('#'+JSObject.type+'_container',JSObject.DOMDoc).animate({opacity:0.4},300);
		
		return true;
	}
	
	
	
	/*****************************************************************************************************/
	/*                                                                                                   */
	/*                              FUNCTION COMPLETE UPLOADING DATA                                     */          
	/*                                                                                                   */
	/*****************************************************************************************************/
	this.completeUploadingData = function(response){
		
		//alert(response)
		$("#"+JSObject.form.id,JSObject.DOMDoc).unbind("submit");
		$("#"+JSObject.form.id,JSObject.DOMDoc).bind("submit",function(){return false;});
		
		response = Boolean(Number(String(response)));
		
		// remove preloader
		JSInterface.Preloader.remove(100);

		if (response == true){

			// ************************** DISPLAY COUNTER *************************** //
			
			noSeconds = 3;
			
			var $LastName = $('#'+JSObject.type+'_lastname',JSObject.DOMDoc);
			var $FirstName = $('#'+JSObject.type+'_firstname',JSObject.DOMDoc);
			
			// show message
			var message = 'Welcome '+$LastName.val()+' '+$FirstName.val()+' <br/>In&nbsp;<span id="seconds_container" style="font-family:Arial, Helvetica, sans-serif; font-size:11px; color:#F00; margin:0px; padding:0px;">'+noSeconds+'</span> seconds you will be redirected to your account page';
			JSInterface.Loader.display({message: message});
			
			var secondsContainer = $('#seconds_container');
	
			function changeNoSeconds(){
				
				noSeconds--;
				secondsContainer.html(noSeconds);
				
				if(noSeconds == 0){
					clearInterval(interval);
					//redirect
					document.location.href = JSInterface.localpath+"users/user/accountform";
				}
			
			}
			
			interval = setInterval(changeNoSeconds,1000);
			
			// ********************************************************************** //

		}else{
			
			// show message
			var message = 'There was an error. Please try again in few seconds.';
			JSInterface.Loader.display({message: message});
			
			//enable form elements
			setTimeout(function(){
							var aElems = JSObject.form.elements;
							nElems = aElems.length;
							for (j=0; j<nElems; j++) {
								aElems[j].disabled = false;
							}
						},300);
			
			//enable buttons
			JSObject.enableButton(JSObject.send_btn);
			
			$('#'+JSObject.type+'_container',JSObject.DOMDoc).animate({opacity:1},300);
		}
		
	}
}
