var PUBLICO = "Público en general";
var RFC_PUBLICO = "XAXX010101000";
var RFC_EXTRANJERO = "XEXX010101000";
var PAIS = "México";
var DECIMALES = 2;
var CLAVE_ANTICIPOS = '84111506';


var db = new loki('data.db');
var table_config = db.addCollection('config')
var table_taxes = db.addCollection('taxes')
var table_pt = db.addCollection('productstaxes')
var table_totals = db.addCollection('totals', {unique: ['tax']})
var table_series = db.addCollection('series')
var table_usocfdi = db.addCollection('usocfdi')
var table_relaciones = db.addCollection('relaciones')


var months = [
    {id: -1, value: 'Todos'},
    {id: 1, value: 'Enero'},
    {id: 2, value: 'Febrero'},
    {id: 3, value: 'Marzo'},
    {id: 4, value: 'Abril'},
    {id: 5, value: 'Mayo'},
    {id: 6, value: 'Junio'},
    {id: 7, value: 'Julio'},
    {id: 8, value: 'Agosto'},
    {id: 9, value: 'Septiembre'},
    {id: 10, value: 'Octubre'},
    {id: 11, value: 'Noviembre'},
    {id: 12, value: 'Diciembre'},
]


function focus(name){
    webix.UIManager.setFocus(name)
}


function showvar(values){
    webix.message(JSON.stringify(values, null, 2))
}


function show(nombre, value){
    if(value == '0'){
        value = false
    }
    if(value){
        $$(nombre).show()
    }else{
        $$(nombre).hide()
    }
}


function msg_error(msg){
    if(!msg){
        msg = 'Error al consultar'
    }
    webix.message({type: 'error', text: msg})
}


function msg_ok(msg){
    webix.message({type: 'success', text: msg})
}


Number.prototype.round = function(decimals){
    return Number((Math.round(this + "e" + decimals)  + "e-" + decimals))
}


String.prototype.is_number = function(){
    return /^\d+$/.test(this)
}


String.prototype.to_float = function(){
    return get_float(this)
}


function get_float(value){
    return parseFloat(value.replace('$', '').replace(',', '').trim()).round(2)
}


webix.protoUI({
    $cssName: "text",
    name: "currency",
    $init:function(){
        this.attachEvent("onItemClick", function(){
            this.$setValue(this.config.raw, true)
        })
        this.attachEvent("onBlur", function(){
            this.$setValue(this.config.value)
        })
    },
    $render:function(){
        this.$setValue(this.config.value)
    },
    $setValue:function(value, raw){
        this.config.raw = value
        if(!raw){
            value = webix.i18n.priceFormat(value)
        }
        this.getInputNode().value = value
    }
}, webix.ui.text)


webix.ui.datafilter.rowCount = webix.extend({
    refresh:function(master, node, value){
            node.firstChild.innerHTML = master.count();
    }
}, webix.ui.datafilter.summColumn)


function validate_rfc(value){
    rfc = value.trim().toUpperCase();
    if ( rfc == ""){
        msg_error('El RFC no puede estar vacío')
        return false
    }

    var tipo_persona = $$('tipo_persona').getValue()
    var length = 13
    var start = 4
    if(tipo_persona==2){
        length = 12
        start = 2
    }
    if (rfc.length != length){
        msg_error('Longitud incorrecta del RFC')
        return false
    }
    if (tipo_persona < 3 && (rfc == RFC_PUBLICO || rfc == RFC_EXTRANJERO)){
        msg_error('RFC incorrecto')
        return false
    }

    var part = rfc.slice(0, start);
    var re = new RegExp('[a-z&Ñ]{' + start + '}', 'i');
    if (!part.match(re)){
        msg_error('El RFC tiene caractéres inválidos al inicio')
        return false
    }
    part = rfc.slice(-3);
    re = new RegExp('[a-z0-9]{3}', 'i');
    if (!part.match(re)){
        msg_error('El RFC tiene caractéres inválidos al final')
        return false
    }

    part = rfc.slice(-9, -3);
    re = new RegExp('[0-9]{6}', 'i');
    if (!part.match(re)){
        msg_error('Fecha inválida')
        return false
    }
    var month = parseInt(part.slice(-4, -2))
    if (month == 0 || month > 12 ){
        msg_error('Fecha inválida')
        return false
    }
    var day = parseInt(part.slice(-2))
    if (day == 0 || day > 31 ){
        msg_error('Fecha inválida')
        return false
    }

    return true
}


function validate_email(email){
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    return re.test(email)
}


function add_config(args){
    var key = table_config.findOne({key: args.key})
    if(key===null){
        table_config.insert(args)
    }else{
        key.value = args.value
        table_config.update(key)
    }
}


function get_config(value){
    var key = table_config.findOne({key: value})
    if(key===null){
        return ''
    }else{
        return key.value
    }
}


webix.DataDriver.plainjs = webix.extend({
  arr2hash:function(data){
    var hash = {};
    for (var i=0; i<data.length; i++){
      var pid = data[i].parent_id;
      if (!hash[pid]) hash[pid]=[];
      hash[pid].push(data[i]);
    }
    return hash;
  },
  hash2tree:function(hash, level){
    var top = hash[level];
    for (var i=0; i<top.length; i++){
      var branch = top[i].id;
      if (hash[branch])
        top[i].data = this.hash2tree(hash, branch);
    }
    return top;
  },
  getRecords:function(data, id){
    var hash = this.arr2hash(data);
    return this.hash2tree(hash, 0);
  }
}, webix.DataDriver.json)
