function parseDate(_str) {
    var _mdy = _str.split('/')
	if (_mdy.length == 3)
	{
    	return new Date(_mdy[2], _mdy[1]-1, _mdy[0]);
	}
	else
	{
		return false;
	}	
}

function dayDiff(_first, _second) {
    return Math.floor(( _second - _first ) / 86400000);
}

$(document).ready(function()
{
	$('#tbxPallets, #tbxLastInvoice, #tbxNextInvoice, #tbxCompany').change(function()
	{
		_company = $('#tbxCompany').val();
		
		if (_company > 0)
		{
			_pallets = parseInt($('#tbxPallets').val());
			
			_lastInvoice = parseDate($('#tbxLastInvoice').val());
			_nextInvoice = parseDate($('#tbxNextInvoice').val());
			_cost = _costs[_company];
			
			if (_lastInvoice && _nextInvoice)
			{
				_duration = dayDiff(_lastInvoice,_nextInvoice);
				_total = _duration * _cost * _pallets;
				if (!isNaN(_total))
				{
					$('#tbxCharge').val(_total.toFixed(2));
				}
				else
				{
					$('#tbxCharge').val('');
				}
			}
		}
	});
	
	if ($('input.popdate').length > 0)
	{
		$.getScript('/js/jquery-ui-1.7.3.custom.min.js', function() 
		{
			$('input.popdate').datepicker({dateFormat:'dd/mm/yy',gotoCurrent: true});
		});
	}
	
	$('#actions select').change(function()
	{
		this.form.submit();
		return true;
	});
	
	$('a#addPallet').click(function()
	{
		$('#addPalletForm').slideToggle();
		return false;
	});
	
	$('a.accountDelete').click(function()
	{
		return confirm('You are about to remove a record from the database');
	});
	
	$('#addPalletForm form').submit(function()
	{
		_q = $('#tbyQuantity').val();
		if (_q.length > 0)
		{
			_s = $('#tbySite').val();
			_r = $('#tbyRack').val();
			_h = $('#tbyHeight').val();
			_v = $('#tbyVertical').val();
			_i = $('#tbyId').val();
			
			_parameters = 'ajax=1&tbyId='+_i+'&tbySite='+_s+'&tbyRack='+_r+'&tbyHeight='+_h+'&tbyVertical='+_v+'&tbyQuantity='+_q;
			
			$.ajax({type: 'POST', url: 'account.html?do=addPallet', data: _parameters, dataType: 'json', success: function(_data) 
			{
				if (_data._ok == '1')
				{
					_new_row = '<tr><td>'+$('#tbySite :selected').text()+'&nbsp;'+_r+_h+_v+'</td><td>'+_q+'</td><td><a href="/account.html?do=deletePallet&amp;id='+_data._id+'" class="accountDelete" title="Delete"><img width="16" height="16" alt="Delete" src="/images/account_delete.png"></a>&nbsp;</td>';
					$('#palletsTable tr:first').after(_new_row);
					
					if (_data._counter < 0)
					{
						$('#palletsTable tr.palletInfo:last').html('<td colspan="3">'+(-1*_data._counter)+'&nbsp;stock items unallocated</td>');
					}
					else if (_data._counter > 0)
					{
						$('#palletsTable tr.palletInfo:last').html('<td colspan="3">'+_data._counter+'&nbsp;stock items over allocated</td>');
					}
					else
					{
						$('#palletsTable tr.palletInfo:last').html('');
						$('a#addPallet').hide();
						$('#addPalletForm').slideUp();
					}
				}
			}});
		}

		return false;
	});
	
});

