"use strict";

var new_items = 0;
var new_payments = 0;

var invoiceform_component = Vue.extend({
  template: '#invoiceform-vue-template',
  props: ["invoice"],
  computed: {

    username_id: function() {
      if (parseInt(this.invoice.joomla_user_id)) return this.invoice.username + " [" + this.invoice.joomla_user_id + "]";else return "";
    },
    status_name: function() {
      return Joomla.JText._(this.invoice.getComputedStatus());
    }

  },
  methods: {

    //only for form
    showAlert: function(tax_id) {
      //for (var key in this.invoice.taxes) {
      if (this.invoice.taxes.hasOwnProperty(tax_id)) {
        if (this.invoice.taxes[tax_id].active) {
          //check tax duplicity
          for (var i = 0; i < this.invoice.items.length; i++) {
            if (this.invoice.items[i].tax_id == tax_id) {
              console.log(tax_id);
              return true;
            }
          }
        }
        //}
      }
      return false;
    },

    newItem: function() {

      new_items++;

      this.invoice.items.push({
        id: new_items,
        prefix: '0_',
        tax_id: vm.defaults.tax_id,
        value: "",
        amount: "",
        tax: vm.defaults.tax,
        discount: "",
        selected: false,
        isNew: true
      });

      //dirty trick
      setTimeout(function () {
        initializeItemTypeahead('0_name_' + new_items);
        jQuery('#0_name_' + new_items).focus();
      }, 100);

    },
    newPayment: function() {

      new_payments++;

      this.invoice.payments.push({
        id: new_payments,
        prefix: '0_',
        payment_amount: '',
        payment_status: 0,
        selected: false,
        isNew: true
      });

      var i = this.invoice.payments.length - 1;

      //dirty trick
      setTimeout(function () {
        jQuery('#0_payment_duedate_' + new_payments).datepicker('update', vm.current_invoice.payments[i].payment_duedate).on('changeDate', function(ev) {
  				var index = ev.target.getAttribute("data-index");
  		    jQuery('#0_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("#0_payment_duedate_btn_" + new_payments).click(function(ev) {
  				var index = jQuery(this).attr('data-index');
  		    jQuery('#0_payment_duedate_' + vm.current_invoice.payments[index].id).datepicker('show');
  		  });

  		  jQuery('#0_payment_datetime_' + new_payments).datepicker('update', vm.current_invoice.payments[i].payment_datetime).on('changeDate', function(ev) {
  				var index = ev.target.getAttribute("data-index");
  		    jQuery('#0_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("#0_payment_datetime_btn_" + new_payments).click(function(ev) {
  				var index = jQuery(this).attr('data-index');
  		    jQuery('#0_payment_datetime_' + vm.current_invoice.payments[index].id).datepicker('show');
  		  });

        jQuery('#0_payment_value_' + new_payments).focus();
      }, 100);

    },
    togglePublish: function(value) {
      this.invoice.publish = value;
    },
    toggleRecurrent: function(value) {
      this.invoice.is_recurrent = value;
    },
    toggleRecemail: function(value) {
      this.invoice.rec_email = value;
    },
    togglePaymentStatus: function(i, value) {
      this.invoice.payments[i].payment_status = value;
    },
    toggleContactOptions: function(value) {
      this.invoice.vincular_cliente_checkbox = value;
    },
    set_item_tax: function(item_id, tax_id, index) {
      this.invoice.items[index].tax_id = tax_id;
    },
    deleteItems: function() {

      var values = this.invoice.items.filter(function (item, index) {
        return item.selected && !item.isNew;
      }).map(function (item) {
        return item.id;
      });
      var string = values.join("&cid[]=");
      delete_item(string, values);
    },
    numSelectedItems: function() {

      return this.invoice.items.filter(function (item, index) {
        return item.selected;
      }).length;
      
    },
    deletePayments: function() {

      var values = this.invoice.payments.filter(function (item, index) {
        return item.selected && !item.isNew;
      }).map(function (item) {
        return item.id;
      });
      var string = values.join("&cid[]=");
      delete_payment(string, values);
    },
    numSelectedPayments: function() {

      return this.invoice.payments.filter(function (item, index) {
        return item.selected;
      }).length;

    },

    validate_eu_vat: function() {

    	var vat_number = this.invoice.to_vatid;

    	jQuery('#vatid_container').removeClass('has-success has-error');
    	jQuery('#spinner_euvat').removeClass('hide');

    	jQuery.ajax({
    			url: "http://www.apilayer.net/api/validate?access_key=" + access_key + "&vat_number=" + vat_number,
    			dataType: 'json',
    			success: function(response, textStatus, jqXHR){
            if (response.valid) {
                jQuery('#vatid_container .form-control-feedback').removeClass('glyphicon-remove').addClass('glyphicon-ok');
                jQuery('#vatid_container').addClass('has-success');
              }
              else{
                jQuery('#vatid_container .form-control-feedback').removeClass('glyphicon-ok').addClass('glyphicon-remove');
                jQuery('#vatid_container').addClass('has-error');
            }

    			},
    			error: function(response, textStatus, jqXHR){
    					jQuery('#vatid_container .form-control-feedback').removeClass('glyphicon-ok').addClass('glyphicon-remove');
    					jQuery('#vatid_container').addClass('has-error');

    			},
    			complete: function() {
    				jQuery('#spinner_euvat').addClass('hide');
    			}
    	});
    }

  },
  mounted: function() {
    jQuery('#invoice-edit-container [data-toggle="tooltip"]').tooltip();
  }
});
