/**
 * @requires js/modules/loading.js
 * @requires js/modules/validate.js
 * @requires js/libs/jQuery/ui/jquery.ui.dialog.js
 */

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

(function($) {
	var preorderPopup = null,
		config = {defaultCommentText : 'Комментарий к предзаказу'},
		productId = null;

	m.preorder = {
		show : function(id) {
			productId = id;
			m.loading.show();

			$.post('/basket/getpreorderform/', {id:id}, function(data) {
				m.loading.hide();
				__setup();

				preorderPopup.html(data.html);
				preorderPopup.dialog('option', 'position', 'center');
				preorderPopup.dialog('option', 'title', data.product.product_name);
				preorderPopup.dialog('open');

				__setupPreorderForm();
			}, 'json');
		}
	}

	function __setupPreorderForm()
	{
		$('#preorder_comment')
			.focus(function(e) {
				if (this.value == config.defaultCommentText) {
					this.value = '';
				}
			})
			.blur(function(e) {
				if (this.value == '') {
					this.value = config.defaultCommentText;
				}
			});

		var conf = m.validate.getConf();
		conf.submitHandler = function() {
			__submitPreorderForm();
		};

		$('#preorder-form').validate(conf);
	}

	function __submitPreorderForm()
	{
		var data = $('#preorder-form').serializeArray();

		$('#preorder-form').css('visibility', 'hidden');
		$('#preorder-intro').css('visibility', 'hidden');

		m.loading.show();
		$.post('/basket/makepreorder/?id=' + productId, data, function(res) {
    		m.loading.hide();
			preorderPopup.html(res.html);

			if (!res.result) {
				__setupPreorderForm();
			}
		}, 'json');
	}

	function __setup()
	{
		if (null === preorderPopup) {
		    preorderPopup = $("#preorder-popup").dialog({
				modal : true,
				title : 'Предзаказ',
				width : 430,
				minHeight : false
		    });
		}
	}
}) (jQuery);
