/**
 * @requires js/modules/validate.js
 * @requires js/modules/win.js
 * @requires js/libs/jQuery/plugins/jquery.scrollTo.js
 * @requires js/libs/jQuery/plugins/jquery.blink.js
 */

if (typeof(m) == "undefined" || !m) {
	var m = {};
}

(function($) {
	var popupObj = null,
		config = {
			defaultCommentText : 'Ваш комментарий...'
		};


	m.default_catalog_addComment = {
		show : function() {
			__setup();

			popupObj.show();
			$('#comment_author').get(0).focus();
		},

		hide : function() {
			__setup();
			popupObj.hide();
		}
	}

	function __setup()
	{
		if (null === popupObj) {
			popupObj = new m.win('add-comment');
			popupObj.setConfig({isModal : true});

			__setupForm();
		}
	}

	function __setupForm()
	{
		__setupEvents();
		__setupValidate();
	}

	function __setupValidate()
	{
		var conf = m.validate.getConf();
		conf.rules = {
				comment_author : {
					required : true,
					maxlength: 255
				},
				comment_author_email : {
					required : true,
					maxlength: 255,
					email : true
				},
				comment_rating : {
					required : true
				},
				comment_text : {
					commentText : true
				},
				captcha : {
					required : true
				}
		};

		conf.submitHandler = function(form) {
			__submitForm();
		};

		$.validator.addMethod("commentText", __validateCommentText, $.validator.messages.required);
		$('#add-comment-form').validate(conf);
	}

	function __submitForm()
	{
		var form = $('#add-comment-form');
		var action = form.attr('action');
		var data = form.serializeArray();

		form.css('visibility', 'hidden');
		popupObj.showLoading();

		$.post(action, data, __submitResult, 'json');
	}

	function __submitResult(data)
	{
		popupObj.hideLoading();
		popupObj.setBody(data.form_html);
		__setupForm();

		if (data.result) {
			popupObj.hide();
			$('#comments').get(0).innerHTML = data.comments_html;
			m.default_catalog_product.setupComments();
			$.scrollTo('#comments');
//			$.scrollTo($('#comment-' + data.comment_id).get(0));
			$('#comment-' + data.comment_id).blink();
		}
	}

	function __validateCommentText(val)
	{
		if (val == '' || val == config.defaultCommentText) {
			return false;
		} else {
			return true;
		}
	}

	function __setupEvents()
	{
		$('#comment_text')
			.focus(function(e) {
				if (this.value == config.defaultCommentText) {
					this.value = '';
				}
			})
			.blur(function(e) {
				if (this.value == '') {
					this.value = config.defaultCommentText;
				}
			});
	}
}) (jQuery);
