$(document).ready( function(){

	//If location is set then show tables.
	getLocationTables($('input#location_id').val());

	$('select#select_location_id').change(function(){
		var location_id = $(this).val();
		getLocationTables(location_id);
	});

	$(document).on('click', 'button.add_modifier', function(){
		var checkbox = $(this).closest('div.modal-content').find('input:checked');
		selected = [];
		checkbox.each(function(){
   			selected.push($(this).val());
		});
		var index = $(this).closest('div.modal-content').find('input.index').val();
		add_selected_modifiers(selected, index);
	});
	$(document).on('click', '#refresh_orders', function(){
		refresh_orders();
	});
});

function getLocationTables(location_id){
	var transaction_id = $('span#restaurant_module_span').data('transaction_id');

	if(location_id != ''){
		$.ajax({
			method: "GET",
			url: '/modules/data/get-pos-details',
			data: {'location_id': location_id, 'transaction_id': transaction_id},
			dataType: "html",
			success: function(result){
				$('span#restaurant_module_span').html(result);
			}
		});
	}
}

function add_selected_modifiers(selected, index){
	if(selected.length > 0){
		$.ajax({
			method: "GET",
			url: '/modules/add-selected-modifiers/',
			data: {selected: selected, index: index},
			dataType: "html",
			success: function(result){
				if(result != ''){
					$('table#pos_table tbody').find("tr").each( function(){
						if($(this).data('row_index') == index){
							$(this).find('td:first .selected_modifiers').html(result);
							return false; 
						}
					});

					//Update total price.
					pos_total_row();
				}
			}
		});
	} else {
		$('table#pos_table tbody').find("tr").each( function(){
			if($(this).data('row_index') == index){
				$(this).find('td:first .selected_modifiers').html('');
				return false; 
			}
		});
	}
}

function refresh_orders(){
	$('.overlay').removeClass('hide');
	var orders_for = $('input#orders_for').val(); 
	var service_staff_id = '';
	if($('select#service_staff_id').val()){
		service_staff_id = $('select#service_staff_id').val();
	}
	$.ajax({
        method: "POST",
        url: '/modules/refresh-orders-list',
        data:{ orders_for:orders_for, service_staff_id: service_staff_id },
        dataType: "html",
        success: function(data){
            $('#orders_div').html(data);
            $('.overlay').addClass('hide');
        }
    });
}