var submitted = false;

$(document).ready(function()
{
	
	$('#ordercoat').submit(function()
	{
		if(!submitted)
		{
			var submit = $('input[type=submit]',this);
			submit.attr('disabled',true);
			
			var coats={	name:		$('#name',this).val(),
						 			email:	$('#email',this).val(),
						 			phone:	$('#phone',this).val(),
						 			year:  	$('#year',this).val()};
			$('[id^=order_]').each(function()
			{
				var total = $('.total',this).text();
				var coatid = $(this).attr('id').split('_')[1];
				coats['coat['+coatid+']'] = total;
			});
			
			$.getJSON(root+'/whitecoat/_ordercoat',
						 coats,
						 function(o)
						 {
						 	if(o.s)
						 	{
						 		submit.hide();
						 		$('input[type=text]').attr('disabled',true);
						 		$('[id^=removecoat_]').remove();
						 		submitted = true;
						 	}
						 	else
						 	{
								submit.attr('disabled',false);			 		
						 	}
						 	error('.error',o.msg);
						 });
		}
		return false;
	});
	
	$('#ordercode input[type=text]').focus(function()
	{
		if($(this).val()=='Enter your order code here...')
		{
			$(this).val('').removeClass('grey');
		}
	});
	$('#ordercode input[type=text]').blur(function()
	{
		if($(this).val()=='')
		{
			$(this).val('Enter your order code here...').addClass('grey');
		}
	});
	
	reg_coatadd();
});

function reg_coatadd()
{
	$('[id^=coat_]').click(function()
	{
		var self = this;
		var parse = $(this).attr('id').split('_');
		var id = parse[1];
		var gender = parse[2];
		var length = parse[3];
		var L = parse[4];
		var cost = parse[5];
		
		if($('#order_'+id).size())
		{
			var num = $('#order_'+id+' .total').text();
			$('#order_'+id+' .total').text(++num);
		}
		else
		{
			var summary = ((parseInt(gender))?'men':'women')+' '+length+' '+((parseInt(L))?'L':'')
			var mf = (parseInt(gender))?'m':'f';
			var li = $('<li><em><span class="total">1</span>x</em> <span class="cost green">$'+cost+'</span> <span class="desc '+mf+'">'+summary+'</span> <a href="#" class="remove" id="removecoat_'+id+'">remove</a></li>');
			li.attr('id','order_'+id);
			$('#ordersummary').append(li);
		}
		reg_remove();
		var currentcost = $('#totalamount').text();
		$('#totalamount').text(parseInt(currentcost)+parseInt(cost));
		return false;
	});
}
function reg_remove()
{
	$('[id^=removecoat_]').each(function()
	{
		$(this).unbind('click').click(function()
		{
			var total = $(this).parents('li').find('.total');
			var totalsum = parseInt(total.text());
			if(totalsum-1) total.text(--totalsum);
			else $(this).parents('li').remove();
			
			var currentcost = $('#totalamount').text();
			var cost = $('[id^=coat_'+$(this).attr('id').split('_')[1]+']').attr('id').split('_')[5];
			$('#totalamount').text(parseInt(currentcost)-parseInt(cost));
			return false;
		});
	});
}
function coatmanager()
{
	
}