$(document).ready( function() {
	
	// Open Basket Buttons
	$('#flower_basket_link, #flowerCount').click( function( e ) {
		e.preventDefault();
		
		$('#fade').show();
		$('#flower_basket').show();
	} );
	
	// Close Basket Buttons
	$('#flower_basket a.basket_close, #flower_basket a.contine_shopping').click( function( e ) {
		e.preventDefault();
		
		$('#fade').hide();
		$('#flower_basket').hide();
		hidePostalCheck();
	} );
	
	// Add click events to remove flower buttons
	$('a.remove_flower').click( function( e ) {
		e.preventDefault();
		removeFromCart( $(this).parent().attr( 'id' ), $(this).siblings('h4').children('a').html() );
	} );
	
	// Update Subtotal
	updateSubtotal();
	
	// Calculate Shipping Buttton
	$('#flower_basket_shipping a').click( function( e ) {
		e.preventDefault();
		
		// Only load if not empty
		if( $('#flower_basket_items div.flower_basket_item').size() == 0 )
		{
			return;
		}
		
		// Check postal code
		var postal = $('#postal_code').val();
		if( postal.search( /^[a-zA-Z]\d[a-zA-Z][ ]?\d[a-zA-Z]\d$/i ) == -1 && postal.search( /^\d{5}$/ ) == -1 )
		{
			alert( "Invalid zip or postal code." );
			return;
		}
		
		// Get number of flowers
		var num = $('div.flower_basket_item').size();
		
		// AJAX response
		$.ajax( {
			url: $('#ajaxUrl').val(),
			dataType: "json",
			async: true,
			data: ({ method: "postalCheck", postal: postal, num: num }),
			success: function( response ) {
				// Check for error
				if( response.error )
				{
					alert( response.error );
					return;
				}
				
				// Calculate and display Cost Details
				var subtotal = 0;
				$('#flower_basket_items div.flower_basket_item').each( function() {
					subtotal += parseInt( $(this).children('span').html().substr( 1 ) );
				} );
				var total = subtotal + response.delivery + response.service + response.tax;
				var delivery = response.delivery + response.service;
				
				$('#flower_basket_costs div:eq(0)').html( "$"+subtotal.toFixed(2) );
				$('#flower_basket_costs div:eq(1)').html( "$"+delivery.toFixed(2) );
				$('#flower_basket_costs div:eq(2)').html( "$"+response.tax.toFixed(2) );
				$('#flower_basket_subtotal span').html( "Order total:" );
				$('#flower_basket_subtotal div').html( "$"+total.toFixed(2) );
				
				$('#flower_basket_costs').slideDown( 400 );
			},
			error: function() {
				alert( "Failed to retrieve costs." );
			}
		} );
		
		// Google Analytics
		_gaq.push(['_trackEvent', 'Flowers', 'CalculateShipping']);
	} );
	
	// Checkout Button
	$('#flower_basket a.checkout_proceed, #checkoutButton').click( function( e ) {
		e.preventDefault();
		
		// Only load if basket is not empty
		if( $('#flower_basket_items div.flower_basket_item').size() != 0 )
		{
			// Google Analytics
			_gaq.push(['_trackEvent', 'Flowers', 'Checkout']);
		
			var checkoutURL = "https" + location.href.substr( 4 );
			if( location.href.indexOf( "?checkout" ) == -1 )
			{
				checkoutURL += "?checkout";
			}
			window.location.assign( checkoutURL );
		}
	} );
	
	// Logout Button
	$('a.logout').click( function( e ) {
		e.preventDefault();
		
		// Logout
		$.ajax( {
			url: $('#ajaxUrl').val(),
			dataType: "text",
			async: true,
			data: ({ method: "userLogout" }),
			success: function( response ) {
				// Display error message if no success
				if( response != "success" )
				{
					alert( response );
					return;
				}
				
				location.reload();
			},
			error: function() {
				alert( "Failed to logout." );
			}
		} );
	} );
	
	// Quantity updates
	$('#flower_basket_items select').change( function() {
	
		var fid = $(this).parent().attr( 'id' );
		var quantity = $(this).val();
	
		$.ajax( {
			url: $('#ajaxUrl').val(),
			dataType: "text",
			async: true,
			data: ({ method: "updateQuantity", fid: fid, quantity: quantity }),
			success: function( response ) {
				// Display error message if no success
				if( response != "success" )
				{
					alert( response );
				}
			},
			error: function() {
				alert( "Failed to update cart." );
			}
		} );
		
	} );

} );

function removeFromCart( fid, name )
{
	// Remove from cart via ajax
	$.ajax( {
		url: $('#ajaxUrl').val(),
		dataType: "text",
		async: true,
		data: ({ method: "removeFromCart", fid: fid }),
		success: function( response ) {
			// Display error message if no success
			if( response != "success" )
			{
				alert( response );
			}
		},
		error: function() {
			alert( "Failed to update cart." );
		}
	} );
	
	// Remove html
	$('#'+fid).remove();
	
	// Update Subtotal
	updateSubtotal();
	
	// Add empty message if empty
	if( $('#flower_basket_items div.flower_basket_item').size() == 0 )
	{
		$('#flower_basket_items').html( "<h2>You have not added any items.</h2> <h2>Please continue shopping.</h2>" );
	}
	
	// Update flower basket count in header
	$('#flowerCount').html( $('#flower_basket_items div.flower_basket_item').size() );
	
	hidePostalCheck();
	
	// Google Analytics
	_gaq.push(['_trackEvent', 'Flowers', 'RemoveFromCart', name]);
}

function updateSubtotal()
{
	var subtotal = 0;

	$('#flower_basket_items div.flower_basket_item').each( function() {
		subtotal += parseInt( $(this).children('span').html().substr( 1 ) );
	} );
	
	$('#flower_basket_subtotal div').html( '$'+subtotal.toFixed(2) );
}

function hidePostalCheck()
{
	$('#flower_basket_subtotal span').html( "Order subtotal:" );
	updateSubtotal();
	$('#flower_basket_costs').hide();
}
