$(function(){
	
	//alert('jquery loaded');
	$('noscript').hide();

	//highlight current page on navigation menu
	navOver($('.nav').attr('rel'));	

	$('#slides').hover(
		 function(){ $('.slides_controls').fadeIn();  $('.pagination').fadeIn();  }
		,function(){ $('.slides_controls').fadeOut(); $('.pagination').fadeOut(); }
	);

	/*
 	 * click find customer button
	 */
	$('#find-customer').click(function(){
		$('#ajax-loader-blue').show();
		if ($('.order #customer_id').val() == '') {
			alert('Please enter your Customer Number');
			$('.order #customer_id').focus();
		}
		else {
			var data = {customer_id: $('.order #customer_id').val()};
			var jqxhr = $.post('../orders/find_customer', data, function (data) {		

				if (data != null) {
					$('.order #name').val(data.name);
					$('.order #email').val(data.email);
					$('.order #phone').val(data.phone);
					$('.order #company').val(data.company);				
					$('.order #contact_name').val(data.contact_name);				
					$('.order #cost_code').val(data.cost_code);				
					$('.order #billing_address').val(data.billing_address);				
					$('#ajax-loader-blue').hide();
					$('#find-customer').fadeOut();
					$('#customer-message').html('Welcome back ' + data.name);
					if (data.billing_email == 'N') $('.order #billing_emailN').attr('checked','checked');			
				}
				else {
					$('#ajax-loader-blue').hide();
					alert('Sorry, we couldn\'t find that Customer Number.');
				}
			},'json');
			return false;
		}
		$('#ajax-loader-blue').hide();
		return false;
	});


	/* 
	 * change menu 
	 */
	$('#order_menu_id').change(function(){
		if ($('#order_menu_id').val() == ''){
			return false;
		}
		else {
			$('.price_option').hide();
			$('#menu_items').html(''); 
			$('#menu_items_h4b').addClass('hidden');
			var menu_id = $('#order_menu_id').val();
			$('#price_option_' + menu_id).show();
			//set initial price per item value
			var price_option = $('#price_option_' + menu_id + ' option:selected').val();
			$('#price_per_person').val(option0(price_option));
			$('#price_per_person2').text(option0(price_option));
			$('#max_items').val(option1(price_option));
			updateTotal();
			resetQuantity();
			setMinQuantity(menu_id);
			checkMinSpend(menu_id, true);
			return false;
		}
	});


	/*
	 * change price option
	 */
	$('.price_option').change(function(){
		//checkMinSpend($('#order_menu_id').val());
		var price_option = $(this).val();
		$('#price_per_person').val(option0(price_option));
		$('#price_per_person2').text(option0(price_option));
		$('#max_items').val(option1(price_option));
		$('#continue2').addClass('hidden');

		// Added by Tailor to fix chef's menu selection
		$( '.cant-select' ).val(option1(price_option) * $('#total_people').val());
		//console.log('max_items: ' + option1(price_option));
		updateTotal();
		resetQuantity();
		clearSelections();
		var menu_id = $('#order_menu_id').val();
		checkMinSpend(menu_id, false);
	});


	/*
	 * force a calculate before submit on order-items form
	 */
	$('#order-items').live('submit',function(e){
		if ($('#continue2').hasClass('hidden')) {
			e.preventDefault();
			//console.log('order-items:calculate');
			$('#calculate').trigger('click');
		}
		else {
			//console.log('order-items: submitting');
			return true;
		}
	});

	/*
 	 * calculate the total items selected and remaining
     */
	$('#calculate').click(function(event, callback){
		//console.log('calculate');
		event.preventDefault();

		var quantity = 0;
		var all_good = true;
		var min_quantity = $('#min_quantity').val();
		$.each( $('#menu_items input'), function(key,input) {
			//if (is_int(input.value)) alert(input.id + ' = ' + input.value);
			if (is_int(input.value)&&input.value!='0'&&all_good){
				//check for value under min_quantity
				if (parseInt(input.value) < min_quantity){
					all_good = false;
					alert('The minimum required for each item is ' + min_quantity);
					input.value = min_quantity;
					return false;
				}
				var max = parseInt($('#select_max').text());
				var select_count = parseInt($('#select_count').text());
				var item_id = input.id.substring(input.id.indexOf('_') + 1, input.id.length );
				quantity += parseInt(input.value);				
				if (input.value > max || quantity > max) {
					alert('You\'ve selected too many items, please adjust the quantities and click "Calculate" again');
					input.value = '';
					all_good = false;
					return;
				}
				//prevent adding over the max
				if (input.value == max || quantity >= max) {
					return;
				}
			}
			else {
				input.value = '';
			}
		});

		if (all_good){
			resetQuantity();
			updateQuantity(quantity);

			if (null != callback) {
				callback();
			}
		}
		return false;
	});


	/*
 	 * change delivery area
  	 */
	$('#delivery_area').change(function(){
		var sub_total = parseFloat($('#order_subtotal').val());
		var delivery_fee = parseFloat($('#delivery_fee_'+ $(this).val()).val());
		var extras_total = parseFloat($('#extras_total').val());
		var sub_total = formatCurrency(sub_total + delivery_fee + extras_total);
		$('#sub_total').text(sub_total);
	});


	/*
	 * submit order index on button click
	 */
	$('#create-order').live('click', function(e){
		e.preventDefault();	
		$('#order-start').submit();
	});

	/*
	 * submit order items on continue button click
	 */
	// Modifield by Tailor to fix extra selections after calculating
	$('#continue2').live('click', function(event){
		event.preventDefault();
		$('#calculate').trigger('click', submitForm);
	});

	$('#continue3').click(function(){
		$('#order-items').submit();
	});

	/*
	 * submit order details on button click
	 */
	$('#submit-order').live('click', function(e){
		e.preventDefault();	
		$('#order-details-form').submit();
	});

	/*
	 * click extra menu item
	 */
	$('#extra_items input').live('click', function(event){
		var item_id = itemId(this.id);
		if ($(this).parent().is('.active')){
			$(this).parent().removeClass('active');
			//if price per person item, subtract price * number_people from subtotal
			if (price1(item_id) == 'pp'){
				var number_people = parseInt($('#number_people').val());				
				updateExtraTotal(-(price0(item_id) * number_people));
			}	
			//price is each item, subtract price * selected quantity from subtotal		
			else {
				var quantity = parseInt($('#extraitem_'+item_id).val());
				if (quantity == 0) {
					return;
				} else {
					updateExtraTotal( -(price0(item_id) * quantity) );
				}
			}
			//reset count on this row
			$('#count_'+item_id).text('1');
			$('#extraitem_'+item_id).val(1);							
		}
		else {
			$(this).parent().addClass('active');

			var quantity = parseInt($('#extraitem_'+item_id).val());
			if ( quantity != 0 ) {
				updateExtraTotal( (price0(item_id) * quantity) );
			}

			//if price per person 
			if (price1(item_id) == 'pp'){
				//update subtotal with price * number_people
				var number_people = parseInt($('#number_people').val());				
				updateExtraTotal(price0(item_id) * number_people);
				//set item input field value
				$('#extraitem_'+item_id).val(1);	
			}
			//else, this is incremented with the plus/minus btn clicks	
		}
	});


	/*
	 * click + - extra item button
	 */
	$('#extra_items button').live('click', function(event){
		event.preventDefault();
		var action =  event.target.id.substring(0, event.target.id.indexOf('_'));
		var item_id = event.target.id.substring(event.target.id.indexOf('_') + 1, event.target.id.length );
		var increment = 1;
		var count = $('#count_'+item_id).text();
		
		if (count == null || count == '') count = 0;
		else count = parseInt(count);

		if (action == 'plus') {
			$('#count_'+item_id).text( count + increment );
			$('#extraitem_'+item_id).val(count + increment);
			updateExtraTotal(price0(item_id));			
		}
		else {
			if (count == 0) return false;
			$('#count_'+item_id).text( count - increment );
			$('#extraitem_'+item_id).val(count - increment);
			updateExtraTotal(-price0(item_id));
		}		
	});		

	$('#add-order').click(function(){
		//console.log('#add-order');
		window.location.href = 'add/' + $(this).attr('rel');
		return false;
	});

	$('#add-order-continue').live('click', function(e){
		//console.log('#add-order-continue');
		e.preventDefault();
		$('#people-error').hide();		
		//validate number-people field
		var people = $('#people').val();
		if (!is_int(people) || people < 5){
			//console.log('#add-order-continue validation failed: ' + $('#people').val());	
			$('#people-error').show();
			$('#people').val(5);
		}
		else {
			//post form to continue on
			//$('#order-add').trigger('submit');
			$('#order-add').submit();
		}
	});

	$('#extras-continue').live('click', function(){
		//console.log('extras-continue');
		//$('#order_extras').trigger('submit');
		$('#order_extras').submit();
		return false;
	});

	//link in order breadcrumb to go back to overview
	$('#return-order-overview').click(function(e){
		//e.preventDefault();
		if (confirm('Are you sure? Changes to this order will not be saved.')){
			var id = $('#return-order-overview').attr('class');
			//console.log('return-order-overview / removing order: ' + id);
			$.post('../orders/remove_order',{order_id: id}, function(data){
				window.location.href = 'overview';
			});
		}
		return false;
	});

	//change details button on order overview
	$('#cancel-order-overview').click(function(){
		if (confirm('Are you sure? Changes to this order will not be saved.')){
			//console.log('cancel-order-overview');
			window.location.href = '../orders';
			return true;
		}
		return false;
	});

	//process the delete order button
	$('.delete-order').live('click', function(e){		
		var id = this.id.substring(6, this.id.length);
		//console.log('delete-order: ' + id);
		if (confirm('Are you sure you want to delete that from your order?')){
			//console.log('delete: ' + id);
			$.post('../orders/remove_order_item', {order_id: id}, function(data){
				//$('#overview_'+id).fadeOut();
				//force reload to recal totals
				window.location.href = 'overview';
			});
		}
		else {
			//console.log('cancel delete: ' + id);			
		}
		e.preventDefault();
	});

	$('#checkout').click(function(){
		window.location.href = 'details';
		return false;
	});


	// // Added by Tailor ltd to fix submit extra selections after calculating
	$('.menuitems').live('focus change', function(event) {
		// hide submit button
		$('#continue2').addClass('hidden');
	});
});

function submitForm() {
	if ( !$('#continue2').hasClass('hidden') ) {
		$('#order-items').submit();
	}
}

function is_int(input){
    return !isNaN(input)&&parseInt(input)==input;
}

function updateTotal(){
	var sub_total = parseFloat($('#order_subtotal').val());
	var delivery_fee = parseFloat($('#delivery_fee').val());
	var extras_total = parseFloat($('#extras_total').val());
	var sub_total = formatCurrency(sub_total + delivery_fee + extras_total);
	$('#sub_total').text(sub_total);
	//console.log('updateTotal: ' + sub_total);
}

function updateDeliveryTotal(){
	var sub_total = parseFloat($('#order_subtotal').val());
	var delivery_fee = parseFloat($('#delivery_fee').val());
	//var extras_total = parseFloat($('#extras_total').val());
	var total = formatCurrency(sub_total + delivery_fee);
	$('#total_label').text(total);
	//console.log('updateTotal: ' + total);
}

function clearSelections(){
	var checked = $('#menu_items input:checked');
	$.each(checked, function(a,b){		
		$(countId(b.id)).text('0');
		$(b).parent().removeClass('active');
		$(b).attr('checked',false);
		$(b).val(0);
	});
}

function updateTotal(){
	var total = ($('#price_per_person').val() * $('#total_people').val());
	$('#total_price').text(formatCurrency(total));
	$('#order_total').val(total);
}

function resetQuantity(){
	var total = ($('#max_items').val() * $('#total_people').val());
	$('#select_count').text('0');
	$('#select_max').text(total);
	$('#select_remain').text(total);
	//console.log('resetQuantity: ' + total);
}

function updateQuantity(i){
	var count = parseInt($('#select_count').text());
	var max = parseInt($('#select_max').text());
	var remain = parseInt($('#select_remain').text());
	count = count + i;
	
	if (count > max) {
		count = max;
	}

	$('#select_count').text(count);	
	$('#select_remain').text(max - count);
	
	if (count == max) {
		$('#continue2').removeClass('hidden');
	} else {
		$('#continue2').addClass('hidden');
	}
}

function updateExtraTotal(item_price){
	var extras_total = parseFloat($('#extras_total').val());
	extras_total += item_price;
	$('#extras_total').val(extras_total);
	$('#extras_total_label').text(formatCurrency(extras_total));	
	var sub_total = parseFloat($('#order_total').val());
	var order_total = sub_total + extras_total;
	$('#sub_total').text(formatCurrency(order_total));
}

function price0(item_id){
	var price = $('#extraitem_'+item_id).attr('rel');
	return parseFloat(price.substring(0, price.indexOf('|')));
}

function price1(item_id){
	var price = $('#extraitem_'+item_id).attr('rel');
	return price.substring(price.indexOf('|')+1, price.length);	
}

function itemId(id){
	return id.substring( id.indexOf('_')+1, id.length );
}

function countId(id){
	return '#count_' + itemId(id);
}

function option0(option){
	return option.substring(0, option.indexOf('|'));
}

function option1(option){
	return option.substring(option.indexOf('|')+1, option.length);
}

function navOver(x){
	if (x > 0) {
		var z = x * 130;
		$('.nav').css({'background-position': '-' + z + 'px 0'});
	}
}

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 setMinQuantity(menu_id){
	$.post("../orders/find_min_quantity", {menu_id: menu_id}, function(data){
		//console.log('min_quantity: ' + data);
		$('#min_quantity').val(data);
		$('#min_quantity_label').text(data);
	});
}

function checkMinSpend(menu_id, reload){
	$('#min_spend_notice').hide();		
 	$.ajax({
        type: "POST",
        url: '../orders/find_min_spend',
        asynch: false,
        data: ({ menu_id: menu_id }),
        dataType: "text",
        success: function(data) {
			$('#min_spend').val(data);
			$('#min_spend_label').text(data);
			var m = parseFloat($('#min_spend').val());
			var t = parseFloat($('#order_total').val());	
			//console.log('order total: ' + t + ', min_spend: ' + m);
			if (m > 0 && t < m){			
				$('#min_spend_notice').show();			
				$('#menu_items').hide();	
				$('#continue1').addClass('hidden');
				$('#menu_items_h4').addClass('hidden');
				$('#menu_items_h4b').addClass('hidden');
				$('#min_spend_valid').val('no');
			}
			else {
				$('#min_spend_valid').val('valid');
				if (reload || $('#menu_items').is(':hidden')) getMenuItems(menu_id);
			}
        },
        error: function() {
            alert('Error occured');
        }
    });
}

function getMenuItems(menu_id){
	//console.log('min_spend_valid: ' + $('#min_spend_valid').val());
	if ( $('#min_spend_valid').val() == 'valid') {
		$('#menu_items').html(''); 
		$('#menu_items').show();	
		$('#ajax-loader').show();
		var jqxhr = $.post("../orders/find_items", {menu_id: menu_id}, function(data) {
			var input_type  = 'text';
			var input_val   = '';
			var item_title  = '';
			var extra_class = 'menuitems';
			$.each(data, function(key,group){
				$('#menu_items').append('<h5>' + group.title + '</h5>');
				$.each(group.items, function(key2,item){
					if (group.can_select == false){
						input_type = 'hidden';
						input_val = $('#total_people').val();
						extra_class = 'cant-select';
					}
					if (item.title.indexOf("\n") != -1) item_title = '<br />' + item.title.replace("\n",'<br />');
					else item_title = item.title;					
					var item_html = 
						'<label for="menuitem_'+item.id+'">'
						+ '<input type="' + input_type + '" id="menuitem_'+item.id+'" name="menuitem_'+item.id+'" value="' + input_val + '" size="5" class="'+ extra_class + '" /> '
						+ item_title + '</label>';
					$('#menu_items').append(item_html);
				});
				if (group.can_select == false){
					$('#continue1').addClass('hidden');
					$('#menu_items_h4').addClass('hidden');
					$('#menu_items_h4b').removeClass('hidden');
				}
				else {
					$('#menu_items_h4').removeClass('hidden');
					$('#continue1').removeClass('hidden');
				}
			});
		},'json')
			.success(function(){ })
			.complete(function(){ $('#ajax-loader').hide(); })
			.error(function() { alert("error"); })
		;//jqxhr.
	}
	else {
		//console.log('getMenuItems: min_spend block');
	}
}
