// initialise plugins
$(function(){
	jQuery('ul.sf-menu').superfish({
		pathClass:	'active',
		animation:   {opacity:'show'},
		speed:	'fast'
	});
});

/* search */

function clearProductSearchBox()
{
	$("#productSearchBox").val();	
}

$(function() {
	// autocomplete search
	$( "#productSearchBox" ).autocomplete({
		minLength: 1,
		delay: 350,
		source: "ajax/search_results.php",
		select: function( event, ui ) {
			// clear search box
			clearProductSearchBox();
			// stop autocomplete from re-filling search box
			event.preventDefault();
			// redirect to appropriate page if necessary
			if (ui.item.href != "Too many results" && ui.item.href != "No results")
			{
				window.location.href = ui.item.href;
			}
		}
	})
	.data( "autocomplete" )._renderItem = function( ul, item ) {
		
		// show feedback if too many or no results
		if (item.href == "Too many results")
		{
			html = "<a href=\"#\">" + item.label + "</a>";
		}
		else if (item.href == "No results")
		{
			html = "<a href=\"#\">" + item.label + "</a>";	
		}
		else
		{
			// show actual link to new page link which will be redirected to if chosen
			html = "<a href='" + item.href +"'>" + item.label + "</a>";
		}
		
		return $( "<li></li>" )
		.data( "item.autocomplete", item )
			.append( html )
			.appendTo( ul );
	};
	
	$('.default-value').each(function() {
		var default_value = this.value;
		$(this).focus(function() {
			if(this.value == default_value) {
				this.value = '';
			}
		});
		$(this).blur(function() {
			if(this.value == '') {
				this.value = default_value;
			}
		});
	});
});

// custom functionality

/* user messages */

$(document).ready(function(){
	$("#userStatusContainer").bind("click",function(){
		hideUserStatusMessages();
	});
	
	$("#ajax_notification").bind("click",function(){
		$("#ajax_notification").slideUp("fast");
	});	
});

function hideUserStatusMessages()
{
	$("#userStatusContainer").slideUp("slow");		
}

function ajaxShowUserNotification(message, auto_close)
{
	// show notification
	$("#ajax_notification").html(message);
	$("#ajax_notification_container").slideDown("fast");
	
	
	if (auto_close)
	{
		var t = setTimeout(function(){
			$("#ajax_notification_container").slideUp("fast");
		}, 3000);
	}
}

function ajaxShowUserNotificationContainer(message, auto_close)
{
	// show notification
	$("#ajax_notification_container").html(message);
	$("#ajax_notification_container").slideDown("fast");
	
	
	if (auto_close)
	{
		var t = setTimeout(function(){
			$("#ajax_notification_container").slideUp("fast");
		}, 3000);
	}
}

/* login */

function toggleLoginBox()
{
	if ($("#loginMiniBox").is(":visible"))
	{ 
		$("#loginMiniBox").slideUp("fast");
	}
	else
	{
		$("#loginMiniBox").slideDown("fast", function(){
			$("#miniLoginEmail").focus();
		});
	}
}

// force enter submission on login
$(document).ready(function(){
	$("#loginFormMini input").keypress(function(e){ 
		if(e.keyCode == 13) 
		{
			$("#loginFormMini").submit();
		}
	});
});

function loginSubmit()
{
	$("#loginFormMini").submit();
}

function customerEmailAlreadyExists()
{
	var tmp_email = $("#email").val();

	// populate the form fields with the existing address
	var return_value = $.ajax({ type: "GET", url: "ajax/ajax_check_email_exists.php?email=" + tmp_email, async: false }).responseText;

	if (return_value == "email exists")
	{
		return false;
	}
	else
	{
		return true;	
	}
}

/* basket related */

function updateBasket()
{
	$("#basketFunc").val("updatebasket");
	$("#basketForm").submit();
}

function removeFromBasket(key)
{
	if (confirm("Are you sure you wish to remove this item from your basket?"))
	{
		$("#basketFunc").val("removefrombasket");
		$("#product_id").val(key);
		$("#basketForm").submit();
		
		return true;	
	}
}

/* admin related */
$(document).ready(function(){
	$("#adminloginform input").keypress(function(e){ 
		if(e.keyCode == 13) 
		{
			$("#adminloginform").submit();
		}
	});
});

/* addressing related */

function newAddress()
{
	// populate key hidden value		
	$("#address_id").val(0);

	// clear form ready for another address to be added
	$("#nickname").val("");
	$("#contact").val("");
	$("#address_1").val("");
	$("#address_2").val("");
	$("#address_3").val("");
	$("#address_4").val("");
	$("#address_5").val("GB|United Kingdom");
	$("#us_state").val("");
	$("#state_container").hide();
	disableUSStateValidation();
	
	// focus user on the add form
	$("#address_form_container").slideDown("fast", function() {
		$("#nickname").focus();
	});
}

function editAddress(address_id)
{
	// populate key hidden value
	$("#address_id").val(address_id);

	// populate the form fields with the existing address
	$.get("ajax/ajax_get_address.php?id=" + address_id, function(data){
		
		// split into a javascript array
		var data_array = data.split('|');

		$("#nickname").val(data_array[0]);
		$("#contact").val(data_array[1]);
		$("#address_1").val(data_array[2]);
		$("#address_2").val(data_array[3]);
		$("#address_3").val(data_array[4]);
		$("#address_4").val(data_array[5]);
		$("#address_5").val(data_array[7] + "|" + data_array[6]);
		$("#us_state").val(data_array[8]);
		// show state container if country is US
		if ($("#address_5").val() == "US|United States")
		{
			$("#state_container").slideDown("fast");
			enableUSStateValidation();
		}
		else
		{
			$("#state_container").hide();	
			disableUSStateValidation();	
		}
	});

	// focus user on the add form
	$("#address_form_container").slideDown("fast", function() {
		$("#nickname").focus();
	});
}

function deleteAddress(address_id)
{
	var choice = confirm("Are you sure you wish to delete this address?");
	if (choice)
	{
		$.get("ajax/ajax_delete_address.php?id=" + address_id, function(data){
			// refresh addresses
			$("#billing_addresses_container").load("ajax/ajax_fetch_addresses.php?type=billing"); 
			$("#shipping_addresses_container").load("ajax/ajax_fetch_addresses.php?type=shipping&offer_billing=1"); 

			// show notification
			ajaxShowUserNotification("Deleted address!", true);
		});
	}
}

function makeBillingAddress(address_id)
{
	$.get("ajax/ajax_make_billing_address.php?id=" + address_id, function(data){
		// refresh addresses
		$("#billing_addresses_container").load("ajax/ajax_fetch_addresses.php?type=billing"); 
		$("#shipping_addresses_container").load("ajax/ajax_fetch_addresses.php?type=shipping&offer_billing=1"); 
	});

	// show notification
	ajaxShowUserNotification("Updated!", true);
}


function saveAddress()
{
	// force validation
	if (!lv_nickname.validate() || !lv_address_1.validate() || !lv_address_2.validate() || !lv_address_4.validate() || ($("#state_container").is(':visible') && !lv_us_state.validate()))
	{
		return false;
	}
	
	var address_id = $("#address_id").val();
	
	// bundle up fields
	var nickname = $("#nickname").val();
	var contact = $("#contact").val();
	var address_1 = $("#address_1").val();
	var address_2 = $("#address_2").val();
	var address_3 = $("#address_3").val();
	var address_4 = $("#address_4").val();
	var address_5 = $("#address_5").val();
	var us_state = $("#us_state").val();
	
	// send request off
	$.post("ajax/ajax_save_address.php?id=" + address_id, {
  		// request
		nickname: nickname,
		contact: contact,
		address_1: address_1,
		address_2: address_2,
		address_3: address_3,
		address_4: address_4,
		address_5: address_5,
		us_state: us_state
	}, function() {
		// callback

		// refresh addresses
		$("#billing_addresses_container").load("ajax/ajax_fetch_addresses.php?type=billing"); 
		$("#shipping_addresses_container").load("ajax/ajax_fetch_addresses.php?type=shipping&offer_billing=1"); 
		
		// clear form ready for another address to be added
		$("#nickname").val("");
		$("#contact").val("");
		$("#address_1").val("");
		$("#address_2").val("");
		$("#address_3").val("");
		$("#address_4").val("");
		$("#address_5").val("GB|United Kingdom");
		$("#us_state").val("");
		$("#state_container").hide();
		disableUSStateValidation();	

		// clear postcode lookup if entered so user starts fresh
		$("#billing_postcode_search").val("");

		// update tip
		$("#addressBookTip").html("Please add/amend your billing and delivery addresses below");

		// hide add form
		$("#address_form_container").slideUp("fast");
		
		// show notification
		ajaxShowUserNotification("Address saved!", true);
	
		return true;
	});
	
	return true;
}

function checkAddressesAndProceed()
{
	// check if user has an open address they haven't saved
	if ($("#address_form_container").is(':visible'))
	{
		// save the address
		if (saveAddress())
		{
			// wait for the above to complete
			var t = setTimeout(function(){
				// then proceed to next screen
				checkAddresses();
			},2000);
		}
		else
		{
			alert("You must complete the required fields for this address before you can proceed");	
		}
	}
	else
	{
		// proceed immediately to next screen after performing checks
		checkAddresses();		
	}
}

function checkAddresses()
{
	$.get("ajax/ajax_has_addresses.php", function(data){
		if (data == "false")
		{
			alert("Please save at least one address before proceeding");	
		}
		else
		{
			window.location.href = "/delivery-details";	
		}
	});	
}

function toggleUSState()
{
	country = $("#address_5").val();
	if (country == "US|United States")
	{
		$("#state_container").slideDown("fast");
		enableUSStateValidation();	
	}
	else
	{
		// hide state
		$("#state_container").slideUp("fast");
		disableUSStateValidation();	
	}
}


/* delivery allocation */

function allocateBasketToAddress(basket_key, address_id)
{
	// force user to pick one
	if (address_id == 0)
	{
		alert("Please choose a delivery address address");
		return false;
	}
	// send request off
	$.post("ajax/ajax_allocate_basket_item_to_address.php", {
  		// request
		basket_key: basket_key,
		address_id: address_id
	}, function() {
		// callback
		
		// show notification
		ajaxShowUserNotification("Updated!", true);
	});
}

function checkDeliveryAllocationAndProceed()
{
	var failed = false;
	// check user has allocated all items
	$("table.allocateTable select" ).each(function(intIndex){
		if (this.value == 0)
		{
			alert("Please allocate all basket items to a delivery address");
			failed = true;
			return false;
		}
	});
	
	if (!failed)
	{
		// proceed
		window.location.href = "/delivery-details";
	}
}

/* delivery details */

function editDelivery(address_id)
{
	// close if not already closed
	$("#delivery_form_container").slideUp("fast");

	// populate key hidden value
	$("#delivery_address").val(address_id);

	// populate the form fields with the existing address
	$.get("ajax/ajax_get_delivery.php?id=" + address_id, function(data){
		
		// split into a javascript array
		var data_array = data.split('|');
		$("#delivery_address").val(data_array[0]);
		$("#delivery_method").val(data_array[1]);
		$("#comments").val(data_array[2]);
	});

	// focus user on the add form
	$("#delivery_form_container").slideDown("fast", function() {
		$("#delivery_method").focus();
	});
}

function saveDelivery()
{
	var address_id = $("#delivery_address").val();
	var delivery_method = $("#delivery_method").val();
	var comments = $("#comments").val();

	// force validation
	if (address_id == 0)
	{
		alert("You must choose the address you want this order to be delivered to\n\nIf you need to add additional addresses, please go back to the address book to do so");
		return false;
	}
	if (!delivery_method)
	{
		alert("You must choose a delivery method from those available for the selected delivery address\n\nPlease select one from the delivery method dropdown list");
		return false;
	}
	
	// update the edit button in case the address id has changed
	$("#edit_delivery_button").attr("href", "javascript:editDelivery(" + address_id + ")");
	

	
	// send request off
	$.post("ajax/ajax_save_delivery.php?id=" + address_id, {
  		// request
		delivery_method: delivery_method,
		comments: comments
	}, function(data) {

		// callback
		// refresh the saved details
		$("#delivery_address_nickname").load("ajax/ajax_fetch_delivery.php?id=" + address_id + "&type=nickname");
		$("#full_address_container").load("ajax/ajax_fetch_delivery.php?id=" + address_id + "&type=full_address");
		$("#delivery_details_container").load("ajax/ajax_fetch_delivery.php?id=" + address_id + "&type=details");
		
		// hide add form
		$("#delivery_form_container").slideUp("fast");
		
		// show notification
		ajaxShowUserNotification("Delivery details updated!", true);

		return true;
	});
	
	return true;
}

function checkDeliveriesAndProceed()
{	
// check if user has an open address they haven't saved
	if ($("#delivery_form_container").is(':visible'))
	{
		// save the address
		if (saveDelivery())
		{
			// wait for the above to complete
			var t = setTimeout(function(){
				// then proceed to next screen
				checkDeliveries();
			},2000);
		}
		else
		{
			// prompt user to fill in required information here	
		}
	}
	else
	{
		// proceed immediately to next screen after performing checks
		checkDeliveries();		
	}
}

function checkDeliveries()
{
	var data = $.ajax({ type: "GET", url: "ajax/ajax_check_deliveries.php", async: false }).responseText;

	if (data == "failure")
	{
		alert("Please edit and complete your delivery details before proceeding");	
	}
	else if (data == "minimum-order")
	{
		alert("The minimum order is 12 bottles to qualify for free local delivery.\n\nPlease add more to your basket or choose next day courier if you wish to proceed with your current order");
	}
	else
	{
		window.location.href = "/review-and-confirm";	
	}
}

function refreshDeliveryMethodOptions(address_id)
{
	// used to update the delivery details form when the customer chooses a different delivery address
	// the delivery address may be GB or overseas
	var is_local_delivery_available = $.ajax({ type: "GET", url: "ajax/ajax_is_local_delivery_available.php?id=" + address_id, async: false }).responseText;

	if (is_local_delivery_available == 1)
	{
		// show recorded delivery option
		$("#delivery_method_local_delivery").remove();	// remove any existing ones - to prevent duplicates
		$("#delivery_method").append('<option id="delivery_method_local_delivery" value="Personal delivery">Personal delivery (Free)</option>');

		// default users delivery choice to this
		$("#delivery_method").val("Personal delivery");
	}
	else
	{
		// check if customer has left themselves on local delivery - we need to default them away from this as its no longer applicable
		if ($("#delivery_method").val() == "Personal delivery")
		{
			$("#delivery_method").val("Next day courier");
		}
	
		// remove local delivery if its still showing
		$("#delivery_method_local_delivery").remove();
	}
}

/* order functions */

function placeOrder()
{
	// hide button and show waiting graphic
	$("#basketStepNext").html("<p style=\"color: green;\"><strong><img src=\"img/loader.gif\" alt=\"Please wait...\" width=\"16\" style=\"float: left;\"> &nbsp;please wait...</strong></p>"); 	

	// store order information
	var data = $.ajax({ type: "GET", url: "ajax/ajax_check_and_store_order.php", async: false }).responseText;

	window.location.href = "/make-payment?order_ref=" + data;
}

function cancelOrder()
{
	// cancel order
	var data = $.ajax({ type: "GET", url: "ajax/ajax_cancel_order.php", async: false }).responseText;
	
	// now redirect customer to a final page
	window.location.href = "/order-cancelled?order_ref=" + data;	
}

function submitToWorldPay()
{
	// hide button and show waiting graphic
	$("#basketStepNext").html("<p style=\"color: green;\"><strong><img src=\"img/loader.gif\" alt=\"Please wait...\" width=\"16\" style=\"float: left;\"> &nbsp;please wait...</strong></p>");

	$("#payment_form").submit();
}

function updateOrderStatus(order_type, order_number)
{
		new_status = $("#order_status_" + order_number).val();
		// prevent admin from marking a trade orcer as awaiting payment
		if (order_type == "Trade" && new_status == "Awaiting payment")
		{
			alert("Trade orders cannot be marked as awaiting payment as WorldPay is not involved for trade orders\n\nInstead, trade orders should be marked as Complete if they are valid or Cancelled if they are not");
			
			// reset back to whichever item was selected before user changed it
			resetOrderStatusSelectToLastValue(order_number);

			return false;
		}
	
	if (confirm("Are you sure you wish to update this order status?\n\nRETAIL ORDERS\n\nIf marked as Complete, amount outstanding will be set to zero (assuming payment has been taken elsewhere i.e. over the telephone) and order will be ready to sync with Sage\n\nIf marked as Awaiting payment, amount outstanding will be set back to the order total and the order will not sync with Sage until payment is taken (i.e. over the telephone) and then marked as Complete by an admin\n\nIf marked as Cancelled, the order will be left as is but never sync with Sage\n\nTRADE ORDERS\n\nIf marked as Complete, the amount outstanding is not changed as trade customers pay on account\n\nAwaiting payment is not applicable to trade orders so choosing this option will be disallowed\n\nIf marked as Cancelled, the order will not sync with Sage"))
	{
		$.get("ajax/ajax_update_order_status.php?order_number=" + order_number + "&new_status=" + new_status, function(data){
			location.reload();
			return true;
		});				
	}
	else
	{
		// reset back to whichever item was selected before user changed it
		resetOrderStatusSelectToLastValue(order_number);
	}
}

function rememberOrderStatusLastValue(order_number)
{
	// store in global variable defined within admin console orders page
	select_box_last_value = $("#order_status_" + order_number).val();
}

function resetOrderStatusSelectToLastValue(order_number)
{
	$("#order_status_" + order_number).val(select_box_last_value);
}

/* product functions */

function showCustomerProductPrices(product_id)
{
	// admin function - fetch customer prices for a particular product
	var data = $.ajax({ type: "GET", url: "ajax/ajax_fetch_customer_prices_for_product.php?product_id=" + product_id, async: false }).responseText;
	$("#customer_prices_container").html(data);
}
