//override joomla default submitbutton functions
var Myvar = {};
Myvar.submitbutton = Joomla.submitbutton;
Joomla.submitbutton = function(task) {
    if(task == "add"){
        edit_payment('0');
    }
    else if(task == "remove"){
        var values = jQuery("#adminForm input[name='cid\\[\\]']:checked").map(function(){return jQuery(this).val();}).get();
        var string = values.join("&pid[]=");
        delete_payment(string, true);
    }
    else Myvar.submitbutton(task);
}

jQuery( document ).ready(function() {

    jQuery( "#cal_start" ).click(function() {
        datepicker_date_in();
    });
    jQuery("#cal_start_btn").click(function() {
        datepicker_date_in();
    });

    jQuery( "#cal_end" ).click(function() {
        datepicker_date_out();
    });
    jQuery("#cal_end_btn").click(function() {
        datepicker_date_out();
    });

});

function load_invoice(result){

		vm.current_payment.invoice_id = result.invoice_id;
    vm.current_payment.to_name = result.name;
    vm.current_payment.invoice_num = result.invoice_num;
    vm.current_payment.username = result.username;

}

function load_more_items() {

    jQuery('div#loadmoreajaxloader_invoices').show();

    var url = "index.php?option=com_invoices&controller=payments&task=load_items&limitstart=" + start
        + "&status_id=" + vm.status_id
        + "&cal_start=" + vm.cal_start
        + "&cal_end=" + vm.cal_end
        + "&filter_order=" + vm.filter_order
        + "&filter_order_Dir=" + vm.filter_order_Dir
        + "&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();

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

}

function render_items(data){

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

      render_item(value);

    });

}

function render_item(data){

    vm.payments.push(new Payment(data));

}

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

    jQuery('#payments-body .item-row').removeClass('active');
    jQuery('#row'+id).addClass('active');

    jQuery.ajax({
        url: url,
        cache: false,
        success: function(responseText, textStatus, jqXHR){
            html = responseText;

            jQuery('#editModal').modal('show');
            jQuery('#editModal .modal-body').html(html);

        }
    });
}

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

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

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

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

            update_summary(response.content);

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

        }
    });
}

function update_summary(summary) {

    vm.summary = summary;

}

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

function edit_payment(id){
    payment_id = id;

    vm.current_action = 'edit';

		if(id != 0){ // existing
			var index = vm.payments.map(function(x) {return x.id; }).indexOf(id);

			vm.current_payment = vm.payments[index];
			prepareEditForm();
		}
    else{
      loadModalEdit('index.php?option=com_invoices&controller=payment&tmpl=component&task=edit&cid[]='+payment_id+'&layout=form&modal=1', payment_id);
    }

    jQuery('#editModal').modal('show');
}

function prepareEditForm(){

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

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

	jQuery("#created_datetime_btn" ).click(function() {
		jQuery('#created_datetime' ).datepicker('show');
	});

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

	jQuery("#payment_duedate_btn" ).click(function() {
		jQuery('#payment_duedate' ).datepicker('show');
	});

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

	jQuery("#payment_datetime_btn" ).click(function() {
		jQuery('#payment_datetime' ).datepicker('show');
	});

}

function save_payment(){

  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();

}

function delete_payment(payment_id, refresh){
    var url = 'index.php?option=com_invoices&controller=payment&task=remove&pid[]='+payment_id+'&ajax=1' ;

    jQuery('#deletebutton_modal').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(payment_id);

            jQuery('#deletebutton_modal').button('reset');

            hide_edit_modal();
        }
    });
}

function render_reload_item(data){

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

    //https://vuejs.org/v2/guide/list.html#Caveats
    if(index_of_row >= 0) Vue.set(vm.payments, index_of_row, data);
    else vm.payments.unshift(data);

    update_totals();

}

function remove_row(payment_id){

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

}

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

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

/**
 * Initializes the typeahead
 */
 function initializeInvoiceSuggestionTypeahead() {
  invoicesBloodhound.initialize();

  jQuery('#search_invoice').typeahead(null, {
    name: 'invoices',
    displayKey: 'invoice_num',
    source: invoicesBloodhound.ttAdapter(),
    templates: {
      suggestion: function(result){
        var res = Vue.compile(jQuery("#invoice-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_invoice(suggestion);
  });
}
