//  @import com.hedgehoglab.application.view.BaseView;
//  @import com.hedgehoglab.KeySequencer;
//	@import com.hedgehoglab.application.helper.BaseHelper;
//  @import com.hedgehoglab.solomon.helper.ContactViewHelper;

function UserEditView(scope){
	BaseView.call(this,scope);
	ContactViewHelper.call(this,scope);
	
	var _this=this;
	var _current_user=null;
	var _username_callback=null;
	
	if(scope.element.hasClass('hide')) scope.element.hide().removeClass('hide');
	$(".hide",scope.element).hide().removeClass('hide');
	
	this.hide=function(callback){
		scope.element.fadeOut(100,function(e){
			if(callback) callback();
		});
	};
	
	this.show=function(callback){
		scope.element.fadeIn(100,function(e){
			if(callback) callback();
		});
	}
	
	$('#cancel-edit-user',scope.element).bind('click',function(e){
		_this.raise_event('on_cancel_edit_user',{});
		return false;
	});
	
	$('#profile_1_action_updateprofile',scope.elememt).bind('click',function(e){
		
		
		//	validate form!
		
		$("#useredit",scope.element).submit();
		// _this.raise_event('on_done_edit_user',_current_user);
		return false;
	});
	
	this.render=function(data,this_user){
		if(data!=null){
			_current_user=data;
			_this.render_template_with_view('users/user-edit',{user:_current_user,this_user:this_user},_this,function(rendered_template){
				var ul=$(rendered_template);
				
				//	Hook onto events to save the changes to the user
				
					// Hook onto the username to check for d
				
				$('.scroll-pane',scope.element).html(ul);
				
				$("#useredit",scope.element).bind('submit',function(e){
					return false;
				});
				
				//$('#set_password',scope.element).hide().attr('style','');
				$('.hide',scope.element).hide().removeClass('hide');
				
				$('#change_password',scope.element).bind('click',function(e){
					if($(this).attr('checked')==true){
						$('#set_password',scope.element).show();
						$('#set_password input',scope.element).removeAttr('disabled');
					}else{
						$('#set_password',scope.element).hide();
						$('#set_password input',scope.element).attr('disabled','disabled');
					}
				});
				
				var validator = $("#useredit",scope.element).validate({ 
				        rules: { 
				            firstName: "required", 
				            lastName: "required", 
				            username: { 
				                required: true, 
				                minlength: 2
				// , 
				// 								remote:"/api/backend/check-valid-username"
				              
				            }, 
				            password: { 
   				                required: "#change_password:checked", 
   				                minlength: 5
   				            }, 
   				            passwordconfirm: { 
   				                required: "#change_password:checked", 
   				                minlength: 5, 
   				                equalTo: "#password" 
   				            }, 
				            email: { 
				                required: true, 
				                email: true// , 
				                // 				                remote: "emails.php" 
				            }, 
				            dateformat: "required", 
				            terms: "required" 
				        }, 
				        messages: { 
				            firstName: "Enter your firstname", 
				            lastName: "Enter your lastname", 
				            username: { 
				                required: "Enter a username", 
				                minlength: jQuery.format("Enter at least {0} characters"), 
				                remote: jQuery.format("{0} is already in use") 
				            }, 
				            password: { 
				                required: "Provide a password", 
				                rangelength: jQuery.format("Enter at least {0} characters") 
				            }, 
				            passwordconfirm: { 
				                required: "Repeat your password", 
				                minlength: jQuery.format("Enter at least {0} characters"), 
				                equalTo: "Enter the same password as above" 
				            }, 
				            email: { 
				                required: "Please enter a valid email address", 
				                minlength: "Please enter a valid email address", 
				                remote: jQuery.format("{0} is already in use") 
				            }, 
				            dateformat: "Choose your preferred dateformat", 
				            terms: " " 
				        }, 
				        // the errorPlacement has to take the table layout into account 
				        errorPlacement: function(error, element) { 
				            // if ( element.is(":radio") ) 
				            // 				                error.appendTo( element.parent().next().next() ); 
				            // 				            else if ( element.is(":checkbox") ) 
				            // 				                error.appendTo ( element.next() ); 
				            // 				            else 
				                // error.insertBefore( $(':first-child',element.parent())[0]); 
								$('span.error',element.parent()).append(error);
				        }, 
				        // specifying a submitHandler prevents the default submit, good for the demo 
				        submitHandler: function() { 
				            //alert("submitted!"); 
							//	raise the event here!
							//	Get the values from the fields and put into the model
							_current_user.firstName=$("input[name='firstName']",scope.element).val();
							_current_user.lastName=$("input[name='lastName']",scope.element).val();
							_current_user.email=$("input[name='email']",scope.element).val();
							_current_user.username=$("input[name='username']",scope.element).val();
							_current_user.password=$("input[name='password']",scope.element).val();
							
							if(_current_user.password==""){
								delete _current_user.password;
							}
							
							//	They want to make the user a normal user
							if($("input[name='make_user']",scope.element).attr('checked')!=null){
								if($("input[name='make_user']",scope.element).attr('checked')==true){
									_current_user.role="ROLE_USER";
								}
							}
							
							//	They want to make the user an admin
							if($("input[name='make_admin']",scope.element).attr('checked')!=null){
								if($("input[name='make_admin']",scope.element).attr('checked')==true){
									_current_user.role="ROLE_ADMIN";
								}
							}
							
							_this.raise_event('on_done_edit_user',_current_user);
				        }, 
				        // set this class to error-labels to indicate valid fields 
				        success: function(label) { 
				            // set   as text for IE 
				            label.html(" ").addClass("checked"); 
				        } 
				    }); 

				    // propose username by combining first- and lastname 
				    // $("#username").focus(function() { 
				    // 				        var firstname = $("#firstname").val(); 
				    // 				        var lastname = $("#lastname").val(); 
				    // 				        if(firstname && lastname && !this.value) { 
				    // 				            this.value = firstname + "." + lastname; 
				    // 				        } 
				    // 				    });
				
				//	Hook onto fields for validation
				
				//	If its a null id we need to check the user name every time they type and only allow
				//	 a save when its confirmed new
				
				if(data.id==null){
				

					$("input[name='username']",scope.element).bind('keyup',function(e){
						return e.keyCode!=13;
					});
					
					
				    function on_sequence_ready(event){
						// _this.raise_event('on_username_changed',{
						// 						val:$("input[name='username']",scope.element).val(),
						// 						update:function(_ok){
						// 							// if(!_ok){
						// 							// 	$('#profile_1_action_updateprofile',scope.element).attr('disabled','disabled');
						// 							// 	$('.fieldError',$("input[name='username']",scope.element).parent()).show();
						// 							// }else{
						// 							// 	$('#profile_1_action_updateprofile',scope.element).removeAttr('disabled');
						// 							// 	$('.fieldError',$("input[name='username']",scope.element).parent()).hide();
						// 							// }
						// 							// _this.raise_event('on_username_changed',{val:$("input[name='username']",scope.element).val(),update:function(e){
						// 								if(_username_callback && typeof _username_callback =="function") _username_callback(_ok);
						// 							// }});
						// 							
						// 						}
						// 					});
				    };


				    function on_sequence_changed(event){
						if($("input[name='username']",scope.element).val()==""){
							on_sequence_ready(event);
						}
				    };
				
					KeySequencer.call({},{
				        element:$("input[name='username']",scope.element)
				        ,on_sequence_ready:on_sequence_ready
				        ,on_sequence_changed:on_sequence_changed
				        ,thread_count:50
				        ,thread_timeout:10
				        ,min_value_length:3
				    });
				

					
				}
				
			});
		}else{
			//	FAIL!
		}
	};
}