$(document).ready(function(){
	$(".roundbutton").corner("5px");
	
	$("#view_rewards_balance").click(function(){
		$('#rewards_balance').dialog('open');
	});
	
	$("#rewards_balance").dialog({
		bgiframe: false, autoOpen: false, height: 450, width:550, modal: true, resizable:false
    });
	
	$("#redeem").click(redeem_rewards);
	
	function redeem_rewards(){
		redeem_button = this;
		
		if($(redeem_button).html() == 'Redeem Points'){
			$(redeem_button).html('<img src="/media/default/images/loading.gif" height="15px">');
			
			$.getJSON('/cart/redeem', function(data) {
				if(data.status == 'success'){
					$(redeem_button).html("Redeemed <img src='/media/default/images/icons/tick.png'>");
					$('#customer_points_message').hide();
					$('#customer_points_message_redeem').html("You have redeemed your points for Spice Credit. Don't forget to apply your credit on the next screen!");
				} else {
					$(redeem_button).html('Redeem Points');
				}
			});
		}
	}
	
	$(".optin").click(function(){
		$("#dialog").dialog('open');
	});
	
	$("#continue").click(function(){
		var logged_in = $("#duplicate_message").attr('signed_in');
		var product_id = "";
		$("#dup_message").empty();
		$(".quantity_box").each(function(){
			var qty = $(this).val();
			var duplicate = $(this).attr("duplicate");
			
			if (qty > 1 || duplicate == 'true')
			{
				$("#duplicates").val("true");
				var product_id = $(this).attr('product_id');
				
				$("#dup_message").append("<tr><td>" + qty + "</td><td>" + $("#"+product_id+"_item_title").html() + "</td></tr>");
			}
		});

		if ($("#duplicates").val() == 'true')
		{
			$("#duplicate_message").dialog('open')
		}
		
		var dup = $("#duplicates").val();
		if (dup == 'false')
		{
			if (logged_in == 'true')
			{
				window.location = '/billing';
			} else {
				window.location = '/login/cart';
			}
		}
	});

	$("#duplicate_message").dialog({
		bgiframe: true,
		resizable: false,
		height:250,
		width:500,
		modal: true,
		draggable: false,
		autoOpen: false,
		buttons: {
			'Go Back and Change Quantity': function() {
				$(this).dialog('close');
			},
			'Continue': function() {
				var logged_in = $("#duplicate_message").attr('signed_in');
				if (logged_in)
				{
					window.location = '/billing';
				} else {
					window.location = '/login/cart';
				}
			}
		}
	});
				
	$("#dialog").dialog({
		bgiframe: true,
		resizable: false,
		height:250,
		width:500,
		modal: true,
		draggable: false,
		autoOpen: false,
		buttons: {
			'Sign me up!': function() {
				
				var signed_in = $(this).attr("signed_in");
				
				if(signed_in){
					$("#dialog_signup").dialog('open');
				} else {
					window.location = '/newsletter/optin';
				}
				$(this).dialog('close');
			},
			'No Thanks.': function() {
				$(this).dialog('close');
			}
		}
	});
	$("#dialog_signup").dialog({
		bgiframe: true,
		resizable: false,
		height:250,
		width:500,
		modal: true,
		draggable: false,
		autoOpen: false,
		open: function() {
			$.getJSON("/profile/newsletter_subscribe",
				function(data){
					if(data == true){
						$('#dialog_signup_content').hide();
						$('#dialog_signup_content_success').show();
						$('#redeem_optin').html('<div id="redeem">Redeem Points</div>');
						$("#redeem").click(redeem_rewards);
						$('#not_subscribed').hide();
                        $('#subscribed').show();
						subscribed = true;
					} else {
						$('#dialog_signup_content').hide();
						$('#dialog_signup_content_failure').show();
                        $('#not_subscribed').show();
                        $('#subscribed').hide();
					}
			});
		},
		buttons: {
			'Close': function() {
				$(this).dialog('close');
			}
		}
	});
	
	$(".cc_radio").click(function(){
		$(".cc_radio").removeClass("radio_selected").addClass("radio_unselected");
		$(this).removeClass("radio_unselected");
		$(this).addClass("radio_selected");
		
		var id = $(this).attr("id");
		$("#cc_use").val(id);
		if ($(this).attr("id") == 'new')
		{
			$("#card_details").show();
		} else {
			$("#card_details").hide();
		}
	});
	
	$(".address_radio").click(function(){
		$(".address_radio").removeClass("radio_selected").addClass("radio_unselected");
		$(this).removeClass("radio_unselected");
		$(this).addClass("radio_selected");
		var id = $(this).attr("address_id");
		$("#address_id").val(id);
	});
	
	$("#ccv_tip").qtip({
		content: {
			text: false
		},
		position: {
			corner: {
				target: 'topMiddle',
				tooltip: 'bottomMiddle'
			}
		},
		style: 'cream'
	});
	
	$(".cart_duplicate_notice").qtip({
		content: {
			text: 'You have purchased this product before.'
		},
		hide: 'mouseout',
		position: {
			corner: {
				target: 'topMiddle',
				tooltip: 'bottomMiddle'
			}
		},
		style: {
			border: {
				width: 3,
				radius: 3
			},
			padding: 8, 
			textAlign: 'center',
			tip: true, // Give it a speech bubble tip with automatic corner detection
			name: 'red'
		}
	});
	
	$.fn.search = function() {
		return this.focus(function() {
		if( this.value == this.defaultValue ) {
			this.value = "";
		}}
		).blur(function() {
			if( !this.value.length ) {
				this.value = this.defaultValue;
			}
		});
	};
	$("#cc_month").search();
	$("#cc_year").search();
	$(".quantity_box").search();
	
	$("#apply_coupon").click(function(){
		var code = $("#coupon_code").val();
		$.ajax({
			type: 'GET',
			url: '/billing/apply_discount/'+code,
			dataType: 'xml',
			success: function (xml) {
				$(xml).find('shopping_cart').each(function(){
					
					var discount_amount = $(this).find('discount_amount').text();
					var status = $(this).find('status').text();
					var total = $(this).find('total').text();
					var message = $(this).find('message').text();
					
					var credit_amount = $(this).find('credit_amount').text();
					var spice_credit_total = $(this).find('credit_total').text();
					
					if (status == 1)
					{
						$(".order_total_amount.discount").html(discount_amount);
						$("#discount_line").show('fast');
						
						$("#apply_coupon").hide();
						$("#remove_coupon").show('fast');
						
						$("#spice_credit_total").html(spice_credit_total);
						$("#credit_amount").html(credit_amount);
						
						$("#total").html(total);
					} else {
						$("#coupon_message").addClass("checkout_error");
					}
					$("#coupon_message").html(message);
					$("#coupon_message").show('fast');
				})
			}
		});
	});
	
	$("#remove_coupon").click(function(){
		$.ajax({
			type: 'GET',
			url: '/billing/remove_discount',
			dataType: 'xml',
			success: function (xml) {
				$(xml).find('shopping_cart').each(function(){
					var discount_amount = $(this).find('discount_amount').text();
					var status = $(this).find('status').text();
					var total = $(this).find('total').text();
					var message = $(this).find('message').text();
					
					if (status == 1)
					{
						$("#order_total_amount_discount").html(discount_amount);
						$("#discount_line").hide('fast');
						
						$("#remove_coupon").hide();
						$("#apply_coupon").show('fast');
						
						$("#total").html(total);
					}
					$("#coupon_message").html(message);
					$("#coupon_message").show('fast');
				})
			}
		});
	});
	
	$("#apply_credit").click(function() {
		var credit = $("#spice_credit_total").html()
		 
		if (credit != "$0.00")
		{
			$.ajax({
				type: "GET",
				url: "/billing/apply_credit",
				dataType: "xml",
				success: function(xml){
					$(xml).find('shopping_cart').each(function(){
						var total = $(this).find('total').text();
						var credit_amount = $(this).find('credit_amount').text();
						var message = $(this).find('message').text();
						var spice_credit_total = $(this).find('credit_total').text();
						
						$("#spice_credit_total").html(spice_credit_total);
						
						$("#apply_credit").hide();
						$("#remove_credit").show("fast");
						
						$("#credit_message").html(message);
						$("#credit_message").show('fast');
						
						$("#credit_line").show('fast');
						$("#credit_amount").html(credit_amount);
						$("#total").html(total);
					});
				}
			});
		}
	});
	
	$("#remove_credit").click(function(){
		$.ajax({
			type: "GET",
			url: "/billing/remove_credit",
			dataType: "xml",
			success: function(xml){
				$(xml).find('shopping_cart').each(function(){
					var total = $(this).find('total').text();
					var credit_amount = $(this).find('credit_amount').text();
					var message = $(this).find('message').text();
					var spice_credit_total = $(this).find('credit_total').text();
					
					$("#spice_credit_total").html(spice_credit_total);
					$("#remove_credit").hide();
					$("#apply_credit").show("fast");
					
					$("#credit_message").html(message);
					$("#credit_message").show('fast');
					
					$("#credit_line").hide('fast');
					$("#credit_amount").html(credit_amount);
					$("#total").html(total);
					
				});
			}
		});
	});
	
	$("#save_credit_card").click(function(){
		var action = $(this).is(':checked');
		if (action == true)
		{
			var save = "yes";
		} else {
			var save = "no";
		}
		$.ajax({
			type: "POST",
			url: "/billing/cc_save/"+save
		});
	});
	
	$("#checkout").click(function(){
		var address_id = $("#address_id").val();
		var save_card = $("#save_credit_card").val();
		var cc_name = $("#cc_name").val();
		var cc_use = $("#cc_use").val();
		var cc_month = $("#cc_month").val();
		var cc_year = $("#cc_year").val();
		var cc_cvn = $("#security_code").val();
		var cc_number = $("#cc_number").val();

		if (cc_use == 'saved')
		{
			var payment_method = 'use_existing_cc';
		}
        else
        {
            var payment_method = '';
        }
		
		var post_cc_data = "cc_name="+cc_name+"&cc_number="+cc_number+"&cc_cvv="+cc_cvn+"&cc_expiration[month]="+cc_month+"&cc_expiration[year]="+cc_year+"&address_id="+address_id+"&payment_method="+payment_method;
		var valid = true;
		$("#payment_messages").html("&nbsp;");
		var order_total_amount = $("#total").html();
		var quantity_total = $("#quantity_total").html();
		
		if (order_total_amount != '$0.00')
		{
			if (cc_name == '')
			{
				$("#payment_messages").addClass("checkout_error");
				$("#payment_messages").append("You must enter your card's security code to complete your order<br />");
				valid = false;
			}
			if (cc_use == 'new')
			{
				if (cc_cvn == '')
				{
					$("#payment_messages").addClass("checkout_error");
					$("#payment_messages").append("You must enter your card's security code to complete your order<br />");
					valid = false;
				}
				if (cc_month == '' || cc_month == 'Mo' || cc_year == '' || cc_year == 'Year')
				{
					$("#payment_messages").addClass("checkout_error");
					$("#payment_messages").append("You must enter an expiration date to complete your order<br />");
					valid = false;
				}
		
				if (cc_use == 'new' && cc_number == '')
				{
						$("#payment_messages").addClass("checkout_error");
						$("#payment_messages").append("You must enter a credit card number to complete your order<br />");
						valid = false;
				}
			}
		} else if (quantity_total == 0){
			alert(quantity_total);
			valid = false;
		}
		
		if (valid) 
		{
			$("#checkout").hide();
			$("#loading").show();
		} else {
			return false;
		}
	});
	
});

function remove_item($product_id)
{
    var qty = $("#"+$product_id+"_item_quantity").val() - 0;

	$("#"+$product_id+"_item").addClass("shadow");

    $.ajax({
		type: "GET",
		url: "/cart/remove_item/"+$product_id+"/"+qty,
		dataType: "xml",
		success: function(xml) {
			$(xml).find('shopping_cart').each(function(){
				var subtotal = $(this).find('subtotal').text();
                var quantity = $(this).find('quantity').text();
				$("#subtotal").html(subtotal);
				$("#"+$product_id+"_item").empty();
				$("#"+$product_id+"_item").hide("slow");
                $('#cart_quantity_display').text(parseInt(quantity));
                $('#cart_indicator').effect("highlight", {}, 500);
			})
		}
	});
}

function update_qty($product_id)
{
	// Get value from text fields and cast to integer (subtract 0).
    var original_qty = $("#"+$product_id+"_item_quantity_original").val() - 0;
	var new_qty = $("#"+$product_id+"_item_quantity").val() - 0;
	
    $("#duplicates").val('false');

    // Check for NAN and reset new_qty to original if NAN data was input.
    if (isNaN(new_qty)) {
        new_qty = original_qty;
        // Set the visible quantity amount
        $("#"+$product_id+"_item_quantity").val(original_qty).effect("highlight", {}, 500);;
    }
    
	if (new_qty > original_qty)
	{
		var qty = new_qty - original_qty;
		$.ajax({
			type: "GET",
			url: "/cart/add_item/"+$product_id+"/"+qty,
			dataType: "xml",
			success: function(xml) {
				$(xml).find('shopping_cart').each(function(){
					var item_quantity = $(this).find('item_quantity').text();
					// Reset the original qty amount
					$("#"+$product_id+"_item_quantity_original").val(item_quantity);
					// Set the visible quantity amount
					$("#"+$product_id+"_item_quantity").val(item_quantity);
					// Get the price of the itme
					var price = $("#"+$product_id+"_item_price").val();
					// Calculate the total for the item
					var item_total = price * item_quantity;
					// Assign that to the total
					$("#"+$product_id+"_item_calculated_price").html(formatCurrency(item_total));
					// Set the subtotal
					var subtotal = $(this).find('subtotal').text();
					$("#subtotal").html(subtotal);
				})
                change_quantity(qty);
			}
		});
	}
	else if (new_qty < original_qty)
	{
		var qty = original_qty - new_qty
		$.ajax({
			type: "GET",
			url: "/cart/remove_item/"+$product_id+"/"+qty,
			dataType:"xml",
			success: function(xml) {
				$(xml).find('shopping_cart').each(function(){
					var item_quantity = $(this).find('item_quantity').text();
					// Reset the original qty amount
					$("#"+$product_id+"_item_quantity_original").val(item_quantity);
					// Set the visible item_quantity amount
					$("#"+$product_id+"_item_quantity").val(item_quantity);
					// Get the price of the itme
					var price = $("#"+$product_id+"_item_price").val();
					// Calculate the total for the item
					var item_total = price * item_quantity;
					// Assign that to the total
					$("#"+$product_id+"_item_calculated_price").html(formatCurrency(item_total));
					// Set the subtotal
					var subtotal = $(this).find('subtotal').text();
					$("#subtotal").html(subtotal);
				})
                change_quantity(-qty);
			}
		});
	}
	else if (new_qty == original_qty)
	{
		// Do Nothing
	}
	$(".quantity_box").each(function(){
		var qty = $(this).val();
		if (qty > 1)
		{
			$("#duplicates").val('true');
		}
	});
	
}

/*
 * Change the cart object to reflect the new count of products in the cart.
 * Any significant changes to this function should likely be replicated in
 * product.js.  Ultimately it would be best to remove this function
 * to a scope where it is accessible from both shopping_cart and product.js
 * TODO: refactor this out of shopping_cart and product.js into one locaiton.
 */
function change_quantity(amount) {
    amount = amount || 1;

    var quantity = parseInt($('#cart_quantity_display').html());

    quantity += amount;

    if(quantity == 1) {
        $('#items_in_cart_text').html('item in cart');
    } else {
        $('#items_in_cart_text').html('items in cart');
    }

    $('#cart_quantity_display').text(parseInt(quantity));
    $('#cart_indicator').effect("highlight", {}, 500);
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function continue_shopping(url)
{
	window.location = url;
}
