$(document).ready(function () {
	$('[action]').click(function() {
		if (this.tagName == 'FORM') {
			return true;
		} else {
			order($(this).attr('action'));
			return false;
		}
	});
});

(function () {
    var genCfgDialog = function () {
        return '\n\
<div style="position: relative;">\n\
<embed src="/files/config/configurator.swf"\n\
       quality="high"\n\
       bgcolor="#ffffff"\n\
       width="735"\n\
       height="701"\n\
       name="cite"\n\
       base="/files/config/"\n\
       allowScriptAccess="sameDomain"\n\
       type="application/x-shockwave-flash"\n\
       wmode="opaque"\n\
       pluginspage="http://www.macromedia.com/go/getflashplayer" />\n\
</div>\n\
        ';
    }

	var genDialog = function (type, comment) {
		return '\n\
<form method="post" action="/mail.php">\n\
	<div class="order-floating-block">\n\
		<span>Имя</span>\n\
		<input type="text" name="name" title="Ваше имя" />\n\
		<span>Телефон</span>\n\
		<input type="text" name="phone" title="Ваш телефон" />\n\
		<span>Комментарии</span>\n\
		<textarea name="comment" title="Комментарий">{comment}</textarea>\n\
		<input type="hidden" name="type" value="{type}" />\n\
		<input type="submit" class="button" value="{text}" onclick="return sendForm(this, 1);" />\n\
	</div>\n\
</form>\n\
		'
		.replace(/{comment}/, comment)
		.replace(/{type}/,    type)
		.replace(/{text}/,    (type == 'garbage-collector' ? 'Вывоз мусора' : type == 'call-measurer' ? 'Заказать звонок' : 'Заказать ванну'));
	}

	var genOrderDialog = function (hidden, text) {
		return '\n\
<form method="post" action="/mail.php">\n\
	<div class="order-floating-block">\n\
		<span>Имя</span>\n\
		<input type="text" name="name" title="Ваше имя" />\n\
		<span>Телефон</span>\n\
		<input type="text" name="phone" title="Ваш телефон" />\n\
		<input type="hidden" name="type" value="{hidden}" />\n\
		<input type="submit" class="button" value="{text}" onclick="return sendForm(this, 1);" />\n\
	</div>\n\
</form>\n\
		'
		.replace(/{hidden}/, hidden || 'order-consult')
		.replace(/{text}/, text || 'Жду звонка!');
	}

	var showDialog = function (type, comment) {
		if (type == 'order-credit') {
			$(genOrderDialog('order-credit', 'Заказать кредит!')).dialog({
				title : "Заказать кредит",
				modal : true
			});
		} else if (type == 'order-consult') {
			$(genOrderDialog()).dialog({
				title : "Заказать консультацию",
				modal : true
			});	
		} else if (type == 'configurator') {
            $(genCfgDialog()).dialog({
                title  : "Конфигуратор",
                width  : 770,
                height : 765,
                resizable : false,
                draggable : false,
                modal  : true
            });
        } else {
			$(genDialog(type, comment)).dialog({
				title : (
					type == 'garbage-collector' ? 'Вывоз мусора' :
					type == 'call-measurer'     ? 'Заказать звонок' :
					                              'Заказать ванну'
				),
				modal : true
			});	
		}
	};

	window.order = function (a, text) {
		if (a == 'order-profile') {
			var elems = $('input[name=profile]');
			for (var k in elems) {
				if (elems[k].checked) {
					showDialog('purchase-windows', 'Я хочу заказать окна профиля ' + elems[k].value)
					return;
				}
			}
		} else {
			showDialog(a, text ? text : '');
		}
	}

    window.showConfigurator = function() {
        showDialog('configurator', '');
    }
})();

function sendForm (button, isDialog) {
	var form   = $(button).parents('form');
	var phoneInput = form.find('input[name=phone]');
	if (!phoneInput.val()) {
		phoneInput
			.css({
				'background-color' : '#f66',
				'border-color'     : '#c00'
			})
			.attr('title', 'Это поле обязательное для заполнения');
		return false;
	}
	var inputs = form.find('input[type!=submit], textarea');
	var values = {};
	for (var i in inputs) {
		values[inputs[i].name] = inputs[i].value;
	}
	var dialog = isDialog ?
		form.dialog({title:"Отправка"}) :
		$('<div></div>').dialog({title:"Отправка", modal:true});
	dialog.html("Отправляется");
	$.ajax({
		type: "POST",
		url: "/mail.php",
		data: values,
		success: function(id) {
			dialog.dialog('option', 'buttons', {
				"Ok": function() {
					$(this).dialog("close");
				}
			}).html(id ?
				"Ваша заявка принята. Номер " + id :
				"Произошла ошибка, заявка не принята"
			);
		}
	});
	return false;
}

function openWebIM (obj) {
	if (navigator.userAgent.toLowerCase().indexOf('opera') != -1 && window.event.preventDefault) {
		window.event.preventDefault();
	}
	obj.newWindow = window.open(
		'http://lite.webim.ru/okna5/webim/client.php?locale=ru', 'webim_',
		'toolbar=0,scrollbars=0,location=0,menubar=0,width=660,height=430,resizable=1'
	);
	if (obj.newWindow == null) {
		return;
	}
	obj.newWindow.focus();
	obj.newWindow.opener = window;
}

function openPrintableContacts (obj) {
	var popupWin = window.open(
		obj.href, 'contacts',
		'toolbar=1,scrollbars=0,location=1,menubar=1,width=820,height=700,top=0,resizable=1'
	);
	popupWin.focus();
}

