function format_number(thenumber, currency_id){

    if(typeof currency_id === "undefined") currency_id = vm.format.currency_id;
    if(currency_id == 0) currency_id = vm.format.currency_id;

    if(typeof vm.currencies[currency_id] === "undefined") currency_id = vm.format.currency_id;

    if(typeof thenumber === "undefined" || thenumber == "" || thenumber === NaN) {
        thenumber = 0;
    }

    var show_before = vm.currencies[currency_id].symbol_before;
    var show_after = vm.currencies[currency_id].symbol_after;
    var decimals = vm.currencies[currency_id].decimals;
    var decpoint = vm.currencies[currency_id].decpoint;
    var thousands = vm.currencies[currency_id].thousands;
    var negative_position = vm.currencies[currency_id].negative_position;

    return format_number_free(thenumber, show_before, show_after, decimals, decpoint, thousands, negative_position);

}

function format_number_free(thenumber, show_before, show_after, decimals, decpoint, thousands, negative_position){

  thenumber = parseFloat(thenumber);

  var negative = thenumber < 0;
  thenumber = (Math.abs(thenumber)).toFixed(decimals) ;

  var integerPart;
  var decimalPart = "";
  var negativeSign = "";

  if (decimals == 0) {
      integerPart = stringNumberWithThousandSeparator(thenumber.toString(), thousands)
      decpoint = "";
  } else {
      var numberParts = thenumber.toString().split(".");

      integerPart = numberParts[0];
      decimalPart = numberParts[1];

      if (thousands != "") {
          integerPart = stringNumberWithThousandSeparator(integerPart, thousands)
      }
  }

  if(negative) negativeSign = "-";

  if(negative_position == '0') return show_before + negativeSign + integerPart + decpoint + decimalPart + show_after;
  else return negativeSign + show_before + integerPart + decpoint + decimalPart + show_after;

}

function stringNumberWithThousandSeparator(x, separator) {
    return x.replace(/\B(?=(\d{3})+(?!\d))/g, separator);
}

function roundnumber(thenumber){
	return (thenumber).toFixed(vm.format.decimals)	 ;
}

function is_mobile() {
    if (jQuery(window).width() < 1200 || jQuery(window).height() < 800) {
        return true;
    }
    else return false;
}

function datepicker_date_in() {
    jQuery('#cal_start').datepicker('show').on('changeDate', function(ev) {
        if (!vm.isLoading) {
            //vm.cal_start = jQuery('#cal_start').val();
            vm.cal_start = moment(ev.date).format('YYYY-MM-DD');
            jQuery(this).datepicker('hide');
            // reset_list_fields();
            // load_more_items();
        }
    });
}

function datepicker_date_out() {
    jQuery('#cal_end').datepicker('show').on('changeDate', function(ev) {
        if (!vm.isLoading) {
            //vm.cal_end = jQuery('#cal_end').val();
            vm.cal_end = moment(ev.date).format('YYYY-MM-DD');
            jQuery(this).datepicker('hide');
            // reset_list_fields();
            // load_more_items();
        }
    });
}

function clearFilters(){

    vm.cal_start = "";
    vm.cal_end = "";
    vm.user_id = "";
    vm.status_id = "";
    vm.keywords = "";
    vm.filter_currency_id = 0;
    vm.time = "";
    vm.periodOffset = 0;

    jQuery('#cal_start').datepicker('clearDates');
    jQuery('#cal_end').datepicker('clearDates');

}

function notify_messages(notifications){
    jQuery.each(notifications, function( index, notification ) {
      //console.log(notification);

      var type = notification.type;

      if(type == "message") type = "success";

      var n = noty({
            text: notification.message,
            layout: 'bottomLeft',
            type: type,
            timeout: 3000 ,
            theme: 'material', // or 'relax'
            animation: {
                open: {height: 'toggle'}, // jQuery animate function property object
                close: {height: 'toggle'}, // jQuery animate function property object
                easing: 'swing', // easing
                speed: 200 // opening & closing animation speed
            }
        });

    });

}

function order_by(order, element){

    //we get the current direction of order
    dir = element.attr('data-order-dir');

    //we set the filters...
    vm.filter_order = order;
    vm.filter_order_Dir = dir;
    //reload the list
    reset_list_fields();
    load_more_items();

    //hide all arrows
    jQuery('.order_dir_button').hide();

    if(dir == "ASC") {
        //only this one arrow, set the arrow direaction and show it
        element.find('.order_dir_button').removeClass('glyphicon-sort-by-attributes-alt').addClass('glyphicon-sort-by-attributes');
        dir = "DESC";
    }
    else if(dir == "DESC") {
        //only this one arrow, set the arrow direaction and show it
        element.find('.order_dir_button').removeClass('glyphicon-sort-by-attributes').addClass('glyphicon-sort-by-attributes-alt');
        dir = "ASC";
    }

    //show the arrow
    element.find('.order_dir_button').show();

    //we set the new direction
    element.attr('data-order-dir', dir);

}

function hide_edit_modal(){
    jQuery('#detailsModal').modal('hide');
}

function translate(value){

  var language = vm.current_invoice.language;
  if(vm.current_invoice.language == "") language = "en-GB";
  if(typeof strings[language][value] === "undefined") return value;
  return strings[language][value];

}

function display_tax(tax_id){
	return parseInt(vm.alltaxes[tax_id].show_column);
}

function changestatus_invoice(invoice_id, status, refresh, invoice){

  if(typeof type === "undefined") var type = 1;

  var url = 'index.php?option=com_invoices&controller=invoice&task=change_status&cid[]='+invoice_id+'&status='+status+'&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);

				invoice.update(response.content);

      }
  });
}

function email_invoice(invoice_id, refresh, invoice){

  if(typeof type === "undefined") var type = 1;

  var url = 'index.php?option=com_invoices&controller=invoice&task=send_email&cid[]='+invoice_id+'&ajax=1' + '&type=' + type ;

  if(!invoice_id.includes("cid")) jQuery('#mainsendbutton' + invoice_id).button('loading');

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

        notify_messages(response.notifications) ;
        if(refresh) refresh_list();

        invoice.update(response.content);

        if(!invoice_id.includes("cid")) jQuery('#mainsendbutton' + invoice_id).button('reset');

      }
  });
}

function preview_invoice(invoice_id, invoice){

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

		//vm.current_invoice = vm.invoices[index];
		vm.current_invoice = invoice;
    vm.current_action = 'preview';

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

function dateset(value) {

  if(value == "0000-00-00 00:00:00" || value == "0000-00-00" || value == "") return false;

  return true;

}

/* VUE FILTERS*/

Vue.filter('currency', function (value, currency_id) {
  if(typeof currency_id === "undefined") currency_id = vm.format.currency_id;
  if(currency_id == 0) currency_id = vm.format.currency_id;
  return format_number(value, currency_id);
});

Vue.filter('symbol_before', function (currency_id) {
  if(typeof currency_id === "undefined") currency_id = vm.format.currency_id;
  if(currency_id == 0) currency_id = vm.format.currency_id;
  return vm.currencies[currency_id].symbol_before;
});

Vue.filter('symbol_after', function (currency_id) {
  if(typeof currency_id === "undefined") currency_id = vm.format.currency_id;
  if(currency_id == 0) currency_id = vm.format.currency_id;
  return vm.currencies[currency_id].symbol_after;
});

Vue.filter('roundnumber', function (value) {
  return roundnumber(value);
});

Vue.filter('date', function (value, format, notset, language) {
  if(typeof format === "undefined") {
      format = 'D MMM YYYY';
  }
  if(typeof notset === "undefined") {
      notset = 'Not set';
  }

  if(value == "0000-00-00 00:00:00" || value == "0000-00-00" || value == "") return notset;

  if(typeof language !== "undefined") {
      //https://momentjs.com/docs/#/i18n/instance-locale/
      var localLocale = moment(value);
      localLocale.locale(language);
      return localLocale.format(format);
  }

  return moment(value).format(format);
});

Vue.filter('dateset', function (value) {

  return dateset(value);

});

Vue.filter('relativedate', function (value) {
  return moment(value).fromNow();
});

Vue.filter('translate', function (value) {
  return translate(value);
});

Vue.filter('taxname', function (value) {
  value = parseInt(value);
  if(value == 0) return "No";
  return vm.alltaxes[value].name;
});

Vue.filter('taxpercentage', function (value, show_before, show_after) {
  if(value == null) return "";
  value = parseFloat(value);
  value = (value).toFixed(vm.format.decimals_tax) ;
  return value + "%";
});

Vue.filter('taxpercentageorflat', function (value, tax, currency_id) {
  if(value == null) return "";
  value = parseFloat(value);
  if(tax.type == "percent"){
    value = (value).toFixed(vm.format.decimals_tax) ;
    return value + "%";
  }
  else {
    if(typeof currency_id === "undefined") currency_id = vm.format.currency_id;
    if(currency_id == 0) currency_id = vm.format.currency_id;
    return format_number(value, currency_id);
  }
});
