;(function($) {	
	$.fn.uploadPhotoAjax = function(selector){				
		if($(selector).size() == 0) return false;						
		if($(selector).data('uploadPhotoAjax.instance') == undefined ){		
			$(selector).data('uploadPhotoAjax.instance', new $.fn.uploadPhotoAjax());
			$(selector).hide().data('uploadPhotoAjax.instance').initialize($(selector));			
		}					
		if ( $.isFunction(this.each) ) {
			return this.each(function() {							
				$(this).data('uploadPhotoAjax.selector',selector);				
				$(this).click(function(){					
					$($(this).data('uploadPhotoAjax.selector')).data('uploadPhotoAjax.instance').toggle();
				});				
			});			
		}		
	};	
	$.extend($.fn.uploadPhotoAjax.prototype, {
		self:null,
		visible:false,
		eventsLocked:false,	
		securityImage:false,
		securityImageSrc:false,
		canSubmit:false,
		initialize:function(selfObject){
			this.self = selfObject;			
			this.securityImage = $(this.self).find('#refresh-security-image').parent().find('img');
			this.securityImageSrc = $(this.securityImage).attr('src');			
			$(this.self).find('form').submit(function(){
				return this.ajaxSubmit($(this.self).find('form'));								
			}.bind(this));		
			$(this.self).find('input[type=button]').click(function(){
				this.toggle();
			}.bind(this));
			$(this.self).find('#refresh-security-image').click(function(){				
				this.refreshSecurityImage();
			}.bind(this));			
		},
		ajaxSubmit:function(form){			
			if(this.canSubmit) return true; 
			this.clearFields(false);			
			$.ajax({
			  type: 'POST',
			  url: $(form).attr('action'),
			  data: $(form).serialize(),
			  success: function(data){
				var obj = $.parseJSON(data);				
				if(!obj){
					this.canSubmit = true;
					$(this.self).find('form').submit();
				}else if(obj.errors != undefined){
					this.canSubmit = false;				
					$.each(obj.errors,function(i,elmName){						
						$(this.self).find('[name='+elmName+']').addClass('error');
					}.bind(this));
				}
			  }.bind(this),
			  dataType: 'JSON'
			});	
			return false;
		},
		refreshSecurityImage:function(){
			$(this.securityImage).attr('src',this.securityImageSrc+'?'+Math.random());			
		},
		clearFields:function(removeValue){
			var fields = $(this.self).find('form').serializeArray();					
			$.each(fields,function(i,element){								
				var element = $(this.self).find('form').find('[name='+$(element).attr('name')+']').removeClass('error');
				if(element && removeValue) element.val('');					
			}.bind(this));			
		},		
		toggle:function(){			
			if(this.eventsLocked) return false;
			this.eventsLocked = true;
			if(!this.visible){
				this.clearFields(true);
				$(this.self).fadeIn('slow',function(){
					this.eventsLocked = false;									
					this.visible = true;					
				}.bind(this));
			}else	
				$(this.self).fadeOut('slow',function(){
					this.eventsLocked = false;
					this.visible = false;					
					this.refreshSecurityImage();
				}.bind(this));			
		}
	});	
									
})(jQuery);
