var Accounts = {
	tourId: "",
	supplier: "",
	entryType: "",
	lineItemIds: [],
	lineDebitAccounts: [],
	lineDescriptions: [],
	init: function(){
		
		$("input#ac_start_date").datepicker( { dateFormat: 'yy-mm-dd' }  );
//		$("input#ac_start_date").datepicker( { dateFormat: 'dd-M-yy' }  );
		$("input#ac_end_date").datepicker( { dateFormat: 'yy-mm-dd' }  );
		Accounts.hidePickerSelect();
	},
	live: function(){
		
		$("input#ac_start_date").datepicker( { dateFormat: 'yy-mm-dd' }  );
//		$("input#ac_start_date").datepicker( { dateFormat: 'dd-M-yy' }  );
		$("input#ac_end_date").datepicker( { dateFormat: 'yy-mm-dd' }  );
		Accounts.hidePickerSelect();
		jQuery('div#ac-picker input[type=radio]').live('click', function(e) {
				button = $(e.target);
				Accounts.showPickerSelect( button.val() );
		});
		jQuery('input#invoice-multiple').live('click', function(e) {
				Accounts.invoiceMultiple();
				return false;
		}); 
		jQuery('input#invoice-attach').live('click', function(e) {
				Accounts.invoiceAttach();
				return false;
		}); 
		jQuery('input#ac-tours').live('click', function(e) {
				Accounts.fetchTours();
				return false;
		}); 
		jQuery('input#invoices_delete_button').live('click', function(e) {
				Accounts.deleteInvoice();
				return false;
		}); 
		jQuery('div#ac-picker select.line_items').live('change', function(e) {
				Accounts.pickerSelection( e.target );
		});
		jQuery('#ac-picker div.user .as-close').live('mouseup', function(e) { 
			jQuery('#ac-picker input[name=ac-pick-user]').show();
			$('#ac_picked_user_id').val( "" );
		} );
		jQuery('#ac-picker div.supplier .as-close').live('mouseup', function(e) { 
			jQuery('#ac-picker input[name=ac-pick-supplier]').show();
			$('#ac_picked_supplier_id').val( "" );
		} );
		jQuery('#ac-picker #tour-PAL').live('click', function(e) {
			tour_id = $('#ac_picked_tour').val();
			if (tour_id != "") {
				Accounts.tourPAL( tour_id );
			}
			else { $('#flash').html('Tour must be selected'); };
			return false;
		} );
		jQuery('#ac-picker #ac-PAL').live('click', function(e) {
			Accounts.acPAL();
			return false;
		} );
		jQuery('#ac-picker .create-invoice').live('click', function(e) {
			entry_type = $( this ).attr('rel');
			switch (entry_type) {
//				case 'sales':
//					tour_id = $('#ac_picked_tour').val();
//					if (tour_id != "") {
//						Accounts.newSalesInvoice( entry_type, tour_id );
//					}
//					else { $('#flash').html('Tour must be selected'); };
//					break;
//				case 'direct_expense':
//					tour_id = $('#ac_picked_tour').val();
//					supplier_name = $('#ac-picker .supplier li').first().text();
//					supplier_name = supplier_name.substr( 1, supplier_name.length - 1 ) 
////					alert( supplier_name );
//					debit_account = $('#direct_expense option:selected').val();
////					alert( debit_account );
//					if ( tour_id != "" && supplier_name != "" && debit_account != ""  ) {
//						Accounts.directInvoice( entry_type, tour_id, supplier_name, debit_account );
//					}
//					else { $('#flash').html('Tour, Supplier & Account must be selected'); };
//					break;
				case 'expense':
//					debit_account = $('#indirect_expense option:selected').val();					
//					supplier_name = $('#ac-picker .supplier li').first().text();
//					supplier_name = supplier_name.substr( 1, supplier_name.length - 1 ) 
//					if ( debit_account != ""  && supplier_name != "") {
						Accounts.expenseInvoice( entry_type );
//					}									
//					else { $('#flash').html('Supplier & Account must be selected'); };
					break;
//				case 'indirect_expense':
//					debit_account = $('#indirect_expense option:selected').val();					
//					supplier_name = $('#ac-picker .supplier li').first().text();
//					supplier_name = supplier_name.substr( 1, supplier_name.length - 1 ) 
//					if ( debit_account != ""  && supplier_name != "") {
//						Accounts.expenseInvoice( entry_type, debit_account, supplier_name );
//					}									
//					else { $('#flash').html('Supplier & Account must be selected'); };
//					break;
//				case 'fixed_asset':
//					supplier_name = $('#ac-picker .supplier li').first().text();
//					supplier_name = supplier_name.substr( 1, supplier_name.length - 1 ) 
//					debit_account = $('#fixed_asset option:selected').val();
//					if ( debit_account != ""  && supplier_name != "") {
//						Accounts.expenseInvoice( entry_type, debit_account, supplier_name );
//					}									
//					else { $('#flash').html('Supplier & Account must be selected'); };
//					break;
			};
			return false;
		} );
		$('#invoice_issue_date').live('change', function(e) { 
//			alert(  $('#invoice_issue_date').val() );
			$('#invoice_new_bank_entry_attributes__entry_date').val( $('#invoice_issue_date').val() );
			currency = $('#invoice_currency option:selected').val();
			if ( currency != '' && currency != 'GBP' ) {
				Accounts.getCurrencyRate( $('#invoice_issue_date').val(), currency );
			};
		} );
		$('#invoice_currency').live('change', function(e) { 
			currency = $('#invoice_currency option:selected').val();
			switch ( currency ) {
				case 'GBP' :
					$('#invoice_currency_rate').val( 1 );
					$('#payment_currency_rate').text( "1.00" );
					break;
				default :
					Accounts.getCurrencyRate( $('#invoice_issue_date').val(), currency );
					break;
			};
		} );
		
		$('#invoice_new_line_item_attributes__debit_account').live('change', function(e) { 
//			alert(  debit_account = $('#invoice_new_line_item_attributes__debit_account option:selected').val() );
			debit_account = $('#invoice_new_line_item_attributes__debit_account option:selected').val();
			debit_account = debit_account[0].toUpperCase() + debit_account.substr( 1, debit_account.length  - 1 ) ;
			$('#invoice_new_line_item_attributes__description').val( debit_account );
			$('#invoice_new_bank_entry_attributes__description').val( debit_account );
		} );
		$('#invoice_new_line_item_attributes__description').live('change', function(e) { 
//			alert(  $('#invoice_new_line_item_attributes__description').val() );
			$('#invoice_new_bank_entry_attributes__description').val( $('#invoice_new_line_item_attributes__description').val() );
		} );
		$('#expense_items_form .expense_net_amount').live('change', function(e) { 
			Accounts.setInvoiceTotals();
		} );
		$('#expense_items_form select[id$=tax_rate]').live('change', function(e) { 
//		alert("Woof");
			Accounts.setInvoiceTotals();
		} );
		$('#tour_accounts_items input[type=checkbox]').live('click', function(e) { 
			element = $( this );
			Accounts.tourId = $('#tourPAL-id').text();
			Accounts.entryType = 'direct expense';
			Accounts.supplier = element.parent().parent().find('td.description').attr('supplier');
			if ( Accounts.supplier != ''){
				Accounts.checkSupplier();							
			};
		} );
		
	},
	acPAL: function() {
			startDate = $('#ac_start_date').val();
			endDate = $('#ac_end_date').val();
			dateRange = $('#ac_date_range option:selected').val();
			$.ajax({
				type: 'GET',
				url: "/query/acPAL",
				data: "ac_start_date=" + startDate + "&ac_end_date=" + endDate  + "&ac_date_range=" + dateRange,
				complete: function(html){
					$('#tripmain').html(html.responseText);
				}
			});
	},
	invoiceMultiple: function() {
		itemIds = "";
		descriptions = "";
		debitAccounts = "";
		if (Accounts.lineItemIds.length > 0) {
			for (var i = 0; i < Accounts.lineItemIds.length; i++) {
				itemIds += "&item_id[]=" + Accounts.lineItemIds[i];
				descriptions += "&description[]=" + Accounts.lineDescriptions[i];
				debitAccounts += "&debit_account[]=" + Accounts.lineDebitAccounts[i];
			};
			//		alert( itemIds );
			$.ajax({
				type: 'GET',
				url: "/invoices/new",
				data: "multiple=true&supplier_name=" + Accounts.supplier + "&entry_type=direct_expense" +
				"&tour_id=" +
				Accounts.tourId +
				itemIds +
				descriptions +
				debitAccounts ,
				complete: function(html){
					$('#tour-editor').html(html.responseText);
				}
			});
		} else {
			$('#flash').html('Select one or more Items');
		};
//		alert("multi");
	},
	invoiceAttach: function() {
		itemIds = "";
		descriptions = "";
		debitAccounts = "";
		invoiceId = $('#tourPAL-invoice option:selected').val();
		if (Accounts.lineItemIds.length > 0 && invoiceId != '' ) {
			for (var i = 0; i < Accounts.lineItemIds.length; i++) {
				itemIds += "&item_id[]=" + Accounts.lineItemIds[i];
				descriptions += "&description[]=" + Accounts.lineDescriptions[i];
				debitAccounts += "&debit_account[]=" + Accounts.lineDebitAccounts[i];
			};
			//		alert( itemIds );
			$.ajax({
				type: 'GET',
				url: "/invoices/" + invoiceId +"/edit",
				data: "multiple=true&supplier_name=" + Accounts.supplier + "&entry_type=direct_expense" +
				"&tour_id=" +
				Accounts.tourId +
				itemIds +
				descriptions +
				debitAccounts ,
				complete: function(html){
					$('#tour-editor').html(html.responseText);
				}
			});
		} else {
			$('#flash').html('Select one or more Items with an existing Invoice');
		};
	},
	
//	tourId: "",
//	supplierName: "",
//	entryType: "",
//	lineItemIds: [],
//	lineDebitAccounts: [],
//	lineDescriptions: [],
	
	checkSupplier: function() {
		checked = $('#tour_accounts_items input[type=checkbox]');
		i = 0;
		checked.each( function() {
			checkbox = $( this );
			row = checkbox.parent().parent();
			if ( checkbox.attr('checked') == true && checkbox.parent().parent().find('td.description').attr('supplier') == Accounts.supplier ) {
				Accounts.lineItemIds[i] = checkbox.val();
				Accounts.lineDebitAccounts[i] = row.find('td.debit').attr('account');
				Accounts.lineDescriptions[i] = row.find('td.description').text();
				i += 1;
			} else {
				checkbox.attr('checked', false );
			};
		});
//		alert( Accounts.lineItemIds.length );
//		alert( Accounts.supplier );
		if ( Accounts.lineItemIds.length > 0 ) {
			Accounts.getSupplierInvoices( Accounts.supplier )		
		};
	},
	getSupplierInvoices: function( supplier ) {
		$.ajax({
			type:		'GET',
			url:		"/invoices/supplier",
			data:		"supplier_name=" + supplier + "&type=direct expense",
			complete:	function( invoiceData ){
				var options = "";
				invoices = JSON.parse(invoiceData.responseText);
				if (invoices.length == 0) {
					var options = "<option value=''>No invoices</option>";				
				} else {
					for ( var i=0; i< invoices.length; i++){
						options += "<option value='" + invoices[i].id + "'>" + "[" + invoices[i].id + "] " + invoices[i].issue_date + "</option>";
					};
				};
				$('#tourPAL-invoice').html( options );
			}
		});
	},
	setInvoiceTotals: function() {
//		alert("In");
	// get each net_amount, get_each VAT rate, get_currency_rate - calc total for each item & add -> payment amount = invoice total 
		net_amounts = $('#expense_items_form .expense_net_amount');
//		VAT_rates = $('#expense_items_form .expense_VAT_rate option:selected');
//		item_total = $('#expense_items_form span.expense_GBP_amount');
		line_total = 0;
		line_tax = 0;
		total_amount = 0;
		total_tax = 0;
	    currency_rate = $('#invoice_currency_rate').val();
		net_amounts.each( function() {
			element =  $(this);
			net_amount = Number( element.val() );
			VAT_rate = Number( element.siblings('select').first().find('option:selected').val() );
			line_tax = Math.round( net_amount * VAT_rate * 100 ) /100 ;
			line_total = ( net_amount + line_tax ) / currency_rate ;
			element.siblings('span').first().text( line_tax.toFixed(2) );
			element.siblings('span').last().text( line_total.toFixed(2) );
			element.siblings('input:eq(0)').val( line_tax );
			element.siblings('input:eq(1)').val( line_total );
			total_amount += line_total;
			total_tax += line_tax;
		});
//		alert($('#bank_entries input[id$=bank_entry_attributes__amount]').last().attr('id'));
		$('#bank_entries input[id$=bank_entry_attributes__amount]').val( total_amount.toFixed(2) );
		$('#show_invoice_total_amount').text( total_amount.toFixed(2) );
		$('#show_invoice_tax_amount').text( total_tax.toFixed(2) );
		$('#invoice_total_amount').val( total_amount.toFixed(2) );
		$('#invoice_tax_amount').val( total_tax.toFixed(2) );
//		alert( total_amount );
	},
	newSalesInvoice: function( entry_type, tour_id ) {
		$.fn.colorbox({
			href: "/invoices/new?entry_type=" + entry_type + "&tour_id=" + tour_id,
			width: "60%",
			opacity: 0.8
		});
	},
	editInvoice: function( id ) {
		$.fn.colorbox({
			href: "/invoices/" + id + "/edit",
			width: "60%",
			opacity: 0.8
		});
//		alert( id );
	},
	deleteInvoice: function() {
		row = $('#gview_invoices tr[aria-selected=true]');
		id = row.find( 'td:first').text();
		if (id != "") {
			$.ajax({
				type: 'DELETE',
				url: "/invoices/" + id,
				complete:	function() {
					row.find('td *').css( { color: 'red' } );
				}
			});
		} else {
			$('#flash').html('Select an Invoice to delete');
		};
	},
	tourPAL: function( id ) {
		$.ajax({
			type:		'GET',
			url:		"/tours/accounts/" + id
		});
	},
	paymentInit: function() { 
		$("#expense-form .date_entry").datepicker( { dateFormat: 'yy-mm-dd' }  );
		$("#supplier_name").autocomplete({
			// TODO doesn't work when loaded from /demos/#autocomplete|remote
			source: "/suppliers",
			minLength: 2,
			select: function(event, ui) {
				if (ui.item) {
					currency = ( ui.item.currency && ui.item.currency != "" ) ? ui.item.currency : 'GBP'
					$('#invoice_currency option').removeAttr('selected');
					$('#invoice_currency option[value=' + currency + ']').attr('selected', 'selected');
					if ( ui.item.currency != 'GBP' ) {
						rate = Accounts.getCurrencyRate( $('#invoice_issue_date').val(), currency ) ;	
					} else {
						rate = 1;
					};
					$('#invoice_currency_rate').val( rate );
				};
				
			}
		});
	},
	invoicesGridInit: function() {
		$('input#invoices_delete_button').confirm({
		  msg:'Confirm deletion',
		  timeout:3000
		});
	},
	getCurrencyRate: function( date, currency ) {
		$.ajax({
			type:		'GET',
			url:		'/currency_rates/show',
			data: 		'date=' + date + '&currency=' + currency,
			complete:	function( data ){
				rate = JSON.parse(data.responseText).rate;
				$('#invoice_currency_rate').val( rate );
				$('#payment_currency_rate').text( rate );
				console.log(data);
			}
		});
		
	},
	expenseInvoice: function( entry_type ) {
//		params = "entry_type=" + entry_type;
//		params = params.replace( /\s/g, "%20" );
		$.ajax({
			type:		'GET',
			url:		'/invoices/new',
			data: 		'entry_type=' + entry_type.replace( /\s/g, "%20" )
		});
//		$.fn.colorbox({
//			href: "/invoices/new?" + params,
//			width: "60%",
//			opacity: 0.8
//		});
	},
//	directInvoice: function( entry_type, tour_id, supplier_name, debit_account ) {
//		params = "entry_type=" + entry_type + "&tour_id=" + tour_id  + "&supplier_name=" + supplier_name  + "&debit_account=" + debit_account;
//		params = params.replace( /\s/g, "%20" );
//		$.fn.colorbox({
//			href: "/invoices/new?" + params,
//			width: "60%",
//			opacity: 0.8
//		});
//	},
	hidePickerSelect: function() {
		$("div#ac-picker select#indirect_expense").hide();
		$("div#ac-picker select#direct_expense").hide();
		$("div#ac-picker select#fixed_asset").hide();
		$("div#ac-picker select#line_item_type").hide();
	},
	showPickerSelect: function( buttonVal ) {
		Accounts.hidePickerSelect();
		switch( buttonVal ) {
			case 'Line Items' :
				$("select#indirect_expense").show();
				$("select#direct_expense").show();
				$("select#fixed_asset").show();
				$("select#line_item_type").show();
				break;
			case 'Bank Entries' :
				$("select#bank_account").show();		
				break;	
		}
	},
	pickerSelection: function( target ) {
		select = $( target );
		$('#line_item_type').val( select.attr('id') ) ;
		value = select.find( 'option:selected').val();
		if ( value == "" ) {
			jQuery('div#ac-picker select.line_items').show();
			jQuery('div#ac-picker select#line_item_type').show();
		} else {
			Accounts.hidePickerSelect();
			select.show();	
		}

//		alert(select.attr('id') );		
//		alert($('#line_item_type').val() );		
	},
	acAsUser: function(data) {
		$("input#ac-pick-user").autoSuggest( Search.getClientelle(), 
					{ selectedItemProp: "name", 
					  searchObjProps: "name",
					  startText: "User name",
					  resultClick: function(data){ Accounts.acPicked(data, "user");
					}
		});
	},
	acAsSupplier: function(data) {
		$("input#ac-pick-supplier").autoSuggest( Search.getDirectory(), 
					{ selectedItemProp: "name", 
					  searchObjProps: "name",
					  startText: "Supplier name",
					  resultClick: function(data){ Accounts.acPicked(data, "supplier");
					}
		} );
	},
	fetchTours: function(data) {
		user_id = $('#ac_picked_user_id').val();
		supplier_id = $('#ac_picked_supplier_id').val();
		match = $('#ac-pick-name').val();
		$.ajax({
			type:		'GET',
			url:		'/tours/ac_tours',
			data: 		'user_id=' + user_id + "&supplier_id=" + supplier_id + "&match=" + match,
			complete: function(data){
				tours = JSON.parse(data.responseText);
//				console.log(tours);
				tOptions = "<option value=''>Tours</option>";
//				alert( tOptions );
				for ( var i = 0; i < tours.length; i++ ){
					tOptions += "<option value='" + tours[i].id + "'>" + tours[i].name + "</option>";
//				alert(tOptions);
				};
				$('#ac_picked_tour').html( tOptions );
//				alert("Woof");
			}
		});
	},
	acPicked: function( data, object ) {
		switch ( object ) {
			case 'supplier' :
				$('#ac_picked_supplier_id').val( data.attributes.value );
				$('#ac-picker input[name=ac-pick-supplier]').hide();
			 	break;
			case 'user' :
				$('#ac_picked_user_id').val( data.attributes.value );
				$('#ac-picker input[name=ac-pick-user]').hide();
			 	break;
		};
	},
	bankEntryProcess: function() {
		currency = $('#currency').text();
		switch ( currency ){
			case 'USD' :
				currencyFormat = 'en-US';
				break;
			case 'ZAR' :
				currencyFormat = 'af-ZA';
				break;
			case 'GBP' :
				currencyFormat = 'en-GB';
				break;
			default :
				currencyFormat = '';
				break;
		};
		$('#opening-balance-show').formatCurrency({ colorize:true, region: currencyFormat });
		new_balance = Number($('#starting_balance').val());
		bank_name = $('#bank_name').val();
		if ( new_balance == "" ) { new_balance == 0 };
		entries = $('#gview_bank_entries tbody tr');
		entries.each(function(i){
			entry = $(this);
			amount_entry = entry.find('td').eq(3);
			entry_amount = Number( amount_entry.text());
			amount_entry.formatCurrency({ colorize:true, region: currencyFormat });
			new_balance = (entry.find('td').eq(4).text() == bank_name) ? new_balance + entry_amount : new_balance - entry_amount
			entry.find('td').last().text(new_balance).formatCurrency({ colorize:true, region: currencyFormat });
		});
	},
	lineItemProcess: function() {
		VAT_total = 0;
		gbp_total = 0;
		entries = $('#gview_line_items tbody tr');
		entries.each(function(i){
			entry = $(this);
			VAT_total += Number( entry.find('td').eq(4).text());
			
			gbp_cell = entry.find('td').eq(7)
			gbp_total += Number( gbp_cell.text());
			gbp_cell.formatCurrency({ colorize:true, region: 'en-GB' })
		});
		$('#VAT_total').html( VAT_total ).formatCurrency({ colorize:true, region: 'en-GB' });
		$('#gbp_total').html( gbp_total ).formatCurrency({ colorize:true, region: 'en-GB' });
	}
	
}
