$(function() {

    var addedBoxes = $(".boxForm").length;
    var addedInvoices = $('.invForm').length;



    $('button').button();
    displayReleventFields();

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


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


    $('.date_paid').datepicker({
	showButtonPanel: true,
	dateFormat: 'yy-mm-dd'
    });


    $('.date_issued').datepicker({
	showButtonPanel: true,
	dateFormat: 'yy-mm-dd'
    });

    /**
     * Display the relevent elements depending on this Shipment Type */
    $("#shipmentType").change(function() {
	displayReleventFields();

    });

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

    //Add a new Freight Forwarder.
    $('.addFreightForwarder').live('click', function() {
	$('#newFreightForwarderDiv').show();
	$(this).hide();
    });

    //Cancel adding a new Freight Forwarder.
    $('.cancelNewFF').live('click', function() {
	$('#newFreightForwarderDiv').hide();
	$('.addFreightForwarder').show();
    });

    //Save the new Freight Forwarder.  **TODO : Handle errors **.
    $('.saveNewFF').live('click', function() {

	$.post('/freight_forwarders/ajax_add', $('#newFreightForwarder'), function(data) {
	    if(data == 'SUCCESS') {
		$.get('/freight_forwarders/build_options', function(newOptions) {
		    $('#ShipmentFreightForwarderId').html(newOptions);
		    $('#newFreightForwarderDiv').hide();
		    $('.addFreightForwarder').show();
		});
	    }
	});
    });

    //Add a(nother) Principle to this Shipment
    $('#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 ) {
	
	    if($('#PurchaseOrderID_'+ui.item.id).length == 0) { //This PO is already in the List. Don't do anything.'
		addToList('PurchaseOrder', ui.item.id, ui.item.value, $('#purchaseOrdersList'));
		
		$.getJSON('/purchase_orders/getdata/'+ui.item.id, function(data) {
		    //console.log(data);
		    //alert(data.Principle.id+' '+data.Principle.name);
		    addToList('Principle', data.Principle.id, data.Principle.name, $('#principlesList'));

		    $.each(data.Job, function(key, job) {
			addToList('Job',job.id, job.title, $('#jobsList'));
		    });

		});
	    }


	}
    });

    $( "#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 Job is already in the List. Don't do anything.'
		addToList('Job', ui.item.id, ui.item.value, $('#jobsList'));


		$.getJSON('/jobs/getdata/'+ui.item.id, function(data) {
		    //console.log(data);
		    //alert(data.Principle.id+' '+data.Principle.name);
		    $("#customer_autocomplete").val(data.Customer.name);
		    $("#customer_id").val(data.Customer.id);

		    $.get('/addresses/customerAddresses/'+data.Customer.id, function(addressdata) {
			$("#address").html(addressdata);
			$(".selectAddress", addressdata).button();
		    });

		});

	    }
	}
    });


    $("#customer_autocomplete").autocomplete({
	source: "/customers/completeCustomer",
	minLength: 2,
	select: function( event, ui ) {
	    $("#customer_id").val(ui.item.id);

	    $.get('/addresses/customerAddresses/'+ui.item.id, function(data) {
		$("#address").html(data);
		$(".selectAddress", data).button();
	    });

	}
    });


    $("#addBox").button().click(function() {
	addBox(addedBoxes);
	addedBoxes++;
    });

    $(".removeBox").live('click',function() {
	$(this).parent().remove();
    });


    $("#addInvoice").button().click(function() {
	addInvoice(addedInvoices);
	addedInvoices++;
    });

    $(".removeInvoice").live('click',function() {
	$(this).parent().remove();
    });



    $(".selectAddress").live('click', function() {
	var ID = $(this).attr('id');
	$("#address_id").val(ID);




	$(this).removeClass('selectAddress');
	$(this).addClass('changeAddress');

	$(".selectAddress").button('disable');
	$(".selectAddress").parent('div').fadeOut();

	$(this).button({
	    label: 'Select a different Address'
	});
	$(this).button('enable');

    });

    $(".changeAddress").live('click', function() {
	$("#address_id").val('');

	$.get('/addresses/customerAddresses/'+$("#customer_id").val(), function(data) {
	    $("#address").html(data);
	    $(".selectAddress", data).button();
	});
	
    });


    function displayReleventFields() {
	var shipmentTypeID = getSelectedID('#shipmentType');
	shipmentTypeID = parseInt(shipmentTypeID);
	$(".hiddenDefault").hide();
	$(".moreInfo").show();
	switch(shipmentTypeID) {
	    case 1: //Import
		$("#importFields,#job,#principle, #purchaseOrder").show();
		$(".moreInfo").hide();
		showCommonFields();
		break;

	    case 2: //Direct
		$("#purchaseOrder, #job,#principle, #dateDispatched, #customer, #address, #addressSpan").show();
		showCommonFields();
		break;
	    case 3: //Export
		$("#job, #dateDispatched, #customer, #address, #addressSpan").show();
		showCommonFields();
		break;
	    case 4: //Local
		$("#job, #dateDispatched, #customer, #address, #addressSpan").show();
		showCommonFields();
		break;
	}
	
    }
    //Show the fields in the shipment form that are available
    //for all 4 cases
    function showCommonFields() {
	$("#airway_bill, #boxes, #invoices, #freight_forwarder, #comments").show();
    }

    function addBox(addedBoxes) {

	var model = 'Box';

	var newBoxForm = $("#boxFactory").clone();

	var boxNo = addedBoxes;

	newBoxForm.removeAttr('id');
	newBoxForm.addClass('boxForm');
	newBoxForm.show();


	var boxFields = ['length', 'width', 'height', 'weight'];

	var div;
	var ID;
	var name;
	
	$.each(boxFields, function(index, field) {
	    div = newBoxForm.find('.'+field);
	    ID = getCakeID(model,boxNo,field);
	    name = getCakeName(model, boxNo, field);
	    div.children('label').attr('for', ID);
	    div.children('input').attr('id', ID).attr('name', name);
	});

	var closeButton = $('<button>X</button>');
	closeButton.addClass('removeBox');
	closeButton.button();

	newBoxForm.prepend(closeButton);

	$("#boxes").append(newBoxForm);
    }


    function addInvoice(addedInvoices) {
	var model = 'ShipmentInvoice';
	var invoiceNo = addedInvoices;

	var newInvoiceForm = $('#invoiceFactory').clone();
	newInvoiceForm.removeAttr('id');
	newInvoiceForm.addClass('invForm');
	newInvoiceForm.show();

	var invFields = ['currency_id','principle_id', 'freight_forwarder_id', 'invoice_number', 'date_issued',
	'invoice_amount','gst_amount','deferred_gst', 'deferred_gst_amount','approved', 'paid', 'date_paid','invoice_type'];

	var div;
	var ID;

	$.each(invFields, function(index,field) {
	    div = newInvoiceForm.find('.inv_'+field);
	    ID = getCakeID(model,invoiceNo, field);
	    name = getCakeName(model, invoiceNo, field);
	    div.children('label').attr('for', ID);
	    div.children(':input').attr('id', ID).attr('name', name);

	    if(field == 'date_issued' || field == 'date_paid') {
		div.children(':input').datepicker({
		    showButtonPanel: true,
		    dateFormat: 'yy-mm-dd'
		});
	    } 

	});

	var closeButton = $('<button>X</button>');
	closeButton.addClass('removeBox');
	closeButton.button();

	newInvoiceForm.prepend(closeButton);

	/* $("#ShipmentInvoice"+invoiceNo+"Date_Issued").datepicker({
	    showButtonPanel: true,
	    dateFormat: 'yy-mm-dd'
	});
	$("#ShipmentInvoice"+invoiceNo+"Date_Paid").datepicker({
	    showButtonPanel: true,
	    dateFormat: 'yy-mm-dd'
	}); */



	$("#invoices").append(newInvoiceForm);
    }

    

    /**
     * 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);

    }

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

    function resetForm() {

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


});
