function toggle_value($name,$value)
{
	if($("input[name='"+$name+"']").val()==$value)
		$("input[name='"+$name+"']").val('');
	else if($("input[name='"+$name+"']").val()=='')
		$("input[name='"+$name+"']").val($value)
}	

function delete_cart_item(item_id)
{
	$('#item_'+item_id).remove();
	
	$.post('/cart_actions.php',{action:'delete',pid:item_id},function(data)
	{
		$('#cart_num').text(data.cart_num);
		if($('#total').length)
			$('#total').text(data.total);
		if(parseInt(data)<1)
		{
			$('.checkout').remove();
			window.location="/cart";
		}
	},'json');
	return false;
}

function update_cart_item(pid)
{
	quant = $('#quantity_'+pid).val();
	if(quant<1)
		delete_cart_item(pid);
	$.post('/cart_actions.php',{pid:pid,action:'update',quantity:quant},function(data)
	{
		$('#price_'+pid).text(data.price);
		$('#cart_num').text(data.cart_num);
		if($('#total').length)
			$('#total').text(data.total);
	},'json');
	return false;
}

function option_dialog(id)
{
	$('#'+id).dialog('open');
	return false;
}

function add_to_cart(pid)
{
	var option_values = [];
	var option_ids = [];
	if($('.'+pid+'_option').length)
	{
		$('.'+pid+'_option').each(function()
		{
			tname = $(this).attr('name');
			pos = tname.indexOf('_')+1;
			oi = tname.substr(pos);
			option_ids.push(oi);
			ov = $('input[name='+tname+']:checked').val();

			if(!ov || ov=='undefined')
				ov = $('#'+tname).val();
			option_values[oi] = ov;
		});
	}
	$.post('/cart_actions.php',{pid:pid,action:'add',ov:option_values},function(data)
	{
		//alert(data);
		window.location="/cart";
	});
}

function add_options(pid)
{
	$.post('/cart_actions.php',{pid:pid,action:'options'},function(data)
	{
		window.location=data.url;
		alert(data.alert);
	},'json');
}

function checkout(link)
{
	method = $('input[name=one]:checked').val();
	var sd = $('#ship_dest').val();
	var sm = $('#ship_meth').val();

	$.post('/add_ship.php',{sd:sd,sm:sm},function(data)
	{
		if(sd!='0' && sm!='0')
		{
			if(method==undefined)
				alert('Please select a payment method.');
			else if(method=='cc')
				//window.location=link;
				_gaq.push(['_link', link]);
			else if(method=='phone')
				window.location='/payment/phone';
			else if(method=='pp')
				window.location='/payment/pp';
			else if(method=='amex')
				window.location='/payment/amex';
			else if(method=='wu')
				window.location='/payment/wu';
			else if(method=='mo')
				window.location='/payment/mo';
			else
				alert('We currently only have phone and credit card payments set up.');
			return false;
		}
		else if(sd=='0')
		{
			alert('Please select a shipping destination.');
			$('#ship_dest').css({'color':'red'}).focus();
			return false;
		}
		else if(sm=='0')
		{
			alert('Please select a shipping method.');
			$('#ship_meth').css({'color':'red'}).focus();
			return false;
		}

	});
}
