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

jQuery( document ).ready(function() {

    jQuery('#keywords').on('input',function(e){
        if (!isloading) {
            doKeywordSearch();
        } else {
            pendingKeyword = jQuery(this).val();
        }
    });

});

function load_user(resultat){

	for (var property in resultat) {
	    if (resultat.hasOwnProperty(property)) {

	        jQuery("#" + property).val( resultat[property] );

	        if(property == "user_id" && resultat[property] != 0) {
	        	jQuery('#label_user').trigger('click');
    				jQuery('#label_user').addClass('active');
    				jQuery("input[name='vincular_cliente_checkbox']").attr("checked", false);
    				jQuery('#vincular_cliente_checkbox').attr("checked", true);
    			}

	    }
	}

}

function load_more_items() {

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

    var url = "index.php?option=com_invoices&controller=contacts&task=load_items&limitstart=" + start
        + "&filter_order=" + filterFields.filter_order
        + "&filter_order_Dir=" + filterFields.filter_order_Dir
        ;

    if (filterFields.keywords != "") {
        url += "&keywords=" + filterFields.keywords;
    } else {
        url += "&keywords= "; //Weeeeeeird but works
    }
    jQuery.ajax({
        url: url,
        cache: false,
        dataType: 'json',
        success: function(result)
        {
            if(result.items.length)
            {
                render_items(result.items);

            }else
            {
                more_items = false;
                jQuery('.no-more-entries').removeClass('hide');
            }

        },
        complete: function()
        {
            // STOP LOADING SPINNER

            jQuery('div#loadmoreajaxloader_invoices').hide();
            start += pagination_step;
            isloading = false;

            if (pendingKeyword != null) doKeywordSearch();

            if(item_to_highlight) {
                highlight_item(item_to_highlight);
                //item_to_highlight = 0 ;
            }

            //set the thead to sticky
            //table_reflow();

            if (typeof contentstats_update_modules == 'function') contentstats_update_modules();
        }
    });

}

function render_items(data){

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

      render_item(value);

    });

}

function render_item(data){

    vm.contacts.push(prepareResponseData(data));

}

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

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

          vm.current_contact = new Contact(response.data);
          prepareEditForm();
          jQuery('#detailsModal').modal('show');

        }
    });
}

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

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

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

function edit_contact(contact){
	contact_id = contact.id;
  vm.current_action = 'preview';

  prepareEditForm();

  jQuery('#detailsModal').modal('show');
  loadModalEdit('index.php?option=com_invoices&controller=contact&tmpl=component&task=edit&cid[]='+contact_id+'&layout=form&modal=1', contact_id);
}

function save_contact(){
  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_contact(invoice_id, refresh){
    var url = 'index.php?option=com_invoices&controller=contact&task=remove&cid[]='+invoice_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(contact_id);

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

            hide_edit_modal();
        }
    });
}

function render_reload_item(data){

    var index_of_row = jQuery( "#contacts-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.contacts, index_of_row, data);
    }
    else vm.contacts.unshift(data);

}

function remove_row(contact_id){

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

}

function preview_contact(id){

		var index = vm.contacts.map(function(x) {return x.id; }).indexOf(id);

		vm.current_contact = vm.contacts[index];
    vm.current_action = 'preview';

    prepareEditForm();

		jQuery('#detailsModal').modal('show');

}

function prepareResponseData(data){

	return new Contact(data);

}

function prepareEditForm(){

	initializeUsernameTypeahead();

}

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()
    }).on('typeahead:select', function(ev, suggestion) {

        load_user_contact(suggestion);
    });
}

function load_user_contact(result){

  vm.current_contact.username = result.username;
  vm.current_contact.user_id = result.joomla_user_id;
	vm.current_contact.vincular_cliente = 1;

}
