var new_items = 0;
var new_payments = 0;
var current_tab = "recipient";
var invoice_id = 0 ;
var autosave_interval_id = null ;

function change_many_status(){
    if (document.adminForm.boxchecked.value==0) {
        alert('Please first make a selection from the list');
    } else {
        var new_val = jQuery('#new_status').val();
        if (new_val == 'no_value'){
            alert('Please select the new status');
        } else {
            jQuery('status_to').val(new_val);
            Joomla.submitbutton('change_status_to_selected');
        }
    }
}

function set_height() {
    if(!is_mobile() || (!split_view && !is_mobile() )){
        var element = jQuery('#invoices-wrapper');
        var space_bottom = jQuery('#status').outerHeight() ;
        var space = window.innerHeight - element.offset().top - space_bottom;

        outer_space = parseInt(space) + 'px';
        inner_space = parseInt(space - 66) + 'px';

        jQuery(".container-wrapper").css('height',outer_space);
        jQuery(".invoice-container").css('height',inner_space);
    }
}

jQuery(document).ready(function() {
    set_height();
    jQuery(window).bind('resize', set_height);
});

//override joomla default submitbutton functions
var Myvar = {};
Myvar.submitbutton = Joomla.submitbutton;
Joomla.submitbutton = function(task) {
    if(task == "add"){
        current_tab = "recipient";
        edit_invoice(new Invoice({id: 0}));
    }
    else if(task == "send_email"){
        var values = jQuery("#invoices-table input[name='cid\\[\\]']:checked").map(function(){return jQuery(this).val();}).get();
        var string = values.join("&cid[]=");
        email_invoice(string, true);
    }
    else if(task == "publish"){
        var values = jQuery("#invoices-table input[name='cid\\[\\]']:checked").map(function(){return jQuery(this).val();}).get();
        var string = values.join("&cid[]=");
        publish_invoice(string, true);
    }
    else if(task == "unpublish"){
        var values = jQuery("#invoices-table input[name='cid\\[\\]']:checked").map(function(){return jQuery(this).val();}).get();
        var string = values.join("&cid[]=");
        unpublish_invoice(string, true);
    }
    else if(task == "remove"){
        var values = jQuery("#invoices-table input[name='cid\\[\\]']:checked").map(function(){return jQuery(this).val();}).get();
        var string = values.join("&cid[]=");
        delete_invoice(string, true);
    }
    else if(task == "change_status_to_selected"){
        var values = jQuery("#invoices-table input[name='cid\\[\\]']:checked").map(function(){return jQuery(this).val();}).get();
        var string = values.join("&cid[]=");
        changestatus_invoice(string, jQuery('#new_status').val(), true);
    }
    else if(task == "duplicate"){
        var values = jQuery("#invoices-table input[name='cid\\[\\]']:checked").map(function(){return jQuery(this).val();}).get();
        var string = values.join("&cid[]=");
        duplicate_invoice(string);
    }
    else if(task == "convert_to_invoice"){
        var values = jQuery("#invoices-table input[name='cid\\[\\]']:checked").map(function(){return jQuery(this).val();}).get();
        var string = values.join("&cid[]=");
        convert_to_invoice(string);
    }
    else if(task == "create_recurring"){
        jQuery.ajax({
            url: "index.php?option=com_invoices&controller=invoice&task=create_recurring&ajax=1",
            dataType: 'json',
            success: function(responseText, textStatus, jqXHR){

                notify_messages(responseText.notifications) ;

                if(responseText.content == '1'){
                    //there were new recurring invoices created, we refresh the list
                    refresh_list();
                }

            }
        });
    }
    else Myvar.submitbutton(task);
}

jQuery( document ).ready(function() {

    var html   = jQuery("#statusoptions-template").html();

    jQuery("#toolbar").append(html);

    var $invoiceContainer = jQuery('.invoice-container');
    var $buttonbarContainer = jQuery('#invoice-buttonbar');

    $invoiceContainer.scroll(function() {
        var scroll = $invoiceContainer.scrollTop();

        if (scroll > 0) {
        $buttonbarContainer.addClass('bottomScrollShadow');
        } else {
        $buttonbarContainer.removeClass('bottomScrollShadow');
        }
    });

    var $invoicesContainer = jQuery('#invoices-wrapper');

    $invoicesContainer.scroll(function() {

        var scroll = $invoicesContainer.scrollTop();

        var $tableheaderContainer = jQuery('.floatThead-container');

        if (scroll > 0) {
        $tableheaderContainer.addClass('bottomScrollShadow');
        } else {
        $tableheaderContainer.removeClass('bottomScrollShadow');
        }
    });

    table_sticky();

});

var $table = null;

function table_sticky(){

    if(!is_mobile()){
        //http://mkoryak.github.io/floatThead/

        $table = jQuery('#invoices-wrapper table');
        $table.floatThead({
            scrollContainer: function($table){
                return $table.closest('#invoices-wrapper');
            },
            position: 'absolute'
        });
    }

}

function table_reflow(){
    if(!is_mobile()){
        $table.floatThead('reflow');
    }
}

function getItem(id, theformid, modalname, importAmount, importAttachment){
    var url = "index.php?option=com_finances&task=getItem&id=" + id ;

    jQuery.ajax({
        url: url,
        cache: false,
        context: document.body,
        dataType: 'json'
    }).done(function(responseText) {

        loadItem(responseText, theformid, modalname, importAmount, importAttachment);
    });
}

function clearFields(modalname){
    jQuery("#itemForm"+modalname+" input[type='text']").each(function(field, i) {

        if (!jQuery( "input[name^='date_item']" ).val()){
            jQuery(this).val( "" );
        }

    });

    jQuery('#long_desctheformid').html("");

    jQuery('#is_recurrenttheformid').prop('checked', false);
    jQuery('#tax_deductabletheformid').prop('checked', false);

    jQuery('attachment_file_theformid').val(""); //Not sure if this does domething

    var opSelect = '0';
    jQuery("#rec_yeartheformid option").filter(function() {
        return jQuery(this).text() == opSelect;
    }).prop('selected', true);
    jQuery("#rec_monththeformid option").filter(function() {
        return jQuery(this).text() == opSelect;
    }).prop('selected', true);
    jQuery("#rec_daytheformid option").filter(function() {
        return jQuery(this).text() == opSelect;
    }).prop('selected', true);

}

function loadModalDetails(url, id){
    var html = '';

    if(!is_mobile() && split_view){

        jQuery('#invoice-paper').html(html);
        jQuery('#loader_preview').show();

    }

}

function loadModalEdit(url, id){
    var html = '';

    jQuery('.maineditbutton').button('loading');

    jQuery.ajax({
        url: url,
        cache: false,
        dataType: 'json',
        success: function(response, textStatus, jqXHR){

            jQuery('.maineditbutton').button('reset');

						//uncomment this line for automatic react between list and form
						vm.current_invoice = new Invoice(response.data);
						prepareEditForm();

            if(is_mobile() || !split_view){
                jQuery('#detailsModal').modal('show');
            }
            else{

                jQuery('#invoice-edit-container [data-toggle="tooltip"]').tooltip();
            }

        }
    });
}

function prepareEditForm(){

	//recipient
	//initializeRecipientNameTypeahead();
	initializeUsernameTypeahead();

	jQuery("#button_search_user").on("click", function(event){
		search_user();
	});

	jQuery("#search_user").on("keypress", function(event){
		if(event.keyCode == 13) search_user();
	});

	//details
	jQuery('#invoice_date_' ).datepicker('update', vm.current_invoice.invoice_date).on('changeDate', function(ev) {
		jQuery('#invoice_date_' ).datepicker('hide');
		vm.current_invoice.invoice_date = moment(ev.date).format('YYYY-MM-DD');
	});

	jQuery("#invoice_date_btn_" ).click(function() {
		jQuery('#invoice_date_' ).datepicker('show');
	});

	jQuery('#invoice_duedate_' ).datepicker('update', vm.current_invoice.invoice_duedate).on('changeDate', function(ev) {
		jQuery('#invoice_duedate_' ).datepicker('hide');
		vm.current_invoice.invoice_duedate = moment(ev.date).format('YYYY-MM-DD');
	});

	jQuery("#invoice_duedate_btn_" ).click(function() {
		jQuery('#invoice_duedate_' ).datepicker('show');
	});

	//publish
	jQuery('#start_publish_' ).datepicker('update', vm.current_invoice.start_publish).on('changeDate', function(ev) {
		jQuery('#start_publish_' ).datepicker('hide');
		vm.current_invoice.start_publish = moment(ev.date).format('YYYY-MM-DD');
	});

	jQuery("#start_publish_btn_" ).click(function() {
		jQuery('#start_publish_' ).datepicker('show');
	});

	jQuery('#end_publish_' ).datepicker('update', vm.current_invoice.end_publish).on('changeDate', function(ev) {
		jQuery('#end_publish_' ).datepicker('hide');
		vm.current_invoice.end_publish = moment(ev.date).format('YYYY-MM-DD');
	});

	jQuery("#end_publish_btn_" ).click(function() {
		jQuery('#end_publish_' ).datepicker('show');
	});

	//recurrency
	jQuery('#rec_nextdate_' ).datepicker('update', vm.current_invoice.rec_nextdate).on('changeDate', function(ev) {
		jQuery('#rec_nextdate_' ).datepicker('hide');
		vm.current_invoice.rec_nextdate = moment(ev.date).format('YYYY-MM-DD');
		jQuery("#row"+vm.current_invoice.id+' [data-toggle="tooltip"]').tooltip();
	});

	jQuery("#rec_nextdate_btn_" ).click(function() {
		jQuery('#rec_nextdate_' ).datepicker('show');
	});

	//history
	get_history(vm.current_invoice.id);

	setTimeout(function(){
		// this is a dirty trick. Since VUE is asynchronous, we wait until the elements are on the page after the v-for elements have rendered...
		//recipient
		initializeRecipientNameTypeahead();

		//items
		jQuery("#items_table").tableDnD({	dragHandle: ".dragHandle",
																			onDragClass: "info",
																			onDrop: function(thetable, therow){
																				// console.log(thetable);
																				// console.log(therow);
																				// console.log(thetable.tBodies[0].rows);
																				var sorting = [];
																				for (var i = 0; i < thetable.tBodies[0].rows.length; i++) {
																					console.log(thetable.tBodies[0].rows[i].getAttribute('data-id'));
																					sorting.push(thetable.tBodies[0].rows[i].getAttribute('data-id'));
																				}
																				console.log(vm.current_invoice.items)

																				var result = []

																				var items = vm.current_invoice.items

																				sorting.forEach(function(key) {
																				    var found = false;
																				    items = items.filter(function(item) {
																				        if(!found && item.id == key) {
																				            result.push(item);
																				            found = true;
																				            return false;
																				        } else
																				            return true;
																				    })
																				})
																				console.log(result);
																				vm.current_invoice.items = result;
																				// result.forEach(function(item) {
																				//     document.writeln(item[0]) /// Bob Jason Henry Thomas Andrew
																				// })
																				//
																				return false;

																			}
																		});

		//payments
		jQuery("#payments_table").tableDnD({dragHandle: ".dragHandle", onDragClass: "info"});

		for (var i = 0; i < vm.current_invoice.payments.length; i++) {

		  jQuery('#payment_duedate_' + vm.current_invoice.payments[i].id).datepicker('update', vm.current_invoice.payments[i].payment_duedate).on('changeDate', function(ev) {
				var index = ev.target.getAttribute("data-index");
		    jQuery('#payment_duedate_' + vm.current_invoice.payments[index].id).datepicker('hide');
				vm.current_invoice.payments[index].payment_duedate = moment(ev.date).format('YYYY-MM-DD');
		  });

		  jQuery("#payment_duedate_btn_" + vm.current_invoice.payments[i].id).click(function(ev) {
				var index = jQuery(this).attr('data-index');
		    jQuery('#payment_duedate_' + vm.current_invoice.payments[index].id).datepicker('show');
		  });

		  jQuery('#payment_datetime_' + vm.current_invoice.payments[i].id).datepicker('update', vm.current_invoice.payments[i].payment_datetime).on('changeDate', function(ev) {
				var index = ev.target.getAttribute("data-index");
		    jQuery('#payment_datetime_' + vm.current_invoice.payments[index].id).datepicker('hide');
				vm.current_invoice.payments[index].payment_datetime= moment(ev.date).format('YYYY-MM-DD');
		  });

		  jQuery("#payment_datetime_btn_" + vm.current_invoice.payments[i].id).click(function(ev) {
				var index = jQuery(this).attr('data-index');
		    jQuery('#payment_datetime_' + vm.current_invoice.payments[index].id).datepicker('show');
		  });
		}

	},100);

	table_reflow();

	clearInterval(autosave_interval_id);

	if(vm.autosave){
		if(!is_mobile()){
		  autosave_interval_id = window.setInterval("autosave()", 10000);
		}
	}

}

function render_items(data){

    jQuery.each(data, function( index, value ) {

      render_item(value);

    });

}

function render_item(data){

    vm.invoices.push(new Invoice(data));

}

function render_reload_item(data){

    var index_of_row = jQuery( "#invoices-body tr.item-row" ).index( jQuery("#row"+data.id) ) ;

    //https://vuejs.org/v2/guide/list.html#Caveats
    if(index_of_row >= 0) {
      //Invoice exists
      //Vue.set(vm.invoices, index_of_row, data);
    }
    else vm.invoices.unshift(data); //invoice is new

}

function render_buttonbar(data){

    vm.current_invoice = data;
    vm.current_action = 'preview';

}

function render_editbuttonbar(id){

    //vm.current_invoice = {id:id};
    vm.current_action = 'edit';

}

function update_totals(){
    var url = 'index.php?option=com_invoices&controller=invoices&task=get_totals&ajax=1&type=' + type  ; ;

    jQuery.ajax({
        url: url,
        cache: false,
        dataType: 'json',
        success: function(response, textStatus, jqXHR){

            update_summary(response.content);

        }
    });
}

function update_summary(summary) {

    vm.summary = summary;

		if (typeof contentstats_update_modules == 'function') contentstats_update_modules(vm.cal_start, vm.cal_end);

}

function load_more_items() {

    var url = "index.php?option=com_invoices&controller=invoices&task=load_items&limitstart=" + start
        + "&status_id=" + vm.status_id
				+ "&filter_currency_id=" + vm.filter_currency_id
        + "&cal_start=" + vm.cal_start
        + "&cal_end=" + vm.cal_end
        + "&filter_order=" + vm.filter_order
        + "&filter_order_Dir=" + vm.filter_order_Dir
        + "&type=" + vm.type
        + "&keywords=" + vm.keywords  ;

    jQuery.ajax({
        url: url,
        cache: false,
        dataType: 'json',
        success: function(result)
        {
            if(result.items.length)
            {
                render_items(result.items);

            }else
            {
                vm.more_items = false;
            }

            update_summary(result.summary);
        },
        complete: function()
        {

            start += pagination_step;
						vm.isLoading = false;
						clearingFilters = false;

            if (pendingKeyword != null) doKeywordSearch();

            //set the thead to sticky
            table_reflow();

            if (typeof contentstats_update_modules == 'function') contentstats_update_modules(vm.cal_start, vm.cal_end);
        }
    });

}

function reset_list_fields() {
    vm.invoices = [];
    start = 0;
    vm.more_items = true;
    vm.isLoading = true;
}

function doKeywordSearch() {
    //vm.keywords = jQuery('#keywords').val();
    if (vm.keywords == pendingKeyword) pendingKeyword = null;
    reset_list_fields();
    load_more_items();
}

var formExpanded = false;

function expand_new_item_form() {
    if (formExpanded) {
        jQuery('#item_form_uncolapsed').addClass('hidden-xs');
        jQuery('#uncolapse_new_form_icon').removeClass('glyphicon-minus').addClass('glyphicon-plus');
        formExpanded = false;
    } else {
        jQuery('#item_form_uncolapsed').removeClass('hidden-xs');
        jQuery('#uncolapse_new_form_icon').removeClass('glyphicon-plus').addClass('glyphicon-minus');
        formExpanded = true;
    }
}

window.closeEditModal = function(){
    jQuery('#editModal').modal('hide');
};

var showingFiltersOnMobile = false;
function showFilters() {
    if (jQuery(window).width() < 768) {
        if (showingFiltersOnMobile){
            jQuery('#filter-contents').addClass('hidden-xs');
            jQuery('#filter-icon-down').removeClass('glyphicon-menu-up').addClass('glyphicon-menu-down');
            jQuery('#filter-page-header').addClass('page-header-small');
            showingFiltersOnMobile = false;
        } else {
            jQuery('#filter-contents').removeClass('hidden-xs');
            jQuery('#filter-icon-down').removeClass('glyphicon-menu-down').addClass('glyphicon-menu-up');
            jQuery('#filter-page-header').removeClass('page-header-small');
            showingFiltersOnMobile = true;
        }
    }
}

function refresh_list(){
    reset_list_fields();
    load_more_items();
}

function edit_invoice(invoice){
    invoice_id = invoice.id;

		vm.current_action = 'edit';

		if(invoice_id != 0){ // existing
			// var index = vm.invoices.map(function(x) {return x.id; }).indexOf(id);
      //
			// vm.current_invoice = vm.invoices[index];
      vm.current_invoice = invoice;
			prepareEditForm();
		}
		else{
			switch(type){
	        case 1: //invoice
	            loadModalEdit('index.php?option=com_invoices&controller=invoice&tmpl=component&task=edit&cid[]='+invoice_id+'&modal=1&tab='+current_tab, invoice_id);
	        break;
	        case 2: //quote
	            loadModalEdit('index.php?option=com_invoices&controller=quote&tmpl=component&task=edit&cid[]='+invoice_id+'&modal=1&tab='+current_tab, invoice_id);
	        break;
	    }
		}

		if(is_mobile() || !split_view){
			jQuery('#detailsModal').modal('show');
		}
}

function new_invoice(contact_id){
    current_tab = "recipient" ;

		vm.current_action = 'edit';

    switch(type){
        case 1: //invoice
            loadModalEdit('index.php?option=com_invoices&controller=invoice&tmpl=component&task=edit&cid[]=0&from='+contact_id+'&modal=1&tab='+current_tab, 0);
        break;
        case 2: //quote
            loadModalEdit('index.php?option=com_invoices&controller=quote&tmpl=component&task=edit&cid[]=0&from='+contact_id+'&modal=1&tab='+current_tab, 0);
        break;
    }
}

function autosave(){
	if(vm.current_action == 'edit' && vm.current_invoice.id > 0) save_invoice();
}

function save_invoice(){

    var options = {
				dataType: 'json',
        beforeSubmit:  showRequest_modal,  // pre-submit callback
        success:       showResponse_modal  // post-submit callback
    };

    // bind form using 'ajaxForm'
    jQuery('#adminForm_modal').ajaxForm(options);

    jQuery('#adminForm_modal').submit();
}

var preview_after_save = 0;

function save_and_preview(){
    preview_after_save = 1;
    save_invoice();
}

function delete_invoice(invoice_id, refresh){
    var url = 'index.php?option=com_invoices&controller=invoice&task=remove&cid[]='+invoice_id+'&ajax=1' + '&type=' + type ;

    jQuery('.maindeletebutton').button('loading');

    jQuery.ajax({
        url: url,
        cache: false,
        dataType: 'json',
        success: function(response, textStatus, jqXHR){

          notify_messages(response.notifications) ;

          if(refresh) refresh_list();
          else remove_row(invoice_id);
          reset_preview();
          jQuery('.maindeletebutton').button('reset');
        }
    });
}

function duplicate_invoice(invoice_id){
    var url = 'index.php?option=com_invoices&controller=invoice&task=duplicate&cid[]='+invoice_id+'&ajax=1' + '&type=' + type ;

    jQuery.ajax({
        url: url,
        cache: false,
        dataType: 'json',
        success: function(response, textStatus, jqXHR){

            notify_messages(response.notifications) ;
            refresh_list();

        }
    });
}

function publish_invoice(invoice_id, refresh){
    var url = 'index.php?option=com_invoices&controller=invoice&task=publish&cid[]='+invoice_id+'&ajax=1' + '&type=' + type ;

    jQuery.ajax({
        url: url,
        cache: false,
        dataType: 'json',
        success: function(response, textStatus, jqXHR){

					var processedData = new Invoice(response.content);

          notify_messages(response.notifications) ;
          if(refresh) refresh_list();
          else render_reload_item(processedData);

					vm.current_invoice = processedData;

        }
    });
}

function unpublish_invoice(invoice_id, refresh){
    var url = 'index.php?option=com_invoices&controller=invoice&task=unpublish&cid[]='+invoice_id+'&ajax=1' + '&type=' + type ;

    jQuery.ajax({
        url: url,
        cache: false,
        dataType: 'json',
        success: function(response, textStatus, jqXHR){

					var processedData = new Invoice(response.content);

					notify_messages(response.notifications) ;
					if(refresh) refresh_list();
					else render_reload_item(processedData);

					vm.current_invoice = processedData;

        }
    });
}

function convert_to_invoice(invoice_id){
    var url = 'index.php?option=com_invoices&controller=invoice&task=convert_to_invoice&cid[]='+invoice_id+'&ajax=1' ;

    jQuery.ajax({
        url: url,
        cache: false,
        dataType: 'json',
        success: function(response, textStatus, jqXHR){

            notify_messages(response.notifications) ;

        }
    });
}

function print_invoice(id){
    invoice_id = id;

		PrintElem('invoice-paper');
		//window.print();
}

function PrintElem(elem)
{
    var mywindow = window.open('', 'PRINT');

    mywindow.document.write('<html><head><title>' + document.title  + '</title>');
		mywindow.document.write('<meta name="viewport" content="width=device-width, initial-scale=1.0">');
		mywindow.document.write('<link rel="stylesheet" href="components/com_invoices/assets/css/template-isis.css" type="text/css" />');
    mywindow.document.write('<link rel="stylesheet" href="components/com_invoices/assets/libs/bootstrap/css/bootstrap-buttons.css" type="text/css" />');
    mywindow.document.write('<link rel="stylesheet" href="components/com_invoices/assets/libs/bootstrap/css/bootstrap-glyphicons.css" type="text/css" />');
    mywindow.document.write('<link rel="stylesheet" href="components/com_invoices/assets/libs/bootstrap/css/bootstrap-forms.css" type="text/css" />');
    mywindow.document.write('<link rel="stylesheet" href="components/com_invoices/assets/libs/bootstrap/css/bootstrap-modal.css" type="text/css" />');
    mywindow.document.write('<link rel="stylesheet" href="components/com_invoices/assets/libs/bootstrap/css/bootstrap-labels.css" type="text/css" />');
    mywindow.document.write('<link rel="stylesheet" href="components/com_invoices/assets/libs/bootstrap/css/bootstrap-panels.css" type="text/css" />');
    mywindow.document.write('</head><body>');
    if(is_mobile() || !vm.split_view) mywindow.document.write(jQuery('.invoice-paper-modal').html());
    else mywindow.document.write(jQuery('.invoice-paper-inline').html());
		mywindow.document.write('<script>window.onload = function() { window.print(); window.close(); }</script>');
    mywindow.document.write('</body></html>');

    mywindow.document.close(); // necessary for IE >= 10
    mywindow.focus(); // necessary for IE >= 10*/

		//mywindow.onload = function() { window.print(); window.close(); }

    // mywindow.print();
    // mywindow.close();

    return true;
}

function delete_item(item_id, values){

		if(values.length){

	    var url = 'index.php?option=com_invoices&controller=item&task=remove&cid[]='+item_id+'&id='+vm.current_invoice.id+'&ajax=1' ;

	    jQuery.ajax({
	        url: url,
	        cache: false,
	        dataType: 'json',
	        success: function(response, textStatus, jqXHR){

	            notify_messages(response.notifications) ;
							removeSelectedItems();

	        }
	    });

		}else{

			removeSelectedItems();

		}
}

function removeSelectedItems(){
	var selected_items = vm.current_invoice.items.filter(function(item, index){return item.selected});

	jQuery.each(selected_items, function( index, value ) {
			var index = vm.current_invoice.items.map(function(x) {return x.selected; }).indexOf(true);
			vm.current_invoice.items.splice(index, 1);
	});
}

function delete_payment(payment_id, values){

  if(values.length){

    var url = 'index.php?option=com_invoices&controller=payment&task=remove&pid[]='+payment_id+'&id='+invoice_id+'&ajax=1' ;

    jQuery.ajax({
        url: url,
        cache: false,
        dataType: 'json',
        success: function(response, textStatus, jqXHR){

					notify_messages(response.notifications) ;
					removeSelectedPayments();

        }
    });
	}else{

		removeSelectedPayments();

	}
}

function removeSelectedPayments(){
	var selected_items = vm.current_invoice.payments.filter(function(item, index){return item.selected});

	jQuery.each(selected_items, function( index, value ) {
			var index = vm.current_invoice.payments.map(function(x) {return x.selected; }).indexOf(true);
			vm.current_invoice.payments.splice(index, 1);
	});
}

function get_history(invoice_id){
	if(cs_installed && invoice_id){
    var url = 'index.php?option=com_invoices&controller=invoice&task=get_history&id='+invoice_id+'&ajax=1' + '&type=' + type ;

    jQuery.ajax({
        url: url,
        cache: false,
        dataType: 'json',
        success: function(response, textStatus, jqXHR){

            notify_messages(response.notifications) ;

						vm.current_invoice.history = response.content;

        }
    });
	}
}

function reset_preview(){

    vm.current_action = "";
    vm.current_invoice = new Invoice({id:0,
		                      items:[],
		                      payments:[],
		                      taxes:vm.alltaxes,
													history:[],
												});

    hide_edit_modal();

}

function remove_row(invoice_id){

    jQuery("#row"+invoice_id +' [data-toggle="tooltip"]').tooltip('destroy');

    var index_of_row = jQuery( "#invoices-body tr.item-row" ).index( jQuery("#row"+invoice_id) ) ;

    vm.invoices.splice(index_of_row, 1);

}

function remove_item_row(item_id){

    jQuery("#itemrow"+item_id).remove();

}

function remove_payment_row(payment_id){

    jQuery("#paymentrow"+payment_id).remove();

}

/**
 * Initializes the typeahead
 */
function initializeRecipientNameTypeahead() {

	var namesBloodhound = new Bloodhound({
	    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
	    queryTokenizer: Bloodhound.tokenizers.whitespace,
	    limit: 10,
	    remote: {
	        url: 'index.php?option=com_invoices&controller=invoice&task=search_contact&searchword=%QUERY',
	        wildcard: '%QUERY'
	    }
	});

    namesBloodhound.initialize(true);
		namesBloodhound.clear(true);

		jQuery('#to_name').typeahead('destroy');

		//https://vuejs.org/v2/api/#Vue-compile

    jQuery('#to_name').typeahead(null, {
        name: 'contacts',
        displayKey: 'name',
        source: namesBloodhound.ttAdapter(),
        templates: {
          suggestion: function(result){
    				var res = Vue.compile(jQuery("#contact-suggestion-template").html());
    				var vuesuggestion = new Vue({
    				  data: result,
    				  render: res.render,
    				  staticRenderFns: res.staticRenderFns,
    					methods:{
    					}
    				}).$mount();
    				return vuesuggestion.$el;
    			}
        }
    }).on('typeahead:select', function(ev, suggestion) {
        load_contact(suggestion);
    });
}

var usersBloodhound = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    limit: 10,

    remote: {
        url: 'index.php?option=com_invoices&controller=invoice&task=search_user&searchword=%QUERY',
        wildcard: '%QUERY'
    }
});

/**
 * Initializes the typeahead
 */
function initializeUsernameTypeahead() {
    usersBloodhound.initialize();

    jQuery('#search_user').typeahead(null, {
        name: 'users',
        displayKey: 'name',
        source: usersBloodhound.ttAdapter(),
        templates: {
          suggestion: function(result){
    				var res = Vue.compile(jQuery("#user-suggestion-template").html());
    				var vuesuggestion = new Vue({
    				  data: result,
    				  render: res.render,
    				  staticRenderFns: res.staticRenderFns,
    					methods:{
    					}
    				}).$mount();
    				return vuesuggestion.$el;
    			}
        }
    }).on('typeahead:select', function(ev, suggestion) {

        load_user(suggestion);
    });
}

var itemsBloodhound = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  limit: 10,

  remote: {
    url: 'index.php?option=com_invoices&controller=invoice&task=search_items&searchword=%QUERY',
    wildcard: '%QUERY'
  }
});

/**
 * Initializes the typeahead
 */
 function initializeItemTypeahead(input_id, index) {
  itemsBloodhound.initialize();

  jQuery('#' + input_id).typeahead(null, {
    name: 'items',
    displayKey: 'name',
    source: itemsBloodhound.ttAdapter(),
    templates: {
      suggestion: function(result){
				var res = Vue.compile(jQuery("#item-suggestion-template").html());
        result.currency_id = vm.current_invoice.currency_id;
				var vuesuggestion = new Vue({
				  data: result,
				  render: res.render,
				  staticRenderFns: res.staticRenderFns,
					methods:{
					}
				}).$mount();
				return vuesuggestion.$el;
			}
    }
  }).on('typeahead:select', function(ev, suggestion) {
		var index = jQuery(this).attr('data-index');
    load_item(suggestion, index);
  });
}

function animateTotals(newSummary, oldSummary){

  //https://vuejs.org/v2/guide/transitioning-state.html#Animating-State-with-Watchers
  // newValue = newSummary.num_invoices;
  // oldValue = oldSummary.num_invoices;
  //
  // var vm = this
  // function animate () {
  //   if (TWEEN.update()) {
  //     requestAnimationFrame(animate)
  //   }
  // }
  // new TWEEN.Tween({ tweeningNumber: oldValue })
  //   .easing(TWEEN.Easing.Quadratic.Out)
  //   .to({ tweeningNumber: newValue }, 500)
  //   .onUpdate(function () {
  //     vm.animatedSummary.num_invoices = this.tweeningNumber.toFixed(0)
  //   })
  //   .start()
  // animate()

  function animate () {
    if (TWEEN.update()) {
      requestAnimationFrame(animate)
    }
  }

  //total Invoices
  if(typeof newSummary.total_invoices[vm.currency_id] !== 'undefined'){
    newValue = newSummary.total_invoices[vm.currency_id].total;
  }
  else newValue = 0;

  if(typeof oldSummary.total_invoices[vm.currency_id] !== 'undefined'){
    oldValue = oldSummary.total_invoices[vm.currency_id].total;
  }
  else oldValue = 0;

  new TWEEN.Tween({ tweeningNumber: oldValue })
    .easing(TWEEN.Easing.Quadratic.Out)
    .to({ tweeningNumber: newValue }, 500)
    .onUpdate(function () {
      vm.animatedSummary.total_invoices = this.tweeningNumber.toFixed(vm.currencies[vm.currency_id].decimals)
    })
    .start()
  //animate()

  //total Income
  if(typeof newSummary.total_income[vm.currency_id] !== 'undefined'){
    newValue = newSummary.total_income[vm.currency_id].total;
  }
  else newValue = 0;

  if(typeof oldSummary.total_income[vm.currency_id] !== 'undefined'){
    oldValue = oldSummary.total_income[vm.currency_id].total;
  }
  else oldValue = 0;

  new TWEEN.Tween({ tweeningNumber: oldValue })
    .easing(TWEEN.Easing.Quadratic.Out)
    .to({ tweeningNumber: newValue }, 500)
    .onUpdate(function () {
      vm.animatedSummary.total_income = this.tweeningNumber.toFixed(vm.currencies[vm.currency_id].decimals)
    })
    .start()

  //pending Income
  if(typeof newSummary.pending_income[vm.currency_id] !== 'undefined'){
    newValue = newSummary.pending_income[vm.currency_id].total;
  }
  else newValue = 0;

  if(typeof oldSummary.pending_income[vm.currency_id] !== 'undefined'){
    oldValue = oldSummary.pending_income[vm.currency_id].total;
  }
  else oldValue = 0;

  new TWEEN.Tween({ tweeningNumber: oldValue })
    .easing(TWEEN.Easing.Quadratic.Out)
    .to({ tweeningNumber: newValue }, 500)
    .onUpdate(function () {
      vm.animatedSummary.pending_income = this.tweeningNumber.toFixed(vm.currencies[vm.currency_id].decimals)
    })
    .start()

  //taxes
	for (var property in newSummary.taxes) {
	    if (newSummary.taxes.hasOwnProperty(property)) {

        if(typeof newSummary.taxes[property][vm.currency_id] !== 'undefined'){
          newValue = newSummary.taxes[property][vm.currency_id];
        }
        else newValue = 0;

        if(typeof oldSummary.taxes[property][vm.currency_id] !== 'undefined'){
          oldValue = oldSummary.taxes[property][vm.currency_id];
        }
        else oldValue = 0;

        new TWEEN.Tween({ tweeningNumber: oldValue })
          .easing(TWEEN.Easing.Quadratic.Out)
          .to({ tweeningNumber: newValue }, 500)
          .onUpdate(function () {
            vm.animatedSummary.taxes[property] = this.tweeningNumber.toFixed(vm.currencies[vm.currency_id].decimals)
          })
          .start()

	    }
	}

  animate()
}
