﻿//stores
var boldata=[
    [1,'Sí'],
    [0,'No']
  ];
var storebol=new Ext.data.SimpleStore({
    fields: ['value','text'],
    data: boldata
});
var genero = [
    ['F', 'F'],
    ['M', 'M']
  ];
var storegenero = new Ext.data.SimpleStore({
    fields: ['value', 'text'],
    data: genero
});
var mesdata = [
	['01', 'Enero'],
	['02', 'Febrero'],
	['03', 'Marzo'],
	['04', 'Abril'],
	['05', 'Mayo'],
	['06', 'Junio'],
	['07', 'Julio'],
	['08', 'Agosto'],
	['09', 'Septiembre'],
    ['10', 'Octubre'],
	['11', 'Noviembre'],
    ['12', 'Diciembre']
    ];
var storemes = new Ext.data.SimpleStore({
    fields: ['value', 'text'],
    data: mesdata
});

var clasifidata = [
	['Cableado Telefónico'],
	['Canaletas'],
	['Equipo Activo de Red'],
	['Gabinetes'],
	['Red de Datos'],
	['Racks, Gabinentes y Accesorios']
    ];
var storeclasificacion = new Ext.data.SimpleStore({
    fields: ['text'],
    data: clasifidata
});
var activorender=function (data) {
    var tip;
    switch(data) {
        case 1: 
            tip="Sí";
            break;
        case 0: 
            tip="No"
            break;

    }
    return tip;
}

// short names
var xg=Ext.grid;
var Gtexto=function (name,id,ancho,maxLen,titulo) {
    var texto=new Ext.form.TextField({
        fieldLabel: titulo,
        labelStyle: "text-align:right",
        name: name,
        id: id,
        width: ancho,
        maxLength: maxLen,
        enableKeyEvents: true
    });
    return texto;
}
var Gtextarea=function (name,id,ancho,alto,maxLen,titulo) {
    var texto=new Ext.form.TextArea({
        fieldLabel: titulo,
        labelStyle: "text-align:right",
        name: name,
        id: id,
        width: ancho,
        height: alto,
        maxLength: maxLen,
        enableKeyEvents: true
    });
    return texto;
}

var GHTMLe=function (name,id,ancho,alto,titulo) {
    var texto=new Ext.form.HtmlEditor({
        fieldLabel: titulo,
        labelStyle: "text-align:right",
        name: name,
        id: id,
        width: ancho,
        height: alto
    });
    return texto;
}

function gCurrency(name,id,ancho,maxLen,titulo) {
    var texto=new Ext.ux.dollarField({
        fieldLabel: titulo,
        labelStyle: "text-align:right",
        name: name,
        id: id,
        width: ancho,
        maxLength: maxLen,
        enableKeyEvents: true,
        baseChars: '0123456789,.$'
    });
    return texto;
}

function Gpass(name,id) {
    var pass=new Ext.form.TextField({
        fieldLabel: "Contraseña",
        labelStyle: "text-align:right",
        name: name,
        id: id,
        inputType: 'password',
        width: 80,
        disabled: false,
        maxLength: 20,
        minLength: 0,
        allowBlank: true
    });
    return pass;
}
function Gnumero(name,id,ancho,maxLen,titulo) {
    var id_num=new Ext.form.NumberField({
        fieldLabel: titulo,
        labelStyle: "text-align:right",
        name: name,
        id: id,
        width: ancho,
        disabled: false,
        maxLength: maxLen,
        minLength: 0,
        allowBlank: true,
        decimalPrecision: 0
    });
    return id_num;
}

function Gcombo(name,id,titulo,store,display,value,w, wL) {
    var combo=new Ext.form.ComboBox({
        fieldLabel: titulo,
        labelStyle: "text-align:right;",
        name: name,
        id: id,
        disabled: false,
        width: w,
        listWidth:wL,
        minChars: 1,
        store: store,
        mode: 'local',
        forceSelection: true,
        queryParam: display,
        displayField: display,
        valueField: value,
        triggerAction: 'all',
        emptyText: 'Seleccione...',
        resizable: true,
        editable: true,
        allowBlank: true
    });
    return combo;
}



var GLabel=function (texto,clase,ancho,id) {
    var label=new Ext.form.Label({
        html: texto,
        cls: clase,
        width: ancho,
        id: id
    });
    return label;
}

var Gbox=function (texto, clase, id) {
    var box=new Ext.BoxComponent({
        autoEl: {
            tag:"div",
            id:id
        },
        autoWidth:true,
        autoHeight:true
    });
    return box;
}

var GHidden=function (name,id,value) {
    var hiddenfield=new Ext.form.Hidden({
        name: name,
        id: id,
        value: value
    });
    return hiddenfield;
}
var Gdate=function (name,id,titulo) {
    var datefield=new Ext.form.DateField({
        fieldLabel: titulo,
        labelStyle: "text-align:right",
        name: name,
        id: id,
        width: 100,
        tabindex: 101,
        maxLength: 50,
        format: 'd/m/Y',
        enableKeyEvents: true
    });
    return datefield;
}


//chekbox
var Gcheckbox=function (name,box) {
    var cbox=new Ext.form.Checkbox({
        labelSeparator: '',
        //autoWidth: 20,
        boxLabel: box,
        name: name
    });

    return cbox;
}

var Gradio=function (name,box) {
    var cbox=new Ext.form.Radio({
        labelSeparator: '',
        autoWidth: 20,
        boxLabel: box,
        name: name,
        checked: false
    });

    return cbox;
}


//botones
var GBtn=function (text,icon,iconAlign,scale) {
    var boton=new Ext.Toolbar.Button({
        text: text,
        cls: 'x-btn-text-icon',
        icon: raizsitio+'content/icons/'+icon,
        iconAlign: iconAlign,
        scale: scale
    });

    return boton;
}

function getBbar(datastore,pageSize) {
    var Bbar=new Ext.PagingToolbar({
        id: 'bbar',
        pageSize: pageSize,
        store: datastore,
        displayInfo: true,
        displayMsg: 'Mostrando registros {0} - {1} de '+addCommas('{2}'),
        emptyMsg: "No hay registros por mostrar"
    });

    return Bbar;

}
// mensajes de excepción
function requestexcept() {
    hideMask();
    Ext.MessageBox.show({
        title: 'Mensaje del sistema',
        msg: 'Ocurrió un error al procesar su petición por favor contacte al Administrador del Sistema',
        buttons: Ext.MessageBox.OK,
        icon: Ext.MessageBox.ERROR
    });
}

//generador dinamico de Reader

function getStore(xurl,remoteSort,sortfield,sorttype,readerAction) {
    var dStore=new Ext.data.Store();
    var dReader=new Ext.data.JsonReader();
    var dProxy=new Ext.data.HttpProxy({
        url: raizsitio+'parsers/'+xurl
    });

    Ext.Ajax.request({
        url: raizsitio+'parsers/'+xurl,
        params: { a: readerAction },
        async: false,
        success: function (conn,response,options) {
            var obj=conn.responseText;
            dReader=new Ext.data.JsonReader(Ext.util.JSON.decode(obj));
            dStore=new Ext.data.Store({
                proxy: dProxy,
                reader: dReader,
                remoteSort: remoteSort,
                sortInfo: { field: sortfield,direction: sorttype }
            });
        }
    });
    return dStore;
}

function StoreException(xconn,response,options) {
    Ext.MessageBox.show({
        title: 'ERROR',
        msg: dataerror+response.responseText,
        buttons: Ext.MessageBox.OK,
        icon: Ext.MessageBox.ERROR,
        modal: true
    });
}



function formError(msg) {
    Ext.MessageBox.show({
	    title: 'Mensaje del sistema',
	    msg: msg,
	    buttons: Ext.MessageBox.OK,
	    icon: Ext.MessageBox.ERROR,
	    modal: true
	});
}

function Msgbox(title,msg) {
    Ext.MessageBox.show({
	    title: title,
	    msg: msg,
	    buttons: Ext.MessageBox.OK,
	    icon: Ext.MessageBox.INFO,
	    modal: true
	});
}

function getGroupStore(xurl, remoteSort, sortfield, sorttype, readerAction) {
    var dStore = new Ext.data.Store();
    var dReader = new Ext.data.JsonReader();
    var dProxy = new Ext.data.HttpProxy({
        url: raizsitio + 'parsers/' + xurl
    });

    Ext.Ajax.request({
        url: raizsitio + 'parsers/' + xurl,
        params: { a: readerAction },
        async: false,
        success: function (conn, response, options) {
            var obj = conn.responseText;
            dReader = new Ext.data.JsonReader(Ext.util.JSON.decode(obj));
            dGroupStore = new Ext.data.GroupingStore({
                proxy: dProxy,
                reader: dReader,
                remoteSort: remoteSort,
                sortInfo: { field: sortfield, direction: sorttype },
                groupField: sortfield

            });
        }
    });
    return dGroupStore;

}

function fieldUpper(field) {
    field.setValue(Ext.util.Format.uppercase(field.getValue()));
}

function fieldTel(field,marcacion) {
    if(field.getValue().length>14)
        field.setValue(field.getValue().substr(0,14));
    else
        field.setValue(f_format_phone(field.getValue(),marcacion));
}

Ext.apply(Ext.form.VTypes, {
    PhoneN:  function(v) {
        return /^\d{1,3}\-\d{1,3}\-\d{1,2}\-\d{1,2}$/.test(v);
    },
    PhoneNText: 'Debe ser un número de 10 digitos',
    PhoneNMask: /[\d\.]/i
});

// return only the digits in a string
  function f_digits_only(thisString)
  {
       return thisString.replace(/[^\d]/ig,'');
  }

  // format phone number for display
  function f_format_phone(thisString, marcacion)
  {
    var phone_formatted = f_digits_only(thisString);
    if(marcacion==3) {
        
        if(phone_formatted.length > 3)
          phone_formatted = '('+phone_formatted.substr(0,3)+') '+phone_formatted.substr(3);
        if(phone_formatted.length > 9)
          phone_formatted = phone_formatted.substr(0,9)+'-'+phone_formatted.substr(9);
    }
    if(marcacion==2) 
    {
        if(phone_formatted.length > 2)
          phone_formatted = '('+phone_formatted.substr(0,2)+') '+phone_formatted.substr(2);
        if(phone_formatted.length > 8)
          phone_formatted = phone_formatted.substr(0,9)+'-'+phone_formatted.substr(9);
    }
    return phone_formatted;
  }
  
  if ((typeof Range !== "undefined") && !Range.prototype.createContextualFragment)
{
	Range.prototype.createContextualFragment = function(html)
	{
		var frag = document.createDocumentFragment(), 
		div = document.createElement("div");
		frag.appendChild(div);
		div.outerHTML = html;
		return frag;
	};
}

function DateDiffYear(f1, f2) {
    var diff = new Date();
    diff.setTime(f1 - f2);
    var timediff = diff.getTime();
    var year = Math.floor(timediff / (1000 * 60 * 60 * 24));
    year = Math.floor(year / 365.1);
    
    return year;
}

function isDate(dateStr) {
    try {
        var datePat = /^(\d{1,4})(\/|-)(\d{1,2})(\/|-)(\d{2})$/;
        var matchArray = dateStr.match(datePat); // is the format ok?

        if (matchArray == null) {
            //alert("Please enter date as either mm/dd/yyyy or mm-dd-yyyy.");
            return false;
        }
        return true; // date is valid
    }
    catch(e) {
        return false;
    }
}



