/*
	ВАЛИДАТОР ФОРМ
*/

var FormValidator = new Class ({
	initialize: function(formID, params) {
		this.formID = formID; // форма
		this.errorPrefix = 'error_'; // префикс ошибок
		this.fields = {}; // поля
		this.submit = true; // добавлять событие здесь или вручную
		if (params != undefined && params.submit != undefined) {
			this.submit = params.submit;
		}
		
		// Сабмит
		if (this.submit) {
			$(formID).addEvent('submit', this.setHandle.bindWithEvent(this));
		}
	},
	
	// Новое правило
	addRoule: function(name, code, text, custom) {
		if (this.fields[name]) {
			var field = {
				"code" : code,
				"text" : text
			};
			this.fields[name][this.fields[name].length] = field;
		}
		else {
			this.fields[name] = [
				{
					"code" : code,
					"text" : text
				}
			];
		}
	},
	
	// Просмотр правил
	viewRoules: function() {
		return this.fields;
	},
	
	// Сабмит
	setHandle: function(event) {
		if (!this.validate()) {
			event.stop();
		}
	},
	
	// Собственно проверка
	validate: function() {
		var errorPrefix = this.errorPrefix;
		var errorText = '';
		var classError = 'error_field';
		var result = true;
		var error = false;
		
		$each(this.fields, function(field, index){
			$each(field, function(check){
				var value = $(index).get('value').trim();
				if ($(index).hasClass('m')) {
					value = '';
				}
				// Условие
				switch (check.code) {
					case 'zero':
						// Не ноль
						cond = "value == 0";
						break;
					case 'empty':
						// Не пусто
						cond = "value == ''";
						break;
					case 'empty_editor':
						// Не пусто (для редактора)
						cond = "tinyMCE.activeEditor.getContent() == ''";
						break;
					case 'empty_file':
						// Не выбран файл
						cond = "$('id').get('value') == 0 && value == ''";
						break;
					case 'num':
						// Только число (целое)
						cond = "value != '' && /[^0-9]/.test(value)";
						break;
					case 'num_float':
						// Только число (с плавающей запятой)
						cond = "value != '' && /[^0-9\.]/.test(value)";
						break;
					case 'num_100':
						// Число (не более 100)
						cond = "value != '' && value > 100";
						break;
					case 'date':
						// Дата в формате БД datetime "0000-00-00"
						cond = "value != '' && !/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test(value)";
						break;
					case 'datetime':
						// Дата в формате БД datetime "0000-00-00 00:00:00"
						cond = "value != '' && !/^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/.test(value)";
						break;
					case 'uri':
						// URI
						cond = "/[а-яА-Я#\'\" ]/.test(value)";
						break;
					case 'photo':
						// Расширение фотки (без "Из сети")
						cond = "value != '' && !/jpg|jpeg|gif|png$/.test(value)";
						break;
					case 'email':
						// Валидность e-mail
						cond = "value != '' && !/^[\.\-_A-Za-z0-9]+?@[\.\-A-Za-z0-9]+?\.[A-Za-z0-9]{2,6}$/.test(value)";
						break;
					case 'checked':
						// Переключатель (вкл.)
						cond = "!$(index).get('checked')";
						break;
					case 'sex':
						// Пол
						cond = "!$(index + '_1').get('checked') && !$(index + '_2').get('checked')";
						break;
					case 'pwd':
						// Пароль
						cond = "$('id').get('value') > 0 && value == ''";
						break;
					case 'pwd_confirm':
						// Подтверждение пароля
						cond = "value != '' && value != $(index + '_confirm').get('value')";
						break;
					case 'banners_upload':
						// Баннеры (загружаемый)
						cond = "$('type').get('value') == 1 && value == ''";
						break;
					case 'banners_code':
						// Баннеры (скрипт)
						cond = "$('type').get('value') == 2 && value == ''";
						break;
					case 'banners_url':
						// Баннеры (URL)
						cond = "($('type').get('value') == 1 && !/swf$/.test($('banner').get('value'))) && value == ''";
						break;
					default:
						cond = check.code;
				}
				
			    if (eval(cond)) {
			        error = true;
			        $(errorPrefix + index).set('text', check.text);
			    }
		    });
			if (error) {
				$(errorPrefix + index).setStyle('display', 'block');
				if ($(index)) {
					$(index).className += ' ' + classError;
				}
				result = false;
			}
			else {
				if ($(index)) {
					$(index).className = $(index).className.replace(' ' + classError, '');
				}
				$(errorPrefix + index).setStyle('display', 'none');
			}
			error = false;
		});
		
		return result;
	}
});
