var openAccount =  {
	container: null,
	dialogStep1: null,
	dialogStep2: null,
	currentStep: null, //track which form step is current
	
	init: function(){
		//check if user allowed
		if(!AppData.openAccount.isAllowed){
			//user apperantly not allowed by country
			$.flashMessage(AppData.langOpenAccount.notAllowedRegion, 
					{msgType:"warning", displayType: 'dialog'});
			return false;
		}
		
		/*init dialog windows*/
		openAccount.container = $('div.container');
		var dialogVars = {
				title: AppData.langOpenAccount.dialogTitle,
				dialogClass: 'bbinary_dialog' ,
				autoOpen: false,
				width: 855,
				height: 552,
				modal:true,
				closeOnEscape: true,
				closeText: ''
		};
		
		openAccount.dialogStep1 = $('div#registerStep1')
		openAccount.dialogStep2 = $('div#registerStep2')
		
		openAccount.dialogStep1.removeClass('hidden');
		openAccount.dialogStep1.dialog(dialogVars);
		
		openAccount.dialogStep2.removeClass('hidden');
		openAccount.dialogStep2.dialog(dialogVars);
		
		/* which form to show?*/
		if(AppData.openAccount.registrationStep == 1){
			openAccount.dialogStep1.dialog('open');
		}
		else if(AppData.openAccount.registrationStep == 2) openAccount.dialogStep2.dialog('open');
		openAccount.validateForm();
		openAccount.currentStep = AppData.openAccount.registrationStep;
		
		$('div.buttonsBlock input.next').click(openAccount.onOpenAccountNext);
		$('div.buttonsBlock input.back').click(openAccount.onOpenAccountBack);
		openAccount.validateForm();
		
		//set sticky birthday fields
		$('td.birthday input').focus(openAccount.onFocusDate).blur(openAccount.onBlurDate);
		
		$('select#currency').selectbox(
				{
					inputClass: 'selectboxBigLong',
					containerClass: 'selectbox-wrapperBig',
					scrollBar: true,
					hoverClass: 'selectHover'
				}
		)
		
		// NEED THIS HERE? openAccount.container.find('div.terms div').jScrollPane({showArrows:true, scrollbarWidth: 16, arrowSize: 16});
	},
	onOpenAccountNext: function() {
		
		//is this form valid?
		var isValid = openAccount.validateForm(openAccount.currentStep);
		if(! isValid){
			$.flashMessage(AppData.langOpenAccount.correctErrorsBeforeMovingOn, 
							{msgType:"error", displayType: 'notification', stick: false});
			return false;
		}
		
		if (openAccount.currentStep == 1) {
			// check minimum age NOT IMPLEMENTED
			/*var day = openAccount.dialogStep1.find('input[name="day"]').val();
			var month = openAccount.dialogStep1.find('input[name="month"]').val();
			var year = openAccount.dialogStep1.find('input[name="year"]').val();
			var age = 18;
			var birthday = new Date();
			birthday.setFullYear(year, month - 1, day);
			var currdate = new Date();
			currdate.setFullYear(currdate.getFullYear() - age);
			if ((currdate - birthday) < 0) {
				$.flashMessage(AppData.langOpenAccount.underAgeForRegistering,
						{
							msgType : "warning",
							displayType : 'dialog'
						});
				return false;
			} else {*/
				openAccount.dialogStep2.dialog('open');
				openAccount.dialogStep1.dialog('close');
				openAccount.currentStep = 2;
			
		} else if (openAccount.currentStep == 2) {
			//submit!!!
			//this will copy all inputs from form1 to form2 and submit form2
			$('form#openAccountForm_1 table.formTable').prependTo($('form#openAccountForm_2'));
			//hide form show animated processsing gif
			openAccount.dialogStep2.find('form.openAccountForm, input.uiDialog_button').css('display','none');
			openAccount.dialogStep2.find('div.processingRegistration').removeClass('hidden');
			
			$('form#openAccountForm_2 input[type="submit"]').click();		
		}
	},
	onOpenAccountBack: function() {
		openAccount.dialogStep1.dialog('open');
		openAccount.dialogStep2.dialog('close');
		openAccount.currentStep = 1;
	},

	  /**
	*	every change of time value (Lightstreamer)
	*	we call to 'onUpdateTime' function
	*
	**/
	onUpdateTime: function() {
		
	},

	onFocusDate: function(event){
		var field = $(event.target);
		var value = $.trim(field.val());
		if(value == AppData.langOpenAccount[field.attr('name')])
			field.val('');
	},

	onBlurDate: function(event){
		var field = $(event.target);
		var value = $.trim(field.val());
		var fieldName = field.attr('name');
		if(value == '')
			field.val(AppData.langOpenAccount[fieldName])
	},
	validateForm : function(formNumber) {
		//Validate OpenAccount form
		
		var validationParams = {
			rules: {	
				email: {
					required: true,
					email: true,
					remote: {
						url: 'rpcProxy/isUniqueEmail',
						type: 'post'
					}	
				},
				captcha: {
					required: true,
					remote: {
						url: 'rpcProxy/isCaptchaValid',
						type: 'post'
					}	
				}	
			},
			messages: {
				email: {
					remote: 'Cannot use that mail address.'
				},
				captcha: {
					remote: 'Incorrect answer.'
				},
				acceptTerms: {
					required: 'Please accept our terms.'
				}
			},
			onkeyup: false,

			
			// Append the error element to the div.error element in the table
			errorPlacement: function(error, element) {
				//refresh captcha image
				if( $(element).is('input[name="captcha"]')){
					var captchaImg = $(element).parents('td').find('img');
					var src = captchaImg.attr('src'); 
					captchaImg.attr('src', ''); 
					captchaImg.attr('src', src ); 
					
				
				}
				//mark tr with error, should turn whole div to error color
				$(element).parents('tr').addClass('error');
				var error_parent = $(element).parents('td').next('td');
				if (error_parent.children('div.errorText').size()){ //en error element exists
					
					error_parent.children('div.errorText').html(error);
					
				} else { //error element doesnt exist. create one and append the error to it
					
					var error_el = $('<div class="attention"><div class="errorText" /></div>').appendTo(error_parent);
					//console.log(error_el);
					error.appendTo(error_el.children('div.errorText'));
				}
				
			},
			unhighlight: function(element) { //When an error is fixed, hide the div.error element
				if( $(element).is('input[name="day"], input[name="month"] ,input[name="year"]')){
					var dateElement = $(element).attr('name');
					//remove only this msgError
					$(element).parents('td').next('td').find('label[for='+ dateElement + ']')
								.parents('div.attention').remove();
					//remove error class from tr only if all messages gone
				
					if( $(element).parents('td').next('td').find('div.attention').length == 0){
						$(element).parents('tr').removeClass('error');	
					}
				}else{
					//other elements
			   	$(element).parents('td').next('td').find('div.attention').remove();
				//remove tr error class 
				$(element).parents('tr').removeClass('error');
				}
			},

			ignore: ".ignore"

			//SUBMIT BY NON AJAX submitHandler: Deposit.depositByCC //submit the form when everything is valid
			
		}; //end .validatationParams
		
		
		if(formNumber == null){
			//init on-click validation 
			$('form.openAccountForm').each(function(){$(this).validate(validationParams)}); 
		}else{
			//validate now  and return result
			return $('form#openAccountForm_'+formNumber).validate(validationParams).form();
		}
	}
}
$(document).ready(function() { 
	if(AppData.openAccount.autoStart) 
			openAccount.init();
}); 
