
	/**
	 * @author Евгений Дорошенко
	 * @date 2009-07-30
	 *
	 * Плагин обработки ошибок формы
	 */


(function($) {

	$.fn.errors = {};
	
	$.fn.extend({
		errors: function(mode, argument) {
		
			this.extend($.fn.errors);
		
			switch(mode) {
				case 'options':
					returned = this._options(argument);
					if (returned)
						return returned;
					break;
				case 'set': this._set(argument); break;
				case 'clear': this._clear(); break;
			}
			
			return this;
		}
	});
	
	$.extend($.fn.errors, {
		config: {
			qtip: {
				show: {
					delay: 0,
					when: {
						event: 'mouseover'
					},
					effect: {
						type: 'fade',
						length: 0
					}
				},
				hide: 'mouseout',
				style: {
					name: 'dark',
					border: {
						width: 0
					},
					background: 'transparent',
					width: 'auto'
				},
				position: {
					corner: {
						target: 'topLeft',
						tooltip: 'bottomLeft'
					},
					adjust: {
						y: -4,
						x: 0
					}
				},
				content: {
					prerender: true
				}
			}
		},
		
		_clear: function() {
			$('.error', this).removeClass('error').qtip('destroy');
		},
		
		_set: function(argument) {
			for (index in argument) {
				var element = $('input[name="' + argument[index].field + '"]', this);
				if ('radio' == element.attr('type')) {
					element
						.bind('change.errors', function() {
							$(this)
								.parents('*[name="' + $(this).attr('name') + '"]')
								.removeClass('error')
								.qtip('destroy')
								.unbind('change.errors');
						})
						.parents('*[name="' + element.attr('name') + '"]')
						.qtip($.extend(this.config.qtip, { content: argument[index].message }))
						.addClass('error');
				} else {
					element
						.qtip($.extend(this.config.qtip, { content: argument[index].message }))
						.addClass('error')
						.bind('change.errors', function() {
							$(this)
								.removeClass('error')
								.qtip('destroy')
								.unbind('change.errors');
						});
				}
			}
			
			$(this).unbind('submit.errors').bind('submit.errors', function() {
				$(this).errors('clear');
				return true;
			});
		},
		
		_options: function(argument) {
			if ('undefined' == typeof argument)
				return $.fn.errors.config.qtip;
			$.extend($.fn.errors.config.qtip, argument);
		}
	});
	
})(jQuery);

