using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Security.Permissions;

namespace GMLC01HerramientasCad.Logica
{
    public partial class CtlConsultar : UserControl
    {
        #region "CODIGO DEBIDO A SER UN CONTROL DE USUARIO"
        /// <summary>
        /// Event fired when the control requests closing
        /// </summary>
        /// <remarks>No remarks</remarks>
        public event EventHandler onQueryClose;

        /// <summary>
        /// Event fired when the control changes the active element
        /// </summary>
        /// <remarks>No remarks</remarks>
        public event EventHandler onCurrentElementChange;

        private void Close()
        {
            if (onQueryClose != null) onQueryClose(this, null);
            initialized = false;
        }
        #endregion

        private IConsultar iCommIF;
        private Elemento elemCurrent;
        private Collection<Elemento> iElementos;
        

        /// <summary>
        /// Para controlar cuando se estan validando datos.
        /// </summary>
        private bool inValidating;

        private bool isDisabled;
        public bool isEnabled
        {
            get
            {
                return !isDisabled;
            }
            set
            {
                isDisabled = !value;
                if (isDisabled)
                    this.lbMessage.Text = Properties.Resources.ConsultaDesactivada;
                else
                    this.lbMessage.Text = string.Format(Properties.Resources.ConsultarSinDatos, ModComun.MaxEntidadesAutoconsulta);

            }
        }

        /// <summary>
        /// Indica si el elemento tiene pendiente o no (la pendiente se calcula internamente).
        /// </summary>
        private bool tienePendiente;

        private bool initialized;

        public bool hideExit
        {
            get
            {
                return !this.salirButton.Visible;
            }
            set
            {
                this.salirButton.Visible = !value;
            }
        }

        public CtlConsultar()
        {
            try
            {
                InitializeComponent();
            }
            catch (Exception e)
            {
                Log.RegisterError(e);
                throw new ExcepcionGMLC(e.Message, e);
            }
        }

        private EventHandler eh;
        public void Initialize(IConsultar commIF, Collection<Elemento> elementos)
        {
            try
            {
                //atributosPanel.Visible = (elementos.Count > 0);
                lbMessage.Visible = (elementos.Count == 0);
                if (commIF != null) iCommIF = commIF;
                iElementos = elementos;
                centrarCheckBox.Checked = ModComun.CentrarDefault;
                resaltarCheckBox.Checked = ModComun.ResaltarDefault;
                pegarButton.Enabled = ModComun.iPortaPapeles != null;

                ///////////////
                initialized = true;
                ///////////////

                elementosBSource.DataSource = iElementos;
                bindingNavigator1.BindingSource = elementosBSource;
                if (eh == null)
                {
                    eh = new EventHandler(ElementosBSourceCurrentChanged);
                    elementosBSource.CurrentChanged += eh;
                }
                ElementosBSourceCurrentChanged(null, null);
            }
            catch (Exception e)
            {
                Log.RegisterError(e);
                throw new ExcepcionGMLC(e.Message, e);
            }
        }

        public void Clear()
        {
            if (elementosBSource.DataSource == null) return;

            elementosBSource.CurrentChanged -= eh;
            eh = null;
            guardarButton.Focus();
            elementosBSource.Clear();
            elementosBSource.DataSource = null;
            bindingNavigator1.BindingSource = null;
            //ElementosBSourceCurrentChanged(null, null);
            atributosPanel.Controls.Clear();
            iCommIF = null;
            iElementos = null;
            atributosPanel.Visible = false;
            lbMessage.Visible = true;
        }

        private void CreaControl(Atributo atributo, int num)
        {
            TableLayoutPanel panel = this.atributosPanel;

            // label
            Label label = new Label();
            if (atributo.Unidades != null)
            {
                label.Text = atributo.Nombre + " (" + atributo.Unidades + ") : ";
            }
            else
            {
                label.Text = atributo.Nombre + " : ";
            }
            label.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
            label.TextAlign = ContentAlignment.MiddleRight;
            panel.Controls.Add(label, 0, num);

            //Tooltip
            ToolTip toolTip = new ToolTip();
            toolTip.SetToolTip(label, atributo.Descripcion);

            //Campo de edición
            switch (atributo.TipoEdicion)
            {
                case TiposEdicion.Texto:
                    TextBox textBox = new TextBox();
                    textBox.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
                    textBox.Name = atributo.Codigo + "_Control";
                    textBox.TextAlign = HorizontalAlignment.Left;
                    textBox.Tag = atributo.Codigo.Clone(); //num;
                    textBox.TextChanged += new EventHandler(TextBoxValidate);
                    panel.Controls.Add(textBox, 1, num);
                    break;
                case TiposEdicion.Entero:
                case TiposEdicion.Doble:
                    TextBox numBox = new TextBox();
                    numBox.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
                    numBox.Name = atributo.Codigo + "_Control";
                    numBox.TextAlign = HorizontalAlignment.Right;
                    numBox.Tag = atributo.Codigo.Clone(); //num;
                    numBox.LostFocus += new EventHandler(NumBoxValidate);
                    numBox.ReadOnly = (this.tienePendiente && atributo.Codigo.Equals("PENDIENTE", StringComparison.OrdinalIgnoreCase));
                    panel.Controls.Add(numBox, 1, num);
                    break;
                case TiposEdicion.Combo:
                    ComboBox comboBox = new ComboBox();
                    comboBox.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
                    comboBox.Name = atributo.Codigo + "_Control";
                    comboBox.Tag = atributo.Codigo.Clone(); //num;
                    comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
                    comboBox.SelectedIndexChanged += new EventHandler(ComboBoxSelectedIndexChanged);
                    comboBox.DisplayMember = "Texto";
                    comboBox.ValueMember = "Codigo";
                    comboBox.DataSource = ModComun.XSD.Dominios[atributo.NombreDominio].Valores;
                    panel.Controls.Add(comboBox, 1, num);
                    break;
            }

            //Selector
            CheckBox checkBox = new CheckBox();
            checkBox.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
            checkBox.Name = atributo.Codigo + "_CheckBox";
            checkBox.Enabled = !(this.tienePendiente && atributo.Codigo.Equals("PENDIENTE", StringComparison.OrdinalIgnoreCase));
            panel.Controls.Add(checkBox, 2, num);

            //Abrir documento
            if ((atributo.Action + "").Equals(GMLC01HerramientasCad.Logica.Properties.Resources.abrirFichero, StringComparison.OrdinalIgnoreCase))
            {
                Panel pnl = new Panel();
                pnl.Height = 20;
                pnl.Width = 42;

                Button boton = new Button();
                boton.Text = "";
                boton.Tag = atributo.Codigo.Clone();
                boton.BackgroundImage = GMLC01HerramientasCad.Logica.Properties.Resources.OPEN_FILE;
                boton.BackgroundImageLayout = ImageLayout.Zoom;
                boton.Height = 20;
                boton.Width = 20;
                boton.Click += AbrirDocumento;
                toolTip1.SetToolTip(boton, GMLC01HerramientasCad.Logica.Properties.Resources.abrirFichero_Abrir);
                //panel.Controls.Add(boton, 3, num);
                pnl.Controls.Add(boton);
                boton.Dock = DockStyle.Right;
                Button boton2 = new Button();
                boton2.Text = "";
                boton2.Tag = atributo.Codigo.Clone();
                boton2.BackgroundImage = GMLC01HerramientasCad.Logica.Properties.Resources.SelFile;
                boton2.BackgroundImageLayout = ImageLayout.Zoom;
                boton2.Height = 20;
                boton2.Width = 20;
                boton2.Click += SeleccionarDocumento;
                toolTip1.SetToolTip(boton2, GMLC01HerramientasCad.Logica.Properties.Resources.abrirFichero_Seleccionar);
                pnl.Controls.Add(boton2);
                boton2.Dock = DockStyle.Left;

                panel.Controls.Add(pnl, 3, num);
            }
        }

        void SeleccionarDocumento(object sender, EventArgs e)
        {
            Button cBtn = sender as Button;
            Atributo att = elemCurrent.Atributos[(string)cBtn.Tag];

            if (System.IO.File.Exists(att.Valor))
                openFileDialog1.FileName = att.Valor;
            else
                openFileDialog1.FileName = "";

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                this.atributosPanel.Controls[att.Codigo + "_Control"].Text = openFileDialog1.FileName;
                att.Valor = openFileDialog1.FileName;
            }
        }

        void AbrirDocumento(object sender, EventArgs e)
        {
            Button cBtn = sender as Button;
            //elemCurrent.Atributos[(string)cBtn.Tag].AbrirDocumento();

            Atributo att = elemCurrent.Atributos[(string)cBtn.Tag];
            if (System.IO.File.Exists(att.Valor))
                try
                {
                    System.Diagnostics.Process pr = new System.Diagnostics.Process();
                    pr.StartInfo.FileName = att.Valor;
                    pr.StartInfo.ErrorDialog = true; // important
                    pr.Start();
                }
                catch (System.ComponentModel.Win32Exception ex)
                {
                    MessageBox.Show(ex.Message, "GMLC", MessageBoxButtons.OK, MessageBoxIcon.Stop, MessageBoxDefaultButton.Button1, 0);
                }
            else
                MessageBox.Show(GMLC01HerramientasCad.Logica.Properties.Resources.OpenDocArchivoNoEncontrado, "GMLC", MessageBoxButtons.OK, MessageBoxIcon.Stop, MessageBoxDefaultButton.Button1, 0);
        }

        void ComboBoxSelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox cBox = sender as ComboBox;
            elemCurrent.Atributos[(string)cBox.Tag].Valor = cBox.SelectedValue.ToString();
        }

        void TextBoxValidate(object sender, EventArgs e)
        {
            TextBox tBox = sender as TextBox;
            elemCurrent.Atributos[(string)tBox.Tag].Valor = tBox.Text;
        }

        void NumBoxValidate(object sender, EventArgs e)
        {
            if (inValidating) return;
            inValidating = true;
            TextBox tBox = sender as TextBox;
            if (tBox.Text.Length == 0)
            {
                //Por si hay pendiente
                if (this.tienePendiente &&
                    (
                     ((string)tBox.Tag).Equals("COTA_INICIO", StringComparison.OrdinalIgnoreCase) ||
                     ((string)tBox.Tag).Equals("COTA_FINAL", StringComparison.OrdinalIgnoreCase) ||
                     ((string)tBox.Tag).Equals("LONGITUD", StringComparison.OrdinalIgnoreCase)
                    )
                   )
                {
                    TextBox pendienteBox = this.atributosPanel.Controls["PENDIENTE_Control"] as TextBox;
                    if (pendienteBox != null)
                    {
                        pendienteBox.Text = "";
                        elemCurrent.Atributos["PENDIENTE"].Valor = pendienteBox.Text;
                    }
                }
                elemCurrent.Atributos[(string)tBox.Tag].Valor = "";
                inValidating = false;
                return;
            }
            double dob = double.NegativeInfinity;
            try
            {
                dob = System.Convert.ToDouble(tBox.Text.Replace(',', '.'), System.Globalization.CultureInfo.InvariantCulture);
                if (elemCurrent.Atributos[(string)tBox.Tag].TipoEdicion == TiposEdicion.Entero)
                    dob = Math.Round(dob);
                tBox.Text = dob.ToString(System.Globalization.CultureInfo.InvariantCulture);
                elemCurrent.Atributos[(string)tBox.Tag].Valor = dob.ToString(System.Globalization.CultureInfo.InvariantCulture);
                //Cálculo de la pendiente (si se debe hacer)
                TextBox pendienteBox = null;
                if (this.tienePendiente) pendienteBox = this.atributosPanel.Controls["PENDIENTE_Control"] as TextBox;
                if (pendienteBox != null)
                {
                    if ((((string)tBox.Tag).Equals("COTA_INICIO", StringComparison.OrdinalIgnoreCase) ||
                        ((string)tBox.Tag).Equals("COTA_FINAL", StringComparison.OrdinalIgnoreCase) ||
                        ((string)tBox.Tag).Equals("LONGITUD", StringComparison.OrdinalIgnoreCase)) &&
                       (!string.IsNullOrEmpty(elemCurrent.Atributos["COTA_INICIO"].Valor) &&
                        !string.IsNullOrEmpty(elemCurrent.Atributos["COTA_FINAL"].Valor) &&
                        !string.IsNullOrEmpty(elemCurrent.Atributos["LONGITUD"].Valor)
                       ))
                    {
                        if (System.Convert.ToDouble(elemCurrent.Atributos["LONGITUD"].Valor, System.Globalization.CultureInfo.InvariantCulture) != 0)
                        {
                            pendienteBox.Text = Math.Round(Math.Abs(
                                                         System.Convert.ToDouble(elemCurrent.Atributos["COTA_FINAL"].Valor, System.Globalization.CultureInfo.InvariantCulture) -
                                                         System.Convert.ToDouble(elemCurrent.Atributos["COTA_INICIO"].Valor, System.Globalization.CultureInfo.InvariantCulture)
                                                        ) * 100 / System.Convert.ToDouble(elemCurrent.Atributos["LONGITUD"].Valor, System.Globalization.CultureInfo.InvariantCulture)
                                                , 3).ToString(System.Globalization.CultureInfo.InvariantCulture);
                        }
                        else
                        {
                            pendienteBox.Text = "";
                        }
                        elemCurrent.Atributos["PENDIENTE"].Valor = pendienteBox.Text;
                    }
                    else
                    {
                        //pendienteBox.Text = "";
                    }
                }

            }
            catch (FormatException)
            {
                tBox.Focus();
                //System.Windows.Forms.MessageBox.Show(Properties.Resources.ElAtributoDebeSerUnValorNumerico);
                MessageBox.Show(System.String.Format(CultureInfo.CurrentCulture, GMLC01HerramientasCad.Logica.Properties.Resources.ElAtributoDebeSerUnValorNumerico, elemCurrent.Atributos[(string)tBox.Tag].Nombre),
                    "GMLC", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1, 0);
            }
            catch (OverflowException)
            {
                tBox.Focus();
                //System.Windows.Forms.MessageBox.Show(Properties.Resources.ElAtributoDebeSerUnValorNumerico);
                MessageBox.Show(System.String.Format(CultureInfo.CurrentCulture, GMLC01HerramientasCad.Logica.Properties.Resources.ElAtributoDebeSerUnValorNumerico, elemCurrent.Atributos[(string)tBox.Tag].Nombre),
                    "GMLC", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1, 0);
            }
            inValidating = false;
        }

        private void CreaControlesDinamicos(Entidad entidad)
        {
            int nAtributos = 0;

            atributosPanel.Visible = false;
            this.SuspendLayout();
            atributosPanel.Controls.Clear();

            //Comprobar si el registro tiene pendiente o no.
            byte cuentaCampos = 0;
            foreach (Atributo atributo in entidad.Atributos)
            {
                if (atributo.Codigo.Equals("COTA_INICIO", StringComparison.OrdinalIgnoreCase) ||
                    atributo.Codigo.Equals("COTA_FINAL", StringComparison.OrdinalIgnoreCase) ||
                    atributo.Codigo.Equals("LONGITUD", StringComparison.OrdinalIgnoreCase) ||
                    atributo.Codigo.Equals("PENDIENTE", StringComparison.OrdinalIgnoreCase))
                {
                    cuentaCampos++;
                }
            }
            tienePendiente = (cuentaCampos == 4);

            foreach (Atributo atributo in entidad.Atributos)
            {
                if (atributo.Codigo != ModComun.XSD.Clave)
                    CreaControl(atributo, nAtributos++);
            }

            this.ResumeLayout(true);
            atributosPanel.Visible = true;
        }

        private void ElementosBSourceCurrentChanged(object sender, EventArgs e)
        {
            //Se cambia el foco para forzar la validación de cuadros de texto numéricos.
            if (elemCurrent == (Elemento)elementosBSource.Current) return;
            guardarButton.Focus();
            elemCurrent = (Elemento)elementosBSource.Current;
            if (elemCurrent == null) return;
            this.Text = elemCurrent.CodigoEntidad;
            if (onCurrentElementChange != null) onCurrentElementChange(this, null);

            CreaControlesDinamicos(ModComun.XSD.Entidades[elemCurrent.CodigoEntidad]);

            foreach (Atributo atr in elemCurrent.Atributos)
            {
                ComboBox cBox;

                if (atr.Codigo == ModComun.XSD.Clave)
                    continue;

                switch (atr.TipoEdicion)
                {
                    case TiposEdicion.Entero:
                    case TiposEdicion.Doble:
                    case TiposEdicion.Texto:
                        this.atributosPanel.Controls[atr.Codigo + "_Control"].Text = atr.Valor;
                        break;
                    case TiposEdicion.Combo:
                        cBox = (ComboBox)this.atributosPanel.Controls[atr.Codigo + "_Control"];
                        cBox.SelectedValue = atr.Valor == null ? "" : atr.Valor;
                        break;
                }
            }

            if (centrarCheckBox.Checked) iCommIF.Centrar(elemCurrent);
            if (resaltarCheckBox.Checked) iCommIF.Resaltar(elemCurrent);
        }

        private void GuardarButtonClick(object sender, EventArgs e)
        {
            if (!initialized) return;

            if (iElementos.Count == 1)
            {
                iCommIF.Guardar(iElementos);
            }
            else
            {
                switch (MessageBox.Show(Properties.Resources.DeseaGuardarTodosLosElementosSeleccionadosOSoloElActivo,
                                        Properties.Resources.GuardarTxt, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, 0))
                {
                    case DialogResult.Yes:
                        iCommIF.Guardar(iElementos);
                        break;
                    case DialogResult.No:
                        {
                            Collection<Elemento> unElemento = new Collection<Elemento>();
                            unElemento.Add(elemCurrent);
                            iCommIF.Guardar(unElemento);
                            break;
                        }
                    case DialogResult.Cancel:
                        break;
                }
            }
            //ElementosBSourceCurrentChanged(null, null);
            if (resaltarCheckBox.Checked) iCommIF.Resaltar(elemCurrent);
        }

        private void AplicarATodosButtonClick(object sender, EventArgs e)
        {
            if (!initialized) return;

            foreach (Control control in atributosPanel.Controls)
            {
                if (control.Name.EndsWith("_CheckBox", StringComparison.Ordinal) && ((CheckBox)control).Checked)
                {
                    String nombreAtributo = control.Name.Remove(control.Name.LastIndexOf("_CheckBox", StringComparison.Ordinal));

                    foreach (Elemento elemento in (iElementos))
                    {
                        if (!elemento.Equals(elemCurrent) && elemento.Atributos.Contains(nombreAtributo))
                        {
                            elemento.Atributos[nombreAtributo].Valor = elemCurrent.Atributos[nombreAtributo].Valor;
                            if ((nombreAtributo.Equals("COTA_INICIO", StringComparison.OrdinalIgnoreCase) ||
                                 nombreAtributo.Equals("COTA_FINAL", StringComparison.OrdinalIgnoreCase) ||
                                 nombreAtributo.Equals("LONGITUD", StringComparison.OrdinalIgnoreCase)))
                            {
                                CheckPendiente(elemento);
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Chequea y recalcula la pendiente de un elemento si fuese necesario.
        /// </summary>
        /// <param name="elemento"></param>
        private void CheckPendiente(Elemento elemento)
        {
            //Comprobar si el registro tiene pendiente o no.
            byte cuentaCampos = 0;
            foreach (Atributo atributo in elemento.Atributos)
            {
                if (atributo.Codigo.Equals("COTA_INICIO", StringComparison.OrdinalIgnoreCase) ||
                    atributo.Codigo.Equals("COTA_FINAL", StringComparison.OrdinalIgnoreCase) ||
                    atributo.Codigo.Equals("LONGITUD", StringComparison.OrdinalIgnoreCase) ||
                    atributo.Codigo.Equals("PENDIENTE", StringComparison.OrdinalIgnoreCase))
                {
                    cuentaCampos++;
                }
            }
            if (cuentaCampos == 4)
            {
                if (!string.IsNullOrEmpty(elemento.Atributos["COTA_INICIO"].Valor) &&
                    !string.IsNullOrEmpty(elemento.Atributos["COTA_FINAL"].Valor) &&
                    !string.IsNullOrEmpty(elemento.Atributos["LONGITUD"].Valor)
                   )
                {
                    if (System.Convert.ToDouble(elemCurrent.Atributos["LONGITUD"].Valor, System.Globalization.CultureInfo.InvariantCulture) != 0)
                    {
                        elemento.Atributos["PENDIENTE"].Valor = (Math.Abs(
                                                                         System.Convert.ToDouble(elemento.Atributos["COTA_FINAL"].Valor, System.Globalization.CultureInfo.InvariantCulture) -
                                                                         System.Convert.ToDouble(elemento.Atributos["COTA_INICIO"].Valor, System.Globalization.CultureInfo.InvariantCulture)
                                                                        ) * 100 / System.Convert.ToDouble(elemento.Atributos["LONGITUD"].Valor, System.Globalization.CultureInfo.InvariantCulture)
                                                                ).ToString(System.Globalization.CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        elemento.Atributos["PENDIENTE"].Valor = "";
                    }
                }
                else
                {
                    elemento.Atributos["PENDIENTE"].Valor = "";
                }
            }
        }

        private void CopiarButtonClick(object sender, EventArgs e)
        {
            if (!initialized) return;

            ModComun.iPortaPapeles = new Collection<Atributo>();

            foreach (Control control in atributosPanel.Controls)
                if (control.Name.EndsWith("_CheckBox", StringComparison.Ordinal) && ((CheckBox)control).Checked)
                {
                    String nombreAtributo = control.Name.Remove(control.Name.LastIndexOf("_CheckBox", StringComparison.Ordinal));
                    ModComun.iPortaPapeles.Add((Atributo)elemCurrent.Atributos[nombreAtributo].Clone());
                }

            pegarButton.Enabled = ModComun.iPortaPapeles.Count > 0;

            if (!pegarButton.Enabled)
            {
                ModComun.iPortaPapeles.Clear();
                ModComun.iPortaPapeles = null;
            }
        }

        private void PegarEnElemento(Elemento elemento)
        {
            foreach (Atributo atr in ModComun.iPortaPapeles)
            {
                if (elemento.Atributos.Contains(atr.Codigo))
                {
                    elemento.Atributos[atr.Codigo].Valor = atr.Valor;
                }
            }
            CheckPendiente(elemento);
        }

        private void PegarButtonClick(object sender, EventArgs e)
        {
            if (!initialized) return;

            if (elemCurrent.CodigoEntidad == ModComun.iPortaPapeles[0].Entidad.Codigo)
                switch (MessageBox.Show(System.String.Format(CultureInfo.CurrentCulture, Properties.Resources.DeseaPegarEnTodosLosElementosDeTipoSeleccionadosOSoloEnElActivo, ModComun.iPortaPapeles[0].Entidad.Codigo),
                                        Properties.Resources.Pegar,
                                        MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, 0))
                {
                    case DialogResult.Yes:
                        foreach (Elemento elem in iElementos)
                            if (elem.CodigoEntidad == ModComun.iPortaPapeles[0].Entidad.Codigo)
                                PegarEnElemento(elem);
                        ElementosBSourceCurrentChanged(null, null);
                        break;
                    case DialogResult.No:
                        PegarEnElemento(elemCurrent);
                        ElementosBSourceCurrentChanged(null, null);
                        break;
                    case DialogResult.Cancel:
                        break;
                }
            else
                switch (MessageBox.Show(System.String.Format(CultureInfo.CurrentCulture, Properties.Resources.DeseaPegarEnTodosLosElementosDeTipoSeleccionados, ModComun.iPortaPapeles[0].Entidad.Codigo),
                                        Properties.Resources.Pegar, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, 0))
                {
                    case DialogResult.Yes:
                        foreach (Elemento elem in iElementos)
                            if (elem.CodigoEntidad == ModComun.iPortaPapeles[0].Entidad.Codigo)
                                PegarEnElemento(elem);
                        ElementosBSourceCurrentChanged(null, null);
                        break;
                    case DialogResult.No:
                        break;
                }
        }

        private void SalirButtonClick(object sender, EventArgs e)
        {
            if (!initialized)
            {
                this.Close();
                return;
            }
            switch (MessageBox.Show(Properties.Resources.DeseaGuardarLosCambiosRealizados,
                                    Properties.Resources.SalirTxt, MessageBoxButtons.YesNoCancel,
                                     MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, 0))
            {
                case DialogResult.Yes:
                    iCommIF.Guardar(iElementos);
                    this.Close();
                    break;
                case DialogResult.No:
                    this.Close();
                    break;
                case DialogResult.Cancel:
                    break;
            }
            //this.Close();
        }

        private void CentrarCheckBoxCheckedChanged(object sender, EventArgs e)
        {
            if (!initialized) return;

            if (((CheckBox)sender).Checked && elemCurrent != null)
                iCommIF.Centrar(elemCurrent);
            else
                iCommIF.Centrar(null);
        }

        private void ResaltarCheckBoxCheckedChanged(object sender, EventArgs e)
        {
            if (!initialized) return;

            if (((CheckBox)sender).Checked && elemCurrent != null)
                iCommIF.Resaltar(elemCurrent);
            else
                iCommIF.Resaltar(null);
        }
        /// <summary>
        /// 
        /// </summary>
        public void ActualizarIdiomaInterfaz()
        {
            try
            {
                //this.lbMessage.Text = string.Format(Properties.Resources.ConsultarSinDatos, ModComun.MaxEntidadesAutoconsulta);
                this.isEnabled = this.isEnabled;
                this.bindingNavigator1.CountItemFormat = Properties.Resources.de;
                this.bindingNavigatorCountItem.ToolTipText = Properties.Resources.TotalNumberOfItems;
                this.bindingNavigatorMoveFirstItem.Text = Properties.Resources.IrAlPrimero;
                this.bindingNavigatorMoveFirstItem.ToolTipText = Properties.Resources.IrAlPrimero;
                this.bindingNavigatorMovePreviousItem.Text = Properties.Resources.IrAlAnterior;
                this.bindingNavigatorMovePreviousItem.ToolTipText = Properties.Resources.IrAlAnterior;
                this.bindingNavigatorPositionItem.ToolTipText = Properties.Resources.Actual;
                this.bindingNavigatorMoveNextItem.Text = Properties.Resources.IrAlSiguiente;
                this.bindingNavigatorMoveNextItem.ToolTipText = Properties.Resources.IrAlSiguiente;
                this.bindingNavigatorMoveLastItem.Text = Properties.Resources.IrAlUltimo;
                this.bindingNavigatorMoveLastItem.ToolTipText = Properties.Resources.IrAlUltimo;
                this.toolTip1.SetToolTip(this.salirButton, Properties.Resources.SalirDelFormulario);
                this.toolTip1.SetToolTip(this.pegarButton, Properties.Resources.PegarValoresDelPortapapeles);
                this.toolTip1.SetToolTip(this.copiarButton, Properties.Resources.CopiarValoresSeleccionadosAlPortapapeles);
                this.toolTip1.SetToolTip(this.aplicarATodosButton, Properties.Resources.AplicarValoresSeleccionadosATodos);
                this.toolTip1.SetToolTip(this.guardarButton, Properties.Resources.GuardarLosCambios);
                this.centrarCheckBox.Text = Properties.Resources.Centrar;
                this.toolTip1.SetToolTip(this.centrarCheckBox, Properties.Resources.CentrarElElementoActivoEnPantalla);
                this.resaltarCheckBox.Text = Properties.Resources.Resaltar;
                this.toolTip1.SetToolTip(this.resaltarCheckBox, Properties.Resources.ResaltarElElementoActivoEnPantalla);
                this.Text = Properties.Resources.ConsultarEditar;
            }
            catch (Exception e)
            {
                Log.RegisterError(e);
                throw new ExcepcionGMLC(e.Message, e);
            }
        }

        private bool resized;

        protected override CreateParams CreateParams
        {
            [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
            get
            {
                CreateParams cp = base.CreateParams;
                if (resized) cp.ExStyle |= 0x02000000;
                resized = false;
                return cp;
            }
        }

        private void CtlConsultarResize(object sender, EventArgs e)
        {
            resized = true;
        }
    }
}
