/*submenu*/
$(document).ready(function(){
	$("#yearssel select").live("change",function(){
		var url = location.href;
		var re = /\.ru\/([^\/]+)/;
		var newstr = re.exec(url);
		var nurl = "/"+newstr[1]+"/"+$(this).val()+"/";
		location.replace(nurl);
	});
/*
	$("#teplo-stroy, #teplo-tech").live("click",function(){
		var cid = $(this).attr("id");
		if(!$("#p-izol").hasClass("switch-izol") && cid=='teplo-tech'){
			$("#p-izol").addClass("switch-izol");
		} else {
			if(cid!='teplo-tech'){
				$("#p-izol").removeClass("switch-izol");
			}
		}
	});
*/
	$('td a.submit').click(function(){
		var product = 'Хочу купить ' + $(this).parent().find('a:first').text();
		initForm(product);
		return false;
	});
	$('.production-buttons .orderTo:first').submit(function(){
		var product = 'Хочу купить ' + $('h1').text();
		initForm(product);
		return false;
	});
	$('#order-form form').live('submit', function(){
		var formData = $(this).serialize() + '&' + 'ajax=1';
		$.ajax({
			url: '/order/',
			type: 'POST',
			cache: false,
			data: formData,
			contentType: 'application/x-www-form-urlencoded',
			beforeSend: function(){
				$('#sbtn').attr('disabled', 'disabled');
				$('#my-form').fadeTo('fast', 0.5);
			},
			success: function(data){
				if(data.error){
					$('#order-form').html(data.html).append('<div class="mask" />');
					$('#my-form').append('<div class="close-button" title="Закрыть" />');
				}
				else{
					$('#order-form').html('').hide();
					if($('#tooltip').length == 0){
						$('body').append('<div id="tooltip" />');
						$('#tooltip').append('<div id="tooltip-wrapper" />');
						$('#tooltip-wrapper').append('<div id="tooltip-header" />', '<div id="tooltip-body" />', '<div id="tooltip-button" />');
						$('#tooltip-button').text('OK');
					}
					$('#tooltip-header').text(data.header);
					$('#tooltip-body').html('<p>' + data.message + '</p>');
					$('#tooltip').show().delay(5000).fadeTo(5000, 0);
				}
			},
			error: function(xhr){
				//console.log(xhr);
			},
			dataType: 'json'
		});
		return false;
	});
	$('#order-form .mask, #tooltip-button').live('click', function(){
		$(this).parent().hide();
	});
	$('#my-form .close-button').live('click', function(){
		$('#order-form').hide();
	});
});

function initForm(product){
	if($('#order-form').length == 0){
		$('body').append('<div id="order-form" />');
	}
	$.ajax({
		url: '/order/',
		data: {ajax: 1},
		success: function(data){
			$('#order-form').html(data.html).append('<div class="mask" />').fadeIn('fast');
			$('#my-form').append('<div class="close-button" title="Закрыть" />');
			$('#my-form textarea').text(product);
		},
		dataType: 'json'
	});
}

