﻿//
//Buscar y seleccionar valor en un combo
//
function selectDdlValue(object,value){
        for(i=0;i< object.length;i++){ // recorro todas las opciones del select 
                if (object.options[i].value == value ){
                  object.options[i].selected=true;
                  return;
                }
        }
        object.selectedIndex = 0;
}
function queryString( name ){  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");  var regexS = "[\\?&]"+name+"=([^&#]*)";  var regex = new RegExp( regexS );  var results = regex.exec( window.location.href );  if( results == null )    return "";  else    return results[1];}
function queryStringHash( name , hash ){  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");  var regexS = "[\\?&]"+name+"=([^&#]*)";  var regex = new RegExp( regexS );  var results = regex.exec( hash );  if( results == null )    return "";  else    return results[1];}
function getQueryParam(key, query) {
    
    var re = new RegExp("[?|&]" + key + "=(.*?)&");
    var matches = re.exec(query + "&");
    if (!matches || matches.length < 2)
        return "";
    return decodeURIComponent(matches[1].replace("+", " "));
}
function setQueryParam(key, value, query) {
   
    query = query;
    var q = query + "&";
    var re = new RegExp("[?|&]" + key + "=.*?&");
    if (!re.test(q))
        q += key + "=" + encodeURI(value);
    else
        q = q.replace(re, "&" + key + "=" + encodeURIComponent(value) + "&");
    q = q.trimStart("&").trimEnd("&");
    return q[0]=="" ? q : q =  q;
}
String.prototype.trimEnd = function(c) {
    if (c)        
        return this.replace(new RegExp(c.escapeRegExp() + "*$"), '');
    return this.replace(/\s+$/, '');
}
String.prototype.trimStart = function(c) {
    if (c)
        return this.replace(new RegExp("^" + c.escapeRegExp() + "*"), '');
    return this.replace(/^\s+/, '');
}

String.prototype.escapeRegExp = function() {
    return this.replace(/[.*+?^${}()|[\]\/\\]/g, "\\$0");
};

function showMessageBos(title,message,width,height,isError,hide)
    {
        var type = isError ? "error":"";
        var configuration = {
				pnotify_title: title,
				pnotify_text: message,
				pnotify_type: type,
				pnotify_history: false,
				pnotify_width: width,
				pnotify_height: height,
				pnotify_hide: hide
			}
        $.pnotify(configuration);
    }
///========================================================================
function getDNICharacter(dni_number)
{
    // devuelve la letra correspondiente a un número DNI
    var lockup = 'TRWAGMYFPDXBNJZSQVHLCKE';
    return lockup.charAt(dni_number % 23);                 		        
}
function validateDNI(dniValue){var PrimerCaracter=new String(dniValue.substring(0,1));if(PrimerCaracter.toUpperCase()=="X")return"";if(dniValue.indexOf("-")!=-1){var ArrNumeroyLetra;ArrNumeroyLetra=dniValue.split("-");if(ArrNumeroyLetra.length==2){var Numero=ArrNumeroyLetra[0];var Letra=ArrNumeroyLetra[1].toUpperCase();if(Numero.length!=8){return false}else{if(isNaN(Numero)){return false}else{if(Letra!=getDNICharacter(Numero)){return false}else{return true}}}}}else{var Numero=new String(dniValue.substring(0,dniValue.length-1));var Letra=new String(dniValue.charAt(dniValue.length-1).toUpperCase());if(Numero.length!=8){return false}else{if(isNaN(Numero)){return false}else{if(Letra!=getDNICharacter(Numero)){return false}else{return true}}}}}
function validateCIF(cif)
{
    
    var PrimerCaracter= new String(cif.substring(0,1));
    
    if(PrimerCaracter.toUpperCase() == "X")
        return true;
        
    //Comprueba que tenga 9 dígitos, el primero debe ser una letra y el resto números
    if (!/^([A-Z]\d{8})|([PX]\d{7}[A-J])$/.test(cif.toUpperCase()))
    {
        return false;
    }

    //Comprueba que la letra sea una de las posibles
    if (!/^[ABCDEFGHKLMPQSX]/.test(cif.toUpperCase()))
    {
        return false;
    }

    //Comprueba el dígito de control del CIF
    return ComprobarDigitoControlCIF(cif);
}

/*
La siguiente función se encarga de validar el dígito de control
*/
function ComprobarDigitoControlCIF(cif)
{
    var arrayCIF
    var sumaDigitosPares = 0;
    var sumaDigitosImpares = 0;
    var numero;
    var arrayNumero;
    var digitoControl;
    
    //mete el cif en un array
    arrayCIF = cif.split("");
	
    //Si no tiene 9 caracteres es incorrecto
    if (arrayCIF.length != 9)
    {
        return false;
    }
	
    //Suma los dígitos pares de la cadena resultante de quitar el primer y último caracter del CIF
    for(i = 2; i < arrayCIF.length - 1; i = i + 2)
    {
        sumaDigitosPares = sumaDigitosPares + parseInt(arrayCIF[i]);
    }

    //Multiplicar por 2 los dígitos impares de la cadena resultante de quitar el primer y último caracter del CIF
    //y con cada resultado, sumar sus dígitos. 
    //Sumarlo todo
    for(i = 1; i < arrayCIF.length - 1; i = i + 2)
    {
        numero = arrayCIF[i] * 2;
        if (numero > 9)
        {
            numero = (numero % 10) + 1
        }
		
        sumaDigitosImpares = sumaDigitosImpares + numero;
    }
	
    //Sumar la suma de dígitos pares y la de dígitos impares
    //Coger la última cifra del número obtenido y restarle 10
    numero = sumaDigitosPares + sumaDigitosImpares	
    for (i = numero; i >= 0; i = i - 10)
    {
        numero = i;
    }
    digitoControl = 10 - numero;
	
    //Para los tipos de sociedades P y X el dígito de control debe ser una letra
    if (arrayCIF[0].toUpperCase() == "P" || arrayCIF[0].toUpperCase() == "X")
    {
        digitoControl = String.fromCharCode(digitoControl + 64);
    } 
	
    //Comprueba si el dígito de control se corresponde correctamente
    if (digitoControl.toString() == arrayCIF[8])
    {
        return true;
    }
    else
    {
        return false;
    }
}
function validarEmail(valor) {  
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(valor))
    {   return true;  } 
    else {  return false;  } 
}

///========================================================================    
/// generateAlpha
///======================================================================== 
function generateAlpha( length, extraChars, firstNumber, firstLower, firstUpper, firstOther, latterNumber, latterLower, latterUpper, latterOther)
{
  var rc = "";

  if ( length > 0 )
    rc += getRandomChar(firstNumber,firstLower,firstUpper,firstOther,extraChars);

  for ( var idx = 1; idx < length; ++idx )
    rc += getRandomChar(latterNumber,latterLower,latterUpper,latterOther,extraChars);

  return rc;
}


///========================================================================    
/// getRandomChar
///======================================================================== 
function getRandomChar( number, lower, upper, other, extra )
{
  var numberChars = "0123456789";
  var lowerChars  = "abcdefghijklmnopqrstuvwxyz";
  var upperChars  = "abcdefghijklmnopqrstuvwxyz";
  var otherChars  = "`~!@#$%^&*()-_=+[{]}\\|;:'\",<.>/? ";
  var charSet     = extra;

  if ( number ) charSet += numberChars;
  if ( lower )  charSet += lowerChars;
  if ( upper )  charSet += upperChars;
  if ( other )  charSet += otherChars;

  return charSet.charAt(getRandomNum(0,charSet.length));
}

///========================================================================    
/// getRandomNum
///======================================================================== 
function getRandomNum( lbound, ubound )
{
  return (Math.floor(Math.random() * (ubound - lbound)) + lbound);
}