$(document).ready(function(){
	jQuery.pre_load_images(
		"/media/default/images/shopping_cart/continueshopping_button.png",
		"/media/default/images/shopping_cart/continueshopping_button_pressed.png",
		"/media/default/images/shopping_cart/continueshopping_button_rollover.png",
		"/media/default/images/shopping_cart/continuetocheckout_button.png",
		"/media/default/images/shopping_cart/continuetocheckout_button_pressed.png",
		"/media/default/images/shopping_cart/continuetocheckout_button_rollover.png",
		"/media/default/images/shopping_cart/continuetobilling_button.png",
		"/media/default/images/shopping_cart/continuetobilling_button_pressed.png",
		"/media/default/images/shopping_cart/continuetobilling_button_rollover.png");
	
	$("#view_rewards_balance").click(function(event){
		$('#rewards_balance').dialog('open');
		event.preventDefault();
	});
	$("#newsletter_button").click(function(){
		window.open('/newsletter','_blank');
	});
	$("#rewards_balance").dialog({
		bgiframe: false, autoOpen: false, height: 450, width:550, modal: true, resizable:false     	
	});
	
	$("#redeem").click(redeem_rewards);
	
	$("#coupon_code").keydown(function(event){
		if (event.keyCode == '13')
		{
			event.preventDefault();
			$('#apply_coupon').click();
			return false;
		}
	});
	$('#billing_form').submit(function(event){
		if (event.originalEvent.explicitOriginalTarget.id == "billing_form")
		{
			return true;
		}
		else
		{
			event.preventDefault();
			return false;
		}
		
	});

	function redeem_rewards(){
		redeem_button = this;
		
		if($(redeem_button).html() == 'Redeem and Apply'){
			$(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. Your credit will be applied at checkout.");
				} else {
					$(redeem_button).html('Redeem Points');
				}
			});
		}
	}
	
	$(".optin").click(function(){
		$("#dialog").dialog('open');
	});
	
	$("#continue_billing_address").click(function(){
		 var address_id = $('input[name="address_radio"]:checked').val();
		$.ajax({
		   type: "POST",
		   url: "/billing_address/store_address/"+address_id,
		   success: function(msg){
		   	 window.location = '/billing';
  		   }
 		});	
	});
	
	$("#continue_button").click(function(){
		var logged_in = $("#duplicate_message").attr('signed_in');
		var product_id = "";
		var dup_in_cart = false;
		var dup_already_purchased = false;
		
		$("#dup_message").empty();
		$(".quantity_box").each(function(){
			var qty = $(this).val();
			var duplicate = $(this).attr("duplicate");
			
			if (qty > 1 || duplicate == 'true')
		 	{
				if (qty > 1)
					dup_in_cart = true;
				else
					dup_already_purchased = true;
					
				$("#duplicates").val("true");
				var product_id = $(this).attr('product_id');
				
				$("#dup_message").append("<tr><td style='text-align: center;'>" + qty + "</td><td>" + $("#"+product_id+"_item_title").html() + "</td></tr>");			
			}
		});
		
		var dup = $("#duplicates").val();
		
		if (dup == 'true')
		{
			var dup_title = "";
			if (dup_in_cart)
				dup_title = 'Are you sure? It looks like you have duplicate items in your cart.';
			if (dup_already_purchased)
				dup_title = 'Are you sure? Our system shows you\'ve purchased this before.';
			
			$("#duplicate_message").dialog("option", "title", dup_title);
			
			$("#duplicate_message").dialog('open');
		}
		else
		{
			if (logged_in == 'true')
			{
				if ($('#subtotal').attr('amount') == '0')
				{
					window.location = '/billing/purchase';
				}
				else
				{
					window.location = '/billing';
				}
			} 
			else 
			{
				window.location = '/login/cart';
			}
		}
		return false;
	});

	$("#duplicate_message").dialog({
		bgiframe: true,
		resizable: false,
		height:250,
		width:500,
		modal: true,
		draggable: false,
		autoOpen: false,
		buttons: {
			'Continue': function() {
				var logged_in = $("#duplicate_message").attr('signed_in');
				if (logged_in == 'true')
				{
					if ($('#subtotal').attr('amount') == '0')
					{
						window.location = '/billing';
					}
					else
					{
						if (window.location.pathname == '/billing')
						{
							$(this).dialog('close');
						}
						else
						{
							window.location = '/billing';
						}
					}
				} 
				else 
				{
					window.location = '/login/cart';
				}
			},
			'Go Back and Change Quantity': function() {
				if (window.location.pathname == '/billing')
				{
					window.location = '/cart';
				}
				else
				{
					$(this).dialog('close');
				}
				
			}
		}
	});
	
	$('.ui-dialog-buttonpane :button').each(function() { 
		$(this).addClass('dialog_'+$(this).text().replace(/\s/g,''));
	});
	
	$('.dialog_Continue').removeClass('ui-button-text-only')
		.addClass('ui-button-text-icon')
		.html('<img src="/media/default/images/shopping_cart/continue_checkout.png"/>')
		.css({'background':'none',
			  'border':'none',
			  'margin-left':'-20px',
			  'margin-right':'-20px'});
	$('.dialog_GoBackandChangeQuantity').removeClass('ui-button-text-only')
		.addClass('ui-button-text-icon')
		.html('<img src="/media/default/images/shopping_cart/change_quantity.png"/>')
		.css({'background':'none',
			  'border':'none',
			  'margin-left':'-30px',
			  'padding-top':'4px'});

	$("#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');
			}
		}
	});
	
	$(".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;
			}
		});
	};
	$(".quantity_box").search();
	
	$("#apply_coupon").click(function(){
		var code = $("#coupon_code").val();
		$("#coupon_message").removeClass("error");
		$("#coupon_code").removeClass("input_error");
		$("#coupon_message").hide('fast');
		$.ajax({
			type: 'GET',
			url: '/billing/apply_coupon/'+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();
					var campaigns_saving = $(this).find('campaigns_saving').text();

					if (status == 1)
					{
						$("#apply_coupon").hide();
						$("#remove_coupon").show('fast');
						location.reload();
					} 
					else 
					{
						$("#coupon_message").addClass("error");
						$("#coupon_code").addClass("input_error");
					}
					$("#coupon_message").html(message);
					$("#coupon_message").show('fast');
				})
			}
		});
		$.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();
					var campaigns_saving = $(this).find('campaigns_saving').text();
					$("#spice_credit_total").html(spice_credit_total);
					$("#remove_credit").hide();
					$("#apply_credit").show("fast");
					
					/*$("#credit_message").html(message);
					$("#credit_message").show('fast');*/

					if(campaigns_saving != '')
					  $("#campaigns_saving_amount").html(campaigns_saving);

					$("#credit_line").hide('fast');
					$("#credit_amount").html(credit_amount);
					$("#total").html(total);
					
				});
			}
		});
	});
	
	$("#remove_coupon").click(function(){
		$.ajax({
			type: 'GET',
			url: '/billing/remove_coupon',
			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();
					var credit_amount = $(this).find('credit_amount').text();
					var spice_credit_total = $(this).find('credit_total').text();
					
					var credit_amount = $(this).find('credit_amount').text();
					var spice_credit_total = $(this).find('credit_total').text();
					var campaigns_saving = $(this).find('campaigns_saving').text();

					if (status == 1)
					{
						$("#spice_credit_total").html(spice_credit_total);
						$("#credit_amount").html(credit_amount);
						
						$("#order_total_amount_discount").html(discount_amount);
						$("#saving_line").hide('fast');
						
						$("#remove_coupon").hide();
						$("#apply_coupon").show('fast');
						
						if(spice_credit_total != '')
							$("#spice_credit_total").html(spice_credit_total);
						if(campaigns_saving != '')
							$("#campaigns_saving_amount").html(campaigns_saving);
						if(credit_amount != '')
							$("#credit_amount").html(credit_amount);
						
						$("#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();
						var campaigns_saving = $(this).find('campaigns_saving').text();
						$("#spice_credit_total").html(spice_credit_total);
						
						$("#apply_credit").hide();
						$("#remove_credit").show("fast");
						
						$("#credit_message").html(message);
						$("#credit_message").show('fast');

						if(campaigns_saving != '')
						   $("#campaigns_saving_amount").html(campaigns_saving);

						$("#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();
					var campaigns_saving = $(this).find('campaigns_saving').text();
					$("#spice_credit_total").html(spice_credit_total);
					$("#remove_credit").hide();
					$("#apply_credit").show("fast");
					
					$("#credit_message").html(message);
					$("#credit_message").show('fast');

					if(campaigns_saving != '')
					  $("#campaigns_saving_amount").html(campaigns_saving);

					$("#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 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 = $("#cc_cvn").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+"&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 == '')
			{
				$("#name_error").empty();
				$("#name_error").append("Please enter first and last name");
				$("#name_error").show();
				$("#error_box").show();
				$("#name_box_error").empty();
				$("#name_box_error").append("- Please enter first and last name");
				$("#name_box_error").show();
				$("#cc_name").addClass('input_error');
				valid = false;
			}
			if (cc_use == 'new')
			{
				if (cc_cvn == '')
				{ 
					$("#security_code_error").empty();
					$("#security_code_error").append("Please enter your card&acute;s security code to complete your order");
					$("#security_code_error").show();
					$("#error_box").show();
					$("#security_code_box_error").empty();
					$("#security_code_box_error").append("- Please enter your card&acute;s security code to complete your order");
					$("#security_code_box_error").show();
					$("#security_code").addClass('input_error');
					valid = false;
				}
				var d = new Date();
				var curr_date = d.getDate();
				var curr_month = d.getMonth();
				var curr_year = d.getFullYear();
				if (cc_month == '' || cc_month == 'Mo' ||  cc_month < 1 || cc_month > 12 || cc_year == '' || cc_year == 'Year')
				{
					$("#expiration_date_error").empty();
					$("#expiration_date_error").append("Please enter a valid expiration date");
					$("#expiration_date_error").show();
					$("#error_box").show();
					$("#expiration_date_box_error").empty();
					$("#expiration_date_box_error").append("- Please enter a valid expiration date");
					$("#expiration_date_box_error").show();
					$("#cc_month").addClass('input_error');
					$("#cc_year").addClass('input_error');
					valid = false;
				}
				if ( cc_month == '' && cc_year == '')
				{
					$("#expiration_date_error").empty();
					$("#expiration_date_error").append("Please enter an expiration date to complete your order");
					$("#expiration_date_error").show();
					$("#error_box").show();
					$("#expiration_date_box_error").empty();
					$("#expiration_date_box_error").append("- Please enter an expiration date to complete your order");
					$("#expiration_date_box_error").show();
					$("#cc_month").addClass('input_error');
					$("#cc_year").addClass('input_error');
					valid = false;
				}
				if (cc_use == 'new' && cc_number == '')
				{ 
					$("#credit_card_error").empty();
					$("#credit_card_error").append("Please enter a credit card number to complete your order");
					$("#credit_card_error").show();
					$("#error_box").show();
					$("#credit_card_box_error").empty();
					$("#credit_card_box_error").append("- Please enter a credit card number to complete your order");
					$("#credit_card_box_error").show();
					$("#cc_number").addClass('input_error');
					valid = false;
				}
			}
		} else if (quantity_total == 0){
			valid = false;
		}
		
		if (valid) 
		{
			$("#checkout").hide();
			$("#loading").show();
		} else {
			return false;
		}
	});
	
	$(".remove_from_cart").dialog({
		resizable: false,
		height:150,
		width:350,
		modal: true,
		draggable: false,
		autoOpen: false,
		buttons: {
			'Yes': function() {
				var product_id = $(this).attr('product_id');
				remove_item_from_cart(product_id);
				$(this).dialog('close');
			},
			'No': function() {
				$(this).dialog('close');
			}
		}
	});
});

function remove_item($product_id)
{
	$("#remove_from_cart_"+$product_id).dialog('open');
}

function remove_item_from_cart(product_id)
{
	var qty = $("#"+product_id+"_item_quantity").val() - 0;
	if (qty == 0) {
		var original_qty = $("#"+product_id+"_item_quantity_original").val() - 0;
		var new_qty = $("#"+product_id+"_item_quantity").val() - 0;
		var qty = original_qty - new_qty;
	}
	$("#"+product_id+"_item").addClass("shadow");
	$.ajax({
		type: "GET",
		url: "/cart/remove_item/"+product_id+"/"+qty,
		dataType: "xml",
		success: function(xml) {
			location.reload();
		}
	});
}

function show_campaign_saving(value)
{
	if (value != '-$0.00')
	{
		$("#saving_line").removeClass('hidden');
	}
	else
	{
		$("#saving_line").addClass('hidden');
	}
}

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 == 0) {
    	remove_item($product_id);
    } else 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);
					var total = $(this).find('total').text();
					$("#total").html(total);
					
					var sales = $(this).find('sales').text();
					$("#sales_amount").html(sales);
					var bogo = $(this).find('bogo').text();
					$("#bogo_amount").html(bogo);
					var subscriptions = $(this).find('subscriptions').text();
					$("#subscriptions_amount").html(subscriptions);
				})
                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);
					var total = $(this).find('total').text();
					$("#total").html(total);

					var sales = $(this).find('sales').text();
					$("#sales_amount").html(sales);
					var bogo = $(this).find('bogo').text();
					$("#bogo_amount").html(bogo);
					var subscriptions = $(this).find('subscriptions').text();
					$("#subscriptions_amount").html(subscriptions);
				})
                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_button').effect("bounce", {}, 250);
}

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 keep_shopping(url)
{
	window.location = url;
}

function check_dup_in_billing()
{
	var product_id = "";
	var dup_in_cart = false;
	var dup_already_purchased = false;
	$("#dup_message").empty();
	$(".quantity_box").each(function(){
		var qty = $(this).html();
		var duplicate = $(this).attr("duplicate");

		if (qty > 1 || duplicate == 'true')
		{
			if (qty > 1)
				dup_in_cart = true;
			else
				dup_already_purchased = 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>");
		}
	});

	var dup = $("#duplicates").val();

	if (dup == 'true')
	{
		var dup_title = "";
		if (dup_in_cart)
			dup_title = 'Are you sure? It looks like you have duplicate items in your cart.';
		if (dup_already_purchased)
			dup_title = 'Are you sure? Our system shows you\'ve purchased this before.';

		$("#duplicate_message").dialog("option", "title", dup_title);

		$("#duplicate_message").dialog('open');
	}

}

check_dup_in_billing();

