/* Your Patch Online Order Module */

jQuery(document).ready( function ($) {

	var base = "#yourpatchorder ";
	
	if (typeof(yourPatchOrder) == 'undefined') {
		// The customer hasn't defined the number of beds yet
		return true;
	}
	
	// Confirmation message for order reset button
	$(base + '#reset_order').submit(function(){ return confirm('Are you sure you want to restart your order?'); });

	// Configure the messages dialog box
	var dialog = $(base + 'div.messages')
		.append(yourPatchLoading)
		.dialog({
			autoOpen: false,
			bgiframe: true,
			buttons: {},
			closeOnEscape: false,
			dialogClass: 'loadingdialog',
			draggable: false,
			height: 100,
			minHeight: 10,
			modal: true,
			resizable: false,
			title: 'Loading ...',
			width: 300
	});
	
	// Configure the instructions dialog box
	var instructions = $(base + 'div.instructions').dialog({
		autoOpen: false,
		bgiframe: true,
		buttons: { 
			"Ok": function() { 
				$(this).dialog("close");
			} 
		},
		closeOnEscape: true,
		dialogClass: 'instructionsdialog',
		draggable: true,
		height: 380,
		minHeight: 10,
		//modal: true,
		resizable: true,
		title: 'Instructions',
		width: 600
	});
	
	showLoadingMessage();
	
	// Set up draggable plants
	$(base + ".drag").draggable({
		helper: 'clone',
		revert: 'invalid', // when not dropped, the item will revert back to its initial position
		cursor: 'move'
	});
	
	// Loop over the two plant types and initialise the droppable areas
	var types = new Array('seed', 'herb');
	for (var index in types) {
		var type = types[index];
	
		$(base + ".drop.accept" + type).droppable({
			accept: base + "." + type,
			activeClass: 'active',
			hoverClass: 'hover',
			drop: function(ev, ui) {
			    var item = $(ui.draggable);
			    
			    var plantID = $(item).attr('id');
			    
			    var plantData = $('#' + plantID).data('data');
			    
			    var bedID = $(this).attr('id');
			    
			    var newTums = yourPatchOrder['beds'][bedID]['tums'];
			    
			    newTums = parseFloat(newTums) + parseFloat($('#' + plantID).data('data').tum);
	
			    if (yourPatchOrder['beds'][bedID]['capacity'] > 0 && (newTums > yourPatchOrder['beds'][bedID]['capacity'])) {
			    	alert('Sorry, this garden bed is too full');
			    	return false;
			    }
			    
			    if (newTums >= yourPatchOrder['beds'][bedID]['capacity']) {
			    	$('#' + bedID).addClass('full');
			    } else {
			    	$('#' + bedID).removeClass('notfull');
			    }
	
		    	// Update the bed's contents
		    	if ( typeof(yourPatchOrder['beds'][bedID]['contents'][plantData.id]) == 'undefined') {
		    		yourPatchOrder['beds'][bedID]['contents'][plantData.id] = 1;
		    	} else {
		    		yourPatchOrder['beds'][bedID]['contents'][plantData.id] += 1;
		    	}
		    	
		    	UpdateOrder(bedID);
			}
		});
	}

	// Get the initial order details and then show the order form
	$.get(yourPatchAjaxURL, {
	    'action': "yourpatch_order_get"
	  }, function(result) {
		  // Process the result
			  yourPatchOrder = result;
			  UpdateDisplay();
			  $(base + 'div.content').show();
			  $(instructions).dialog('open');
	  },
	  'json'
	);
	
	function showLoadingMessage() {
		$(dialog).dialog('open');
	}
	
	function hideLoadingMessage() {
		$(dialog).dialog('close');
	}
	
	function UpdateDisplay() {
		for (var bedID in yourPatchOrder['beds']) {
			refreshBed(bedID);
		}
		hideLoadingMessage();
	}
	
	function UpdateOrder(bedID) {
		showLoadingMessage();
		
		$.get(yourPatchAjaxURL, {
		    'action': "yourpatch_order_save",
		    'order': JSON.stringify(yourPatchOrder)
		  }, function(result) {
			  // Process the result
			  if (result.status == 0) {
				  yourPatchOrder = result.order;
				  UpdateDisplay();
			  }
		  },
		  'json'
		);
	}
	
	// Decrease quantity by one button
	$(base + 'div.drop a.delete').live('click', function() {
			var plantID = $(this).parent().attr('class').replace('plant_','');
			var bedID = $(this).parents('div.drop').attr('id');
			
			if (yourPatchOrder['beds'][bedID]['contents'][plantID] >= 1) {
				yourPatchOrder['beds'][bedID]['contents'][plantID]--;
			} else {
				yourPatchOrder['beds'][bedID]['contents'][plantID] = 0;
			}

			UpdateOrder();
			
			return false;
	});
	
	// Submit order button
	$(base + '#submit_order').live('click', function(){ 
		showLoadingMessage();
		$.get(yourPatchAjaxURL, {
		    'action': "yourpatch_order_submit",
		    'order': JSON.stringify(yourPatchOrder)
		  }, function(result) {
			  // Process the result
			  hideLoadingMessage();
			  if (result.status == 0) {
				  $(base).html(result.html);
			  }
		  },
		  'json'
		);
	});

	function refreshBed(bedID) {
		
		var html = '<ul>';
	  
    	for( var plantID in yourPatchOrder['beds'][bedID]['contents']) {
            var qty = yourPatchOrder['beds'][bedID]['contents'][plantID];
            
            html += '<li class="plant_' + plantID + '">' + qty + ' x ' + $('#plant_' + plantID).data('data').name + ' ' + yourPatchDelete + '</li>';
        }
    	
    	$('#' + bedID + ' div.contents').html(html);

    	$('#' + bedID + ' .tums').text(yourPatchOrder['beds'][bedID]['tums']);
    	
    	if (yourPatchOrder['beds'][bedID]['capacity'] > 0) {
    		$('#' + bedID + ' .capacity').text(yourPatchOrder['beds'][bedID]['capacity']);
    	}
    	
    	if (typeof(yourPatchOrder['beds'][bedID]['percent_full']) != 'undefined') {
    		$(base +'#' + bedID + ' .percentfull .percent').text(yourPatchOrder['beds'][bedID]['percent_full']);
    		$(base + '#totals .' + bedID + ' .percent').text(yourPatchOrder['beds'][bedID]['percent_full']);
    	}
    }
});


function debug(message) {
    if (window.console) {
      console.log(message);
    }
}