$(document).ready(function(){
	var orderUrl = '/order_new/';
	
	$('#order-form form').live('submit', function(){
		var uidName = '', uidValue = '';
		$('input.real', $(this)).each(function(){
			uidName = $(this).attr('name');
			uidValue = $(this).attr('value');
		});
		var formData = $(this).serialize() + '&' + 'ajax=1' + '&' + uidName + '=' + uidValue;
		$.ajax({
			url: orderUrl,
			type: 'POST',
			cache: false,
			data: formData,
			contentType: 'application/x-www-form-urlencoded',
			beforeSend: function(){
				$('#order-form input[type="submit"]').attr('disabled', 'disabled');
				$('#order-form .order').fadeTo('fast', 0.5);
			},
			success: function(data){
				if(data.html){
					$('#order-form').html(data.html);
				}
				else{
					$('#order-form').remove();
					showTooltip(data);
				}
			},
			error: function(xhr){
				//console.log(xhr);
			},
			dataType: 'json'
		});
		return false;
	});
	$('#productlist form, .vborder form').live('submit', function(){
		var formText = $(this).parent().find('h4 a, h3').first().text();
		if($('#order-form').length == 0){
			$('body').append('<div id="order-form" />');
			$.ajax({
				url: orderUrl,
				data: {ajax: 1, url: window.location.pathname},
				success: function(data){
					$('#order-form').html(data.html);
					$('#order-form textarea').text(formText);
				},
				dataType: 'json'
			});
		}
		else{
			$('#order-form textarea').text(formText);
		}
		$('#order-form').fadeIn('fast');
		return false;
	});
	$('#order-form .mask, #tooltip-button').live('click', function(){
		$(this).parent().hide();
	});
	$('#order-form .close-button').live('click', function(){
		$('#order-form').hide();
	});
});

function showTooltip(data){
	if($('#tooltip').length == 0){
		$('body').append('<div id="tooltip" />');
		$('#tooltip').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').stop().fadeIn().show().delay(5000).fadeOut(5000, 0);
}

