/*	Обработка форм */
/*	Опирается на html структуру, описываемую при инициализации скрипта	*/
/*	Необходимые для инициализации параметры:
	prefix - префикс в id html-элементов, на которые опирается скрипт
	fieldNames - объект описывающий поля и способы проверки полей
	...
	(см. пример rus.xslt/_actions.xslt)
	
	todo: логика отправки формы зашита жёстко. нужно сделать, чтобы можно было более гибко задавать последовательность состояний отправки формы.
	Примечание: Для загрузки капчи может быть использован CaptchaLoader
	
*/

var Forms = function (params) {
	Object.copyParams(this, params);
	this.prefix += '_';

	this.container = $(this.prefix + 'form');
	var types = ['INPUT', 'SELECT', 'TEXTAREA', 'HIDDEN', 'RADIO', 'CHECKBOX'];

	this.formFields = [];
	for (var j = 0, l1 = types.length; j < l1; j++) {
		var type = types[j];
		var currItems = $$(this.container, type);
		for (var k = 0, l2 = currItems.length; k < l2; k++) {
			var field = currItems[k];
			this.formFields.push(field);
			if (field.type == 'submit' && !this.submitButton) {
				this.submitButton = field;
			}

			if (field.name == 'captcha') {
				this.captcha = field;
			}
		}
	}

	this.requiredFields = {};
	for (var fieldName in this.fieldNames) {
		this.addField(fieldName, this.fieldNames[fieldName], 1);
	}
	Event.add(this.submitButton, 'click', this.formPrepare.bind(this));
	if (this.use_captcha && $(this.prefix + 'captcha_preload')) {
		Event.add($(this.prefix + 'captcha_preload'), 'click', this.captchaPreload.bind(this));
	}

	this.AJAX = new Ajax(this.fAjax,
		{
			_this		: this,
			container	: this.container,
			spinner		: $(this.prefix + 'sp'),
			fUrlPrepare	: this.fUrlPrepare,
			fAfter		: this.fAfter
		}
	);

	return this;
};

Forms.prototype = {
	addField: function (fieldName, params, exist) {
		var types = ['INPUT', 'SELECT', 'TEXTAREA'];
		for (var j = 0, l1 = types.length; j < l1; j++) {
			var type = types[j];
			var currItems = $$(this.container, type);
			for (var k = 0, l2 = currItems.length; k < l2; k++) {
				var field = currItems[k];
				if (field.name == fieldName && !exist) {
					this.formFields.push(field);
				}
			}
		}

		if (params) {
			this.fieldNames[fieldName] = params;

			for (var i = 0, l1 = this.formFields.length; i < l1; i++) {
				if (this.formFields[i].name == fieldName) {
					field = this.formFields[i];
				}
			}

			this.requiredFields[fieldName] = {};

			if (/(radio|checkbox)/.test(field.type)) {
				this.requiredFields[fieldName].fields = [];
				var tmpArr = $$(this.container, field.tagName);
				for (var i = 0, l2 = tmpArr.length; i < l2; i++) {
					var tmpEl = tmpArr[i];
					if (tmpEl.name == fieldName) {
						this.requiredFields[fieldName].fields.push(tmpEl);
						Event.add(tmpEl, 'click', this.replaceLabel.bind(this, fieldName, false));
						Event.add(tmpEl, 'focus', this.replaceLabel.bind(this, fieldName, false));
					}
				}
			}
			else {
				this.requiredFields[fieldName].fields = [field];
			}
			this.requiredFields[fieldName].valid = false;
			if (field.type != 'submit') {
				Event.add(field, 'click', this.replaceLabel.bind(this, fieldName, false));
				Event.add(field, 'focus', this.replaceLabel.bind(this, fieldName, false));
			}
		}
	},
	
	captchaPreload: function (e) {
		var el = Event.elementEqual(e, 'LI');
		if (!el) { return false; }
		if (!this.container.offsetHeight && /clear\.gif/.test($(this.prefix + 'captcha_img').src)) {
			this.AJAX.nospinner = true;
			this.AJAX.run(e);
		}
	},
	
	captchaManualPreload: function () {
		this.AJAX.run(1, 1);
	},
	// serializer functions
	serialize: function () {
		var aSerializedFields = [];
		for (var i = 0, l = this.formFields.length; i < l; i++) {
			var field = this.formFields[i];
			if (field.type && !/(button)/.test(field.type)) {
				var sField = this.serializeField(field);
				if (sField) {
					aSerializedFields.push(sField);
				}
			}
		}

		return aSerializedFields.join('&');
	},

	serializeField: function (field) {
		if (field.tagName == 'SELECT') {
			return field.name + '=' + field.value;
		} else {
			switch(field.type) {
				case 'checkbox':
					return field.checked ? field.name + '=' + (this.serializeCheckBoxValue ? field.value : field.checked) : '';
				case 'radio':
					return field.checked ? field.name + '=' + field.value : '';
				default: //for text|textarea
					return field.value ? field.name + '=' + escape(field.value) : '';
			}
		}
	},

	// validator functions
	validateHandler: function (event) {
		var element = Event.element(event);
		var type = element.type;
		switch(element.tagName) {
			case 'INPUT':
				if (type == 'checkbox' || type == 'radio') {
					this.countSwitchers(element);
				} else if (type == 'text' || type == 'password') {
					this.validateTextField(element, 0);
				}
			break;
			case 'TEXTAREA':
				this.validateTextField(element, 1);
			break;
			case 'SELECT':
				this.validateSelect(element);
			break;
		}
		this.validate();
	},

	validateTextField: function (element, isTextArea) {
		//this.requiredFields[element.name].valid = (element.value.replace(/(^\s+|\s+$)/, '').length && this.validateLength(element.name, element.value.length));

		// Validate empty
		if (element.disabled) {
			this.requiredFields[element.name].valid = 1;
			return;
		}
		if (this.fieldNames[element.name].errors.empty) {
			this.requiredFields[element.name].valid = element.value.replace(/(^\s+|\s+$)/, '').length;
			if (isTextArea) {
				this.requiredFields[element.name].size = element.value.length;
			}
		} else {
			this.requiredFields[element.name].valid = 1;
		}
	},

	countSwitchers: function (element) {
		var counter = 0;
		for (var i = 0, l = this.requiredFields[element.name].fields.length; i < l; i++) {
			var field = this.requiredFields[element.name].fields[i];
			if (field.disabled) {
				counter++;
				return;
			}
			if (field.checked) {
				counter++;
			}
		}

		this.validateSwitcher(element.name, counter);
	},

	validateSwitcher: function (name, counter) {
		this.requiredFields[name].valid = counter ? true : false;
	},

	validateSelect: function (element) {
		var count = 0;
		for (var i = 0, l = element.options.length; i < l; i++) {
			var option = element.options[i];
			if (option.value.length && option.selected) {
				count++;
			}
		}
		this.requiredFields[element.name].valid = count ? true : false;
	},

	validateLength: function (name, length) {
		var field = this.fieldNames[name];

		if (field.min && field.min > length) {
			return false;
		} else if (field.max && field.max < length) {
			return false;
		} else {
			return length;
		}
	},

	formPrepare: function (e) {
		Event.cancelEvent(e);
		for (var field in this.requiredFields) {
			if (this.requiredFields[field].fields.length == 1) {
				this.validateElementByTagName(this.requiredFields[field].fields[0]);
			} else {
				var counter = 0;
				for (var j = 0, l = this.requiredFields[field].fields.length; j < l; j++) {
					var element = this.requiredFields[field].fields[j];
					if (element.checked) {
						counter++;
					}
					this.validateElementByTagName(element);
				}
				this.validateSwitcher(field, counter);
			}
		}
		this.validate();
	},

	validateElementByTagName: function (element) {
		switch(element.tagName) {
			case 'INPUT':
				if (element.type == 'checkbox' || element.type == 'radio') { // && element.checked) {
					this.validateSwitcher(element.name, 1);
				} else if (element.type == 'text' || element.type == 'password') {
					this.validateTextField(element, 0);
				}
			break;
			case 'TEXTAREA':
				this.validateTextField(element, 1);
			break;
			case 'SELECT':
				this.validateSelect(element);
			break;
		}
	},

	validate: function () {
		var count = 0;
		for (var field in this.requiredFields) {
			//alert(field);
			if (!this.requiredFields[field].valid) {
				count++;
				this.showError(field);
			} else {
				this.replaceLabel(field);
			}
		}

		if (!count) {
			this.AJAX.run();
		} else {
			//если есть ошибки в заполнении полей
			if (this.fields_error) {
				this.fields_error();
			}
		}
	},

	showError: function (field, errType) {
		var message = this.fieldNames[field].errors[errType || 'empty'];

		if (!this.requiredFields[field].label) {
			this.requiredFields[field].label = $('lbl_' + this.prefix + field).innerHTML;
		}

		this.replaceLabel(field, message);
	},

	replaceLabel: function (field, message) {
		var label = $('lbl_' + this.prefix + field);

		if (message) {
			label.innerHTML = message;
		} else if (this.requiredFields[field].label){
			label.innerHTML = this.requiredFields[field].label;
		}

		Object.Class.replace(label, 'alert', '', message);
	},

	clearForm: function () {
		for (var i = 0, l = this.formFields.length; i < l; i++) {
			var field = this.formFields[i];
			if (field.type != 'submit' && field.type != 'radio' && field.name != 'feedback_type') {
				field.value = '';
			}
		}
	},

	showAjaxError: function (errors) {
		for (var error in errors) {
			this.showError(error, errors[error]);
		}
		if (this.captcha) {
			this.captcha.value = '';
		}
	},

	formDoneSH: function (status) {
		Object.Class.replace(this.container, 'invisible', '', status);
		Object.Class.replace($(this.prefix + 'done'), '', 'invisible', status);
	}
};

var FromWithCaptcha = {
	init: function () {
		if ($(this._this.prefix + 'newform')) {
			Event.add($(this._this.prefix + 'newform'), 'click', this.run.bindAsEventListener(this, true));
		}
	},
	
	run: function (e, clear) {
		this.url = this.fUrlPrepare(e);
		if (e) {
			Event.cancelEvent(e);
			if (this.started) { return; }
			this.url += '?newform=1' + (clear ? '&clear' : '');
			this.method = 'GET';
			this.nospinner = clear ? false : true;
			this.go();
		} else {
			this.nospinner = false;
			this.method = 'POST';
			this.go(this._this.serialize());
		}
		this.started = true;
		this._this.submitButton.disabled = true;
	},

	after: function (response) {
		this._this.formDoneSH(!(response.newform || response.error));
		if (response.error) {
			this._this.showAjaxError(response.messages);
		}
		if (response.clear) {
			this._this.clearForm();
		}
		this._this.submitButton.disabled = false;
		
		if (!response.error && this.fAfter) {
			this.fAfter.bind(this)(response);
		}
		
		if (this._this.use_captcha && response.captcha) {
			$(this._this.prefix + 'captcha_img').src = response.captcha[0];
			$(this._this.prefix + 'captcha_md5').value = response.captcha[1];
			if (!response.error && this.fAfter) {
				this.fAfter.bind(this)(response);
			}
			this._this.submitButton.focus();
		}
		this.spinnerSH(0);
		this.started = false;
	}
};



var FormWithoutCaptcha = {
	init: function () {
		if ($(this._this.prefix + 'newform')) {
			Event.add($(this._this.prefix + 'newform'), 'click', this.run.bindAsEventListener(this, true));
		}
	},
	
	run: function (e, clear) {
		this.url = this.fUrlPrepare(e);
		this.asynchronous = false;
		if (e) {
			Event.cancelEvent(e);
			if (this.started) { return; }
			this.url += '?newform=1' + (clear ? '&clear' : '');
			this.method = 'GET';
			this.nospinner = clear ? false : true;
			this.go();
		} else {
			this.nospinner = false;
			this.method = 'POST';
			this.go(this._this.serialize());
		}
		this.started = true;
		this._this.submitButton.disabled = true;
	},

	after: function (response) {
		this._this.formDoneSH(!(response.newform || response.error));
		if (response.error) {
			this._this.showAjaxError(response.messages);
		}
		if (response.clear) {
			this._this.clearForm();
		}
		this._this.submitButton.disabled = false;
		
		$('question_name').value = fields.name;
		$('question_e_mail').value = fields.e_mail;
		$('question_message').value = fields.message;
		
		if (this._this.use_captcha) {
			if(response.captcha)	{
				$(this._this.prefix + 'captcha_block').style.display = 'block';
				$(this._this.prefix + 'captcha_img').src = response.captcha[0];
				$(this._this.prefix + 'captcha_md5').value = response.captcha[1];
				if (!response.error && this.fAfter) {
					this.fAfter.bind(this)(response);
				}
				this._this.submitButton.focus();
			}	else	{
				//alert('captcha not found in json response');
			}
		}	else	{
			//alert('captcha not use');
		}

		this.spinnerSH(0);
		this.started = false;
	}
};


var FormWithoutCaptcha12Tigers = {
	init: function () {},
	
	run: function (e, clear) {
		this.url = this.fUrlPrepare(e);
		this.asynchronous = false;
		this.nospinner = false;
		this.method = 'POST';
		this.go(this._this.serialize());
		this._this.submitButton.disabled = true;
	},

	after: function (response) {
		//this._this.formDoneSH(!(response.newform || response.error));
		document.location.href = '/docs/ny2010/your12tigers.html?a=' + response.count;
		//console.log(response.count);

		this._this.submitButton.disabled = false;

		this.spinnerSH(0);
	}
};


var QuestionFormWithoutCaptcha = {
	init: function () {
		if ($(this._this.prefix + 'newform')) {
			Event.add($(this._this.prefix + 'newform'), 'click', this.run.bindAsEventListener(this, true));
		}
	},
	
	run: function (e, clear) {
		this.url = this.fUrlPrepare(e);
		this.asynchronous = false;
		if (e) {
			Event.cancelEvent(e);
			if (this.started) { return; }
			this.url += '?newform=1' + (clear ? '&clear' : '');
			this.method = 'GET';
			this.nospinner = clear ? false : true;
			this.go();
		} else {
			this.nospinner = false;
			this.method = 'POST';
			this.go(this._this.serialize());
		}
		this.started = true;
		this._this.submitButton.disabled = true;
	},

	after: function (response) {
		this._this.formDoneSH(!(response.newform || response.error));
		if (response.error) {
			this._this.showAjaxError(response.messages);
		}
		if (response.clear) {
			this._this.clearForm();
		}
		this._this.submitButton.disabled = false;
		
		if (this._this.use_captcha) {
			if(response.captcha)	{
				$(this._this.prefix + 'captcha_block').style.display = 'block';
				$(this._this.prefix + 'captcha_img').src = response.captcha[0];
				$(this._this.prefix + 'captcha_md5').value = response.captcha[1];
				if (!response.error && this.fAfter) {
					this.fAfter.bind(this)(response);
				}
				this._this.submitButton.focus();
			}	else	{
				//alert('captcha not found in json response');
			}
		}	else	{
			//alert('captcha not use');
		}
		
		
		/*	дикий страннокод:
			восстановление значений в полях, после их очистки при получении капчи
			/26.11.09/
		*/
	
		var _fieldnames = ['name', 'e_mail', 'message', 'country', 'city', 'occupation', 'smi_name', 'sminame', 'surname', 'position', 'phone', 'birth', 'passport', 'place']
		for (var i = 0; i < _fieldnames.length; i++) {
			if (qfields[_fieldnames[i]]) {
				$('question_' + _fieldnames[i]).value = qfields[_fieldnames[i]]
			}
		}
		

		$('question_loadcaptcha').value = qfields.question_loadcaptcha;
	
		//alert('123');
		if(response.error)	{
			if(response.messages.captcha)	{}
			else	{
				/*	Смена кнопки	*/
				$(this._this.prefix + 'send').style.display='none';
				$(this._this.prefix + 'loadcaptcha').style.display='inline';
				/*	Смена рабочей области	*/
				$(this._this.prefix + 'captcha_block').style.display='none';
				$(this._this.prefix + 'workspace').style.display='block';
				$(this._this.prefix + 'paragraph').style.display='block';				
			}
		}	else	{
			if(!response.newform)	{
				//alert('ok');
			}
		}
		/*	/страннокод	*/			
			
		this.spinnerSH(0);
		this.started = false;
	}
};

var PlagiatFormWithoutCaptcha = {
	init: function () {
		if ($(this._this.prefix + 'newform')) {
			Event.add($(this._this.prefix + 'newform'), 'click', this.run.bindAsEventListener(this, true));
		}
	},
	
	run: function (e, clear) {
		this.url = this.fUrlPrepare(e);
		this.asynchronous = false;
		if (e) {
			Event.cancelEvent(e);
			if (this.started) { return; }
			this.url += '?newform=1' + (clear ? '&clear' : '');
			this.method = 'GET';
			this.nospinner = clear ? false : true;
			this.go();
		} else {
			this.nospinner = false;
			this.method = 'POST';
			this.go(this._this.serialize());
		}
		this.started = true;
		this._this.submitButton.disabled = true;
	},

	after: function (response) {
		this._this.formDoneSH(!(response.newform || response.error));
		if (response.error) {
			this._this.showAjaxError(response.messages);
		}
		if (response.clear) {
			this._this.clearForm();
		}
		this._this.submitButton.disabled = false;
		
		
		if (this._this.use_captcha) {
			if(response.captcha)	{
				$(this._this.prefix + 'captcha_block').style.display = 'block';
				$(this._this.prefix + 'captcha_img').src = response.captcha[0];
				$(this._this.prefix + 'captcha_md5').value = response.captcha[1];
				if (!response.error && this.fAfter) {
					this.fAfter.bind(this)(response);
				}
				this._this.submitButton.focus();
			}	else	{
				//alert('captcha not found in json response');
			}
		}	else	{
			//alert('captcha not use');
		}
		
		
		/*	страннокод	*/
		$('plagiat_name').value = plagiat_fields.name;
		$('plagiat_e_mail').value = plagiat_fields.e_mail;
		$('plagiat_message').value = plagiat_fields.message;
		document.plagiat_form.smi_or_iuser[plagiat_fields.smi_or_iuser].checked=true;

		$('plagiat_url').value = plagiat_fields.url;
		$('plagiat_url_original').value = plagiat_fields.url_original;

		$('plagiat_loadcaptcha').value = plagiat_fields.plagiat_loadcaptcha;
	
		if(response.error)	{
			if(response.messages.captcha)	{}
			else	{
				/*	Смена кнопки	*/
				$(this._this.prefix + 'send').style.display='none';
				$(this._this.prefix + 'loadcaptcha').style.display='inline';
				/*	Смена рабочей области	*/
				$(this._this.prefix + 'captcha_block').style.display='none';
				$(this._this.prefix + 'workspace').style.display='block';
				$(this._this.prefix + 'paragraph').style.display='block';				
			}
		}	else	{
			if(!response.newform)	{
				//alert('ok');
			}
		}
		/*	/страннокод	*/			
		
		
		this.spinnerSH(0);
		this.started = false;
	}
	

};

var FipFormWithoutCaptcha = {
	init: function () {
		if ($(this._this.prefix + 'newform')) {
			Event.add($(this._this.prefix + 'newform'), 'click', this.run.bindAsEventListener(this, true));
		}
	},
	
	run: function (e, clear) {
		this.url = this.fUrlPrepare(e);
		this.asynchronous = false;
		if (e) {
			Event.cancelEvent(e);
			if (this.started) { return; }
			this.url += '?newform=1' + (clear ? '&clear' : '');
			this.method = 'GET';
			this.nospinner = clear ? false : true;
			this.go();
		} else {
			this.nospinner = false;
			this.method = 'POST';
			this.go(this._this.serialize());
		}
		this.started = true;
		this._this.submitButton.disabled = true;
	},

	after: function (response) {
		this._this.formDoneSH(!(response.newform || response.error));
		if (response.error) {
			this._this.showAjaxError(response.messages);
		}
		if (response.clear) {
			this._this.clearForm();
		}
		this._this.submitButton.disabled = false;
		
		if (this._this.use_captcha) {
			if(response.captcha) {
				//$(this._this.prefix + 'captcha_block').style.display = 'block';
				$(this._this.prefix + 'captcha_img').src = response.captcha[0];
				$(this._this.prefix + 'captcha_md5').value = response.captcha[1];
				if (!response.error && this.fAfter) {
					this.fAfter.bind(this)(response);
				}
				this._this.submitButton.focus();
			}	else	{
				//alert('captcha not found in json response');
			}
		}	else	{
			//alert('captcha not use');
		}

		this.spinnerSH(0);
		this.started = false;
	}
};




function setPressSubThemes (response) {
	if (response.subscribe_text) {
	} else {
		$('pr_themes').innerHTML = response.themes;
		this._this.addField('theme', { errors: {empty: 'Темы не указаны'} });
	}
}

/*	Загрузчик капчи */
var CaptchaLoader =	{
	
	method: 'post',
	ajaxData: '1',

	loadCaptcha: function(url, prefix)		{
		this.prefix = prefix;
		Object.Class.replace($(this.prefix + '_sp'), 'visible', '', 1);
		this.doRequest(url);
		return false;
	},
	
	doRequest:	function(url)	{
		this.AJAX = new Ajax(null, null); // оператор антибред
		this.AJAX.getTransport();
		this.AJAX.transport.open(this.method, url, true);	
		this.AJAX.transport.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		this.AJAX.transport.onreadystatechange = function () {
			if (this.AJAX.transport && this.AJAX.transport.readyState == 4 && this.AJAX.transport.status == 200) {
				this.responseHandler(this.AJAX.transport.responseText);
			}
		}.bind(this);

		this.AJAX.transport.send(this.ajaxData);
//		this.AJAX.transport.send(null);

	},
	
	responseHandler:	function(response)	{
		Object.Class.replace($(this.prefix + '_sp'), 'visible', '', 0);
		eval(response);
		$(this.prefix + '_captcha_img').src = response.captcha[0];
		$(this.prefix + '_captcha_md5').value = response.captcha[1];
	}

};
