function validarEmail(source, args) {
    args.IsValid = isValidEmail(args.Value);
}
function validarRequired(source, args) {
    var obj = jQuery("#" + source.controltovalidate);
    if (jQuery.trim(obj.val()) == "") {
        obj.addClass("errorInputNewsletter");
        args.IsValid = false;
    }
    else {
        obj.removeClass("errorInputNewsletter");
    }
}
var auxObject;
function validarCombo(source, args) {
    auxObject = jQuery("#" + source.controltovalidate);
    args.IsValid = auxObject.val() != "-1" && auxObject.val() != "";
}

function validarEmailNewsletter(source, args) {
    var obj = jQuery("#" + source.controltovalidate);
    if (jQuery.trim(obj.val()) == "") {
        obj.addClass("errorInputNewsletter");
        args.IsValid = false;
    }
    else {
        if (args.IsValid = isValidEmail(args.Value)) {
            obj.removeClass("errorInputNewsletter");
        }
        else {
            obj.addClass("errorInputNewsletter");
        }
    }
}
function isValidEmail(str) {
    
    if (str == null || str == "") return false;
    validRegExp = /^[^@]+@[^@]+.[a-z]{2,}$/i;
    strEmail = str;

    // search email text for regular exp matches
    if (strEmail.search(validRegExp) == -1) {        
        return false;
    }
    return true;

}

function validarRequiredEnabled(source, args) {
    var input = jQuery("#" + source.controltovalidate);
    if (input.attr("disabled")=="" && jQuery.trim(input.val()) == "") {
        args.IsValid = false;
    }
}

function validarMax(source, args) {
    var inputMax = jQuery("#" + source.controltovalidate);
    var inputMin = jQuery("." + inputMax.attr("par"));
    if (inputMax.attr("disabled") == "") {
        if (jQuery.trim(inputMin.val()) != "" && jQuery.trim(inputMax.val()) != "") {
            var valMin = parseInt(inputMin.val());
            var valMax = parseInt(inputMax.val());
            if (valMin > valMax) {
                args.IsValid = false;
            }
            
        }
    }
}



// ralvarezg
// corregir URL (anyadir http:// al comienzo)
// el parametro es el elemento INPUT TEXT del formulario,
// puede ejecutarse durante los eventos onchange, onsubmit, ...
function correctUrl(inputTextItem)
{
  // corregimos si: 
  // no comienza por '/',
  // si tiene algun punto (ej www.google)
  // si no contiene '://'
  if ( inputTextItem.value.indexOf('.') >= 0 
  && inputTextItem.value.charAt(0) != '/' 
  && inputTextItem.value.indexOf('://') == -1 )
  {
    inputTextItem.value = 'http://' + inputTextItem.value
  }
}

function abrirpopup(url, title) {
 var ventana=window.open(url,title,"width=850,height=800,resizable=yes,scrollbars=yes,menubar=no"); 
 return false;
}
function popup(url, title, width, height) {
    var parametros = "width=" + width + ",height=" + height + ",resizable=yes,scrollbars=yes,menubar=no";
    var ventana = window.open(url, title, parametros);
    return false;
}
function add_row(str)
{
  var oTbl = document.getElementById(str);
  var oRow = oTbl.rows[oTbl.rows.length-1];
  var oTBody = oTbl.getElementsByTagName("tbody").item(0);
  oTBody.appendChild(oRow.cloneNode(true));
  //oTbl.appendChild(oRow.cloneNode(true));
  var str2 = str.substring(6) + '_preferido';
  var i, v = eval('document.form1.'+str2);
  
  if (v) for (i = 0; i < v.length; i++) v[i].value = i;
}

function msg_win(pForm)
{
  oWin = window.open("","ventana_mensaje", "width=300,height=200,resizable=yes");
  document.forms[pForm].submit();
}

function imprimir(n, m)
{
  if (!confirm("Confirme que desea imprimir el documento")) return;
  
  var str = "ctl_servlet?_f=59&pident="+n;
  if (m != undefined) str = str+"&pexpediente="+m;
  window.open(str,"","");
}


function foco(obj) {
    obj.style.backgroundColor = '#febf10';
}

function nofocod(obj) {
  obj.style.backgroundColor = '#E6E6E6';
}

function nofoco(obj) {
  obj.style.backgroundColor = '#FFFFFF';
}

// ralvarezg...
// activar y desactivar SUBMIT
    // desactiva boton input type submit
    function disableButton(inputButtonItem)
    {
      //alert('disabling');
      inputButtonItem.disabled = true;
    }
    // activa boton input type submit
    function enableButton(inputButtonItem)
    {
      //alert('enabling');
      inputButtonItem.disabled = false;
    }  
    function enableDisableButtonWhenEmpty(inputButtonItem,inputTextItem)
    {
       //alert('actualizando boton...');
       if ( inputTextItem.value == "" )
         disableButton(inputButtonItem);
       else
         enableButton(inputButtonItem);
    }
    // colocado dentro del evento onSubmit de un formulario, impide hacer submit
    // si el input text pasado como param esta vacio
    // ej: onsubmit="return blockSubmitWhenEmpty(this.elements['pbuscar']);"
    function blockSubmitWhenEmpty(inputTextItem)
    {
      //alert('check submit...');
      if ( inputTextItem.value == "" ) return false;
    }
    // colocado dentro del evento onSubmit de un formulario, impide hacer submit
    // si el input text pasado como param esta vacio
    // ademas, muestra una alerta indicando el error
    // ej: onsubmit="return blockSubmitWhenEmptyWithAlert(this.elements['pbuscar'],'Introduzca cadena de búsqueda.');"
    function blockSubmitWhenEmptyWithAlert(inputTextItem,alertText)
    {
      //alert('check submit...');
      if ( inputTextItem.value == "" ) 
      {
        alert(alertText);
        return false;
      }
    }

/***********************************************
Fechas 
**************************************************/

function IsNumeric(valor) 
{ 
var log=valor.length; var sw="S"; 
for (x=0; x<log; x++) 
{ v1=valor.substr(x,1); 
v2 = parseInt(v1); 
//Compruebo si es un valor numérico 
if (isNaN(v2)) { sw= "N";} 
} 
if (sw=="S") {return true;} else {return false; } 
} 

var primerslap=false; 
var segundoslap=false; 

function formateafecha(fecha) 
{ 
var long = fecha.length; 
var dia; 
var mes; 
var ano; 

if ((long>=2) && (primerslap==false)) { dia=fecha.substr(0,2); 
if ((IsNumeric(dia)==true) && (dia<=31) && (dia!="00")) { fecha=fecha.substr(0,2)+"/"+fecha.substr(3,7); primerslap=true; } 
else { fecha=""; primerslap=false;} 
} 
else 
{ dia=fecha.substr(0,1); 
if (IsNumeric(dia)==false) 
{fecha="";} 
if ((long<=2) && (primerslap=true)) {fecha=fecha.substr(0,1); primerslap=false; } 
} 
if ((long>=5) && (segundoslap==false)) 
{ mes=fecha.substr(3,2); 
if ((IsNumeric(mes)==true) &&(mes<=12) && (mes!="00")) { fecha=fecha.substr(0,5)+"/"+fecha.substr(6,4); segundoslap=true; } 
else { fecha=fecha.substr(0,3);; segundoslap=false;} 
} 
else { if ((long<=5) && (segundoslap=true)) { fecha=fecha.substr(0,4); segundoslap=false; } } 
if (long>=7) 
{ ano=fecha.substr(6,4); 
if (IsNumeric(ano)==false) { fecha=fecha.substr(0,6); } 
else { if (long==10){ if ((ano==0) || (ano<1900) || (ano>2100)) { fecha=fecha.substr(0,6); } } } 
} 

if (long>=10) 
{ 
fecha=fecha.substr(0,10); 
dia=fecha.substr(0,2); 
mes=fecha.substr(3,2); 
ano=fecha.substr(6,4); 
// Año no viciesto y es febrero y el dia es mayor a 28 
if ( (ano%4 != 0) && (mes ==02) && (dia > 28) ) { fecha=fecha.substr(0,2)+"/"; } 
} 
return (fecha); 
}

function findValue(li) {
    if (li == null) return alert("No match!");

    // if coming from an AJAX call, let's use the CityId as the value
    if (!!li.extra) var sValue = li.extra[0];

    // otherwise, let's just display the value in the text box
    else var sValue = li.selectValue;

    //alert("The value you selected was: " + sValue);
}

function selectItem(li) {
    findValue(li);
}

function formatItem(row) {
    return row[0] + " (id: " + row[1] + ")";
}

function iniAutoCompleteField(field,url,key, maxRows,tipoResultadoField,poblacionField){
    keyw = document.getElementById(field);

    var poblacion;
    var tipoResultado;
    
    if (tipoResultadoField != '' && poblacionField != '') {
        tipoResultado = document.getElementById(tipoResultadoField);
        poblacion = document.getElementById(poblacionField);
    }
    
    new Autocomplete(field, function() {
        return url+'?'+key+'='+this.value+'&maxRows='+maxRows+( tipoResultado!=null && tipoResultado!=undefined && tipoResultado.value=='Poblacion' && poblacion!=null && poblacion!=undefined?'&poblacionValue='+poblacion.value:'' );
    });
}

function iniAutoCompleteFieldByTable(field, url, key, maxRows,tabla) {
    keyw = document.getElementById(field);
    
    new Autocomplete(field, function() {
        return url + '?' + key + '=' + this.value + '&maxRows=' + maxRows + '&Tabla='+tabla;
    });
}
  
   /*************
    Funcion que deshabilita todos los objetos del formulario aspnetForm.    
    *****************/
    function desactivarInputs() {

        var form = document.getElementById('aspnetForm');

        for (var i = 0; i < form.elements.length; i++) 
        {
            var elemento = form.elements[i];
            if (elemento.type == "text" || elemento.type == "checkbox" || elemento.type == "radio" || elemento.type=="password" ||
            elemento.type == "file" || elemento.type == "select-one" || elemento.type == "select-multiple" || elemento.type == "textarea") 
            {
                elemento.disabled="disabled";        
                elemento.setAttribute(document.all ? 'className' : 'class', elemento.getAttribute(document.all ? 'className' : 'class') + " disabled");        
                
            }
        }    
    }
    
    /*************
    Funcion que quita la visualizacion del los mensajes.    
    *****************/
    function hiddenMessages() {  
    //alert('iniciando acultarMessages');
        var form = document.getElementsByTagName("p");
        for (var i = 0; i < form.length; i++) 
        {
            var elemento = form[i];
            var classname= elemento.getAttribute(document.all ? 'className' : 'class');
            //alert(elemento+" - "+classname);
            if (classname == "actionMessage" ) 
            {
                elemento.style.display='none';                
                
            }
        }
    }
    
    
/***********************************************
Fechas 
**************************************************/

function IsNumeric(valor) 
{ 
var log=valor.length; var sw="S"; 
for (x=0; x<log; x++) 
{ v1=valor.substr(x,1); 
v2 = parseInt(v1); 
//Compruebo si es un valor numérico 
if (isNaN(v2)) { sw= "N";} 
} 
if (sw=="S") {return true;} else {return false; } 
} 

var primerslap=false; 
var segundoslap=false; 

function formateafecha(fecha) 
{ 
var long = fecha.length; 
var dia; 
var mes; 
var ano; 

if ((long>=2) && (primerslap==false)) { dia=fecha.substr(0,2); 
if ((IsNumeric(dia)==true) && (dia<=31) && (dia!="00")) { fecha=fecha.substr(0,2)+"/"+fecha.substr(3,7); primerslap=true; } 
else { fecha=""; primerslap=false;} 
} 
else 
{ dia=fecha.substr(0,1); 
if (IsNumeric(dia)==false) 
{fecha="";} 
if ((long<=2) && (primerslap=true)) {fecha=fecha.substr(0,1); primerslap=false; } 
} 
if ((long>=5) && (segundoslap==false)) 
{ mes=fecha.substr(3,2); 
if ((IsNumeric(mes)==true) &&(mes<=12) && (mes!="00")) { fecha=fecha.substr(0,5)+"/"+fecha.substr(6,4); segundoslap=true; } 
else { fecha=fecha.substr(0,3);; segundoslap=false;} 
} 
else { if ((long<=5) && (segundoslap=true)) { fecha=fecha.substr(0,4); segundoslap=false; } } 
if (long>=7) 
{ ano=fecha.substr(6,4); 
if (IsNumeric(ano)==false) { fecha=fecha.substr(0,6); } 
else { if (long==10){ if ((ano==0) || (ano<1900) || (ano>2100)) { fecha=fecha.substr(0,6); } } } 
} 

if (long>=10) 
{ 
fecha=fecha.substr(0,10); 
dia=fecha.substr(0,2); 
mes=fecha.substr(3,2); 
ano=fecha.substr(6,4); 
// Año no viciesto y es febrero y el dia es mayor a 28 
if ( (ano%4 != 0) && (mes ==02) && (dia > 28) ) { fecha=fecha.substr(0,2)+"/"; } 
} 
return (fecha); 
} 

/*******************Mascara hora textbox***************************/

var patron = new Array(2,2);
function mascaraHora(d,sep,pat,nums){ 
		
	if(d.valant != d.value){ 
	val = d.value ;
	largo = val.length ;
	val = val.split(sep); 
	val2 = ""; 
	for(r=0;r<val.length;r++){ 
	val2 += val[r]; 
	} 
	if(nums){ 
	for(z=0;z<val2.length;z++){ 
	if(isNaN(val2.charAt(z))){ 
	letra = new RegExp(val2.charAt(z),"g") ;
	val2 = val2.replace(letra,""); 
	} 
	} 
	} 
	val = ""; 
	val3 = new Array();
	for(s=0; s<pat.length; s++){ 
	val3[s] = val2.substring(0,pat[s]);
	val2 = val2.substr(pat[s]);
	} 
	for(q=0;q<val3.length; q++){ 
	if(q ==0){ 
	val = val3[q];
	} 
	else{ 
	if(val3[q] != ""){ 
	val += sep + val3[q];
	} 
	} 
	} 
	d.value = val;
	d.valant = val; 
	} 
	if (val.length==5){ 
		var horaArray=val.split(":");
		if ((horaArray[0]>23) ||(horaArray[1]>59)) {
			alert("Recuerde el formato de Horas, desde 00:00 hasta 23:59 ");
			d.value="";
		}
	} 
} 


/*************************************************/

function FormatNumber(amount) {
    
	var val = parseFloat(amount); 
	if (isNaN(val)) 
		{ return "0.00"; } 
	if (val <= 0) 
		{ return "0.00"; } 
	val += ""; 
	// Next two lines remove anything beyond 2 decimal places 
	if (val.indexOf('.') == -1) 
		{ return val+".00"; } 
	else 
		{ val = val.substring(0,val.indexOf('.')+3); } 
		
	val = (val == Math.floor(val)) ? val + '.00' : ((val*10 == Math.floor(val*10)) ? val + '0' : val); 
	return val;
}


function DetectorEnter(This, evt, instruccion) {
    evt = (evt) ? evt : event;
    var code = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
         ((evt.which) ? evt.which : 0));
    if (code == 13) {//Enter
        eval(instruccion);    
    }
}
/**
    mascara par forzar al usuario ingresar solo números
    This: el puntero al input.
    evt: el evento "event".
    AllowDot: true = permite valores con decimales y no caso contrario.
    AllowMinus: true = controla valores negativos, osea que no se inserte el - en cualquier parte del numero poner siempre en true este valor.
**/
function ForceNumericInput(This,evt, AllowDot, AllowMinus)
	{
		
		if(arguments.length == 1)
		{
        	var s = This.value;
        	// if "-" exists then it better be the 1st character
        	var i = s.lastIndexOf("-");
        	if(i == -1)
            	return;
        	if(i != 0)
           		This.value = s.substring(0,i)+s.substring(i+1);
           	return;
        }
				
        evt = (evt) ? evt : event;
    		var code = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
         ((evt.which) ? evt.which : 0));
         
        //alert(code);
        switch(code)
        {	
            case 116:			//F5
        	case 9:			//tab
            case 8:     // backspace
            case 37:    // left arrow
            case 39:    // right arrow
            case 46:    // delete
               if(!evt.preventDefault){ evt.returnValue = true};
                return;
        }
        if(code == 189 || code == 109 )     // minus sign
        {
        	if(AllowMinus == false)
        	{
              if(!evt.preventDefault){ evt.returnValue = true};
                return;
            }


            // wait until the element has been updated to see if the minus is in the right spot
            var s = "ForceNumericInput(document.getElementById('"+This.id+"'))";
            setTimeout(s, 250);
            return;
        }
        if(AllowDot && (code == 190 || code == 110)) {

            var cambiar = "cambiar( '" + This.id + "')";
            setTimeout(cambiar, 50);
            
            if(This.value.indexOf(".") >= 0) {
                // don't allow more than one dot
                if (!evt.preventDefault) {  evt.returnValue = false };
                return;
            }
            if (!evt.preventDefault) { evt.returnValue = true };
            return;
        }
        // allow character of between 0 and 9
        if((code >= 48 && code <= 57) || (code >=96 && code <= 105))
        {
            if(!evt.preventDefault){ evt.returnValue = true};
            return;
        }
     	if(evt.preventDefault){ 
     		evt.preventDefault()}
     		else
     		{evt.returnValue = false};

   }
   function cambiar(id) {
       field = document.getElementById(id);
       field.value=field.value.split('.').join(',');
   }
   function formatoCalculable(numero) {
   return numero.split(',').join('.');
   }	
/*************Funcion que muestra el div en la posicion del mouse************/

function showdiv(event,nombreDiv)
{
    var div;
    if(document.getElementById(nombreDiv))
        div=document.getElementById(nombreDiv);
    else
        div=document.getElementById('ctl00_cuerpo_'+nombreDiv);
        
	//determina un margen de pixels del div al raton
	margin=5;

	//La variable IE determina si estamos utilizando IE
	var IE = document.all?true:false;

	var tempX = 0;
	var tempY = 0;

	//document.body.clientHeight = devuelve la altura del body
	if(IE)
	{ //para IE
		//event.y|event.clientY = devuelve la posicion en relacion a la parte superior visible del navegador
		//event.screenY = devuelve la posicion del cursor en relaciona la parte superior de la pantalla
		//event.offsetY = devuelve la posicion del mouse en relacion a la posicion superior de la caja donde se ha pulsado
		tempX = event.x
		tempY = event.y
		/*if(window.pageYOffset){
			tempY=(tempY+window.pageYOffset);
			tempX=(tempX+window.pageXOffset);
		}else{
			tempY=(tempY+Math.max(document.body.scrollTop,document.documentElement.scrollTop));
			tempX=(tempX+Math.max(document.body.scrollLeft,document.documentElement.scrollLeft));
		}*/
	}else{ //para netscape
		//window.pageYOffset = devuelve el tamaño en pixels de la parte superior no visible (scroll) de la pagina
		document.captureEvents(Event.MOUSEMOVE);
		tempX = event.pageX;
		tempY = event.pageY;
	}

	if (tempX < 0){tempX = 0;}
	if (tempY < 0){tempY = 0;}

	//modificamos el valor del id posicion para indicar la posicion del mouse
//	document.getElementById('posicion').innerHTML="PosX = "+tempX+" | PosY = "+tempY;

	//window.alert(event.pageYOffset+" - "+document.body.pageYOffset+" - "+screen.pageYOffset+" - "+this.pageYOffset+" - "+window.pageYOffset);
   
	div.style.top = (tempY+margin)+"px";
	div.style.left = (tempX+margin)+"px";
	div.style.display='block';
	return;
}
function hidenDiv(nombreDiv){
if(document.getElementById(nombreDiv))
        document.getElementById(nombreDiv).style.display='none';
    else
        document.getElementById('ctl00_cuerpo_'+nombreDiv).style.display='none';	
}
	
	
	
function CantidadBuscadorArticulos(field,stock){
    if(parseFloat(field.value)>parseFloat(stock))
    {
        field.value=stock;
    } 
    
    if(parseFloat(field.value)<0)
    field.value='0';
    
    nofoco(field);
}

function formatNumber(num) {
    var euro = String.fromCharCode(8364);
    num = num.toString().replace('.', '');
    num = num.toString().replace(euro, '');
    num = num.toString().replace('g', '');
    num = num.toString().replace(",", ".");
    return num;
}

function formatCurrency(num) {
    
    if (isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + '.' +
num.substring(num.length - (4 * i + 3));
    return (((sign) ? '' : '-') + num + ',' + cents + ' '+String.fromCharCode(8364));
}

function formatoNumerico(num){

    if (isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + '.' +
    num.substring(num.length - (4 * i + 3));
    return (((sign) ? '' : '-') + num + ',' + cents );
}

function getFlashObject(movieName) {
 return    document.getElementById(movieName);
}
