$(function() {

    resetForm();

    $( "#dialog-form" ).dialog({
	autoOpen: false,
	height: 900,
	width: 600,
	modal: true,
	buttons: {
	    "New Shipment": function() {
		var thisShipmentInputs = $('#ShipmentAddForm').find('input,select');

		$.post('/shipments/ajax_edit', thisShipmentInputs, function(data) {
		    $( "#dialog-form" ).dialog('close');
		    window.location.reload();
		});
					
	    },
	    Cancel: function() {
		$( this ).dialog( "close" );
		$("#ShipmentAddForm")[0].reset();
		$("#principlesList").empty();
	    }
	},
	close: function() {

	    $("#importFields").hide();
	    $("#principle").hide();

	   
	}
    });

    $( "#newShipment" ).button().click(function() {

	$( "#dialog-form" ).dialog( "open" );

    });



    $('#date_arrived_display').datepicker({
	showButtonPanel: true,
	dateFormat: 'd M yy',
	altFormat: 'yy-mm-dd',
	altField: '#date_arrived'
    });



    $("#shipmentType").change(function() {

	var shipmentTypeID = getSelectedID('#shipmentType');

	if(shipmentTypeID == 1) { //Import
	    $("#importFields").show();
	    $("#principle").show();
	}

    });

    //Remove X button clicked.
    $('.removeFromList').live('click', function() {
	$(this).parent().remove();
    });

    

    $('#addPrinciple').button().click(function() {

	var principleID = getSelectedID('#PrinciplePrinciple');

	if($('#PrincipleID_'+principleID).length > 0) { //This Principle is already in the List. Don't do anything.'
	    return false;
	}

	var principleName =getSelectedText('#PrinciplePrinciple');

	//addPrincipleToList(principleID);
	addToList('Principle', principleID, principleName, $('#principlesList') );

	return false;

    });


    $( "#purchase_order_autocomplete" ).autocomplete({
	source: "/purchase_orders/autocomplete",
	minLength: 2,
	select: function( event, ui ) {
	    //alert(ui.item.value + ":" + ui.item.id);
	    //alert($('#PurchaseOrderID_'+ui.item.id).length);

		
	    if($('#PurchaseOrderID_'+ui.item.id).length == 0) { //This Principle is already in the List. Don't do anything.'
		addToList('PurchaseOrder', ui.item.id, ui.item.value, $('#purchaseOrdersList'));
	    }


	}
    });

    $( "#job_autocomplete" ).autocomplete({
	source: "/jobs/autocomplete",
	minLength: 2,
	select: function( event, ui ) {
	    //alert(ui.item.value + ":" + ui.item.id);
	    
	    if($('#JobID_'+ui.item.id).length == 0) { //This Principle is already in the List. Don't do anything.'
		addToList('Job', ui.item.id, ui.item.value, $('#jobsList'));
	    }

	    
	}
    });


    /**
     * Resets the Form to its default site
     */

    function resetForm() {

	$(".hiddenDefault").hide();
	$("#principle").hide();
	$("#ShipmentAddForm")[0].reset();
    }


 
    /**
     * A more generic way of handling the HABTM <ul> <li>[REMOVE BUTTON] NAME [HIDDEN INPUT]</li> </ul>
     */
    function addToList(modelName, id, value, ULelement) {
	var thisLI = $('<li></li>');
	var thisButton = $('<button>X</button>');
	thisButton.addClass('removeFromList');
	thisButton.button();

	var thisHiddenInput = $('<input type="hidden">');

	var modelString = '['+modelName+']';
	thisHiddenInput.attr('name', 'data'+modelString+modelString+'[]');
	thisHiddenInput.attr('value', id);

	thisLI.attr('id', modelName+'ID_'+id);
	thisLI.html(value);
	thisLI.prepend(thisButton);
	thisLI.append(thisHiddenInput);
	ULelement.append(thisLI);

    }


    function getSelectedID(elementID) {
	var id;
	$(elementID+" :selected").each(function(i, selected) {
	    id = this.value;
	});
	return id;
    }

    function getSelectedText(elementID) {
	var text;
	$(elementID+" :selected").each(function(i, selected) {
	    text = $(selected).text();
	});
	return text;
    }



});