
window.onerror = new Function("return true;");

var y2k;

function pad2(number) {
   
     return (number < 10 ? '0' : '') + number;
   
}

function restante(fin) {
	
	now = new Date();
	y2k = new Date(fin);

	dias = (y2k - now) / 1000 / 60 / 60 / 24;
	dias = Math.floor(dias);
	horas = (y2k - now) / 1000 / 60 / 60 - (24 * dias);
	horas = Math.floor(horas);
	minutos = (y2k - now) / 1000 /60 - (24 * 60 * dias) - (60 * horas);
	minutos = Math.floor(minutos);
	segundos = (y2k - now) / 1000 - (24 * 60 * 60 * dias) - (60 * 60 * horas) - (60 * minutos);
	segundos = Math.round(segundos);
	s = (segundos == 1) ? " segundo" : " segundos";
	m = (minutos == 1) ? " minuto" : " minutos";
	h = (horas == 1) ? " hora" : " horas";
	d = (dias == 1) ? " dia" : " dias";

	if (dias<1 && horas<1 && minutos<1 && segundos<1) {
		document.write("Lote Terminado" );
	} else {
		var resto = "<font>Esta subasta termina en</font>";
		if(dias>0) {resto += '<br /><b>' + pad2(dias) + '</b>' + d;}
		if(horas>0) resto += '<br /><b>' + pad2(horas) + '</b>' + h;
		if(minutos>0) resto += '<br /><b>' + pad2(minutos) + '</b>' + m;
		if(segundos>0) resto += '<br /><b>' + pad2(segundos) + '</b>' + s;
//		resto += "  publicaci&oacute;n";

		document.getElementById('tiempo_restante').innerHTML = resto;
		newtime = window.setTimeout("restante(y2k)", 1000);
	}
}
function checkM(t)
{
	var v = t.value;

	if(v!='')
	{
		var respuesta = "";

		ajax=objetoAjax();
		ajax.open("GET", "chequeousuario.php?mail="+v,true);

		ajax.onreadystatechange=function() {
			if (ajax.readyState==4) 
			{
				respuesta = ajax.responseText;
	
				if(respuesta==1) {
					$('logueate_m').appear({duration: 0.20});
					if($('registrate_m').visible()) $('registrate_m').fade({duration: 0.20});
				}
				else {
					$('registrate_m').appear({duration: 0.20});
					if($('logueate_m').visible()) $('logueate_m').fade({duration: 0.20});
					setTimeout("document.getElementById('nom_I').focus()",210);
				}
			}
		}
		ajax.send(respuesta);
	}
}

function noCtrl(evt) {

	var charCode = (evt.which) ? evt.which : evt.keyCode
/*
	var pressedKey = String.fromCharCode(e.keyCode).toLowerCase();

	if (e.ctrlKey && (pressedKey == "c" || pressedKey == "v")) {
		e.returnValue = false;
	}*/

	return (charCode!=17 && !evt.ctrlKey);
}

function tabear(tabeable,t) {	

	var divs = document.getElementsByClassName("tabeable");
	for(var i=0;i<divs.length; i++) {
		divs[i].style.display = "none";
	}
	document.getElementById(tabeable).style.display = "";

	var tabs = document.getElementById("tabs").getElementsByTagName("div");
	for(var i=0;i<tabs.length; i++) {
		if(tabs[i].className!="ader") {tabs[i].className = "";}
	}
	t.parentNode.className = "active";
}

function tabear(tabeable,t,esto)
{
	var divs = document.getElementsByClassName("tabeable");
	for(var i=0;i<divs.length; i++) {
		divs[i].style.display = "none";
	}
	document.getElementById(tabeable).style.display = "";

	var tabs = document.getElementById("tabs").getElementsByTagName("div");
	for(var i=0;i<tabs.length; i++) {
		if(tabs[i].className!="ader") {tabs[i].className = "";}
	}
	t.parentNode.className = "active";
}

function tabearA(tabeable,t,esto)
{	
	var divs = document.getElementsByClassName("tabb");
	for(var i=0;i<divs.length; i++) {
		divs[i].style.display = "none";
	}
	document.getElementById(tabeable).style.display = "";

	if(tabeable=='crear_nuevo')
	{
		posteoAjax('perfil_cliente/estable_nuevo.php','1=1','crear_nuevo',1,1);
		if(document.getElementById('enviar').style.display=='none')
			{document.getElementById('editar').onclick();}

		document.getElementById('enviar').value = 'Crear';
//		document.getElementById('enviar').style.display = '';
//		document.getElementById('editar').style.display = 'none';
	}
	else
	{
		document.getElementById('crear_nuevo').innerHTML = '';
	//	document.getElementById('enviar').value = 'Guardar';

//		if(document.getElementById('enviar').style.display=='')
//		{ document.getElementById('editar').onclick(); }
//		document.getElementById('enviar').style.display = 'none';
//		document.getElementById('editar').style.display = '';
	}

	var tabs = document.getElementById("tabs_esta").getElementsByTagName("div");
	for(var i=0;i<tabs.length; i++) {
		if(tabs[i].className!="ader") {tabs[i].className = "";}
	}
	t.parentNode.className = "active";
}

function getElementValue(formElement)
{
	if(formElement.length != null) var type = formElement[0].type;
	if((typeof(type) == 'undefined') || (type == 0)) var type = formElement.type;

	switch(type)
	{
		case 'undefined':return;

		case 'radio':
			if(formElement.checked==true) {
				return formElement.value;
			}

		case 'select-multiple':
			var myArray = new Array();
			for(var x=0; x < formElement.length; x++)
				if(formElement[x].selected == true)
					myArray[myArray.length] = formElement[x].value;
			return myArray;

		case 'checkbox':return formElement.checked;

		default:return formElement.value;
	}
}

function generoQuery(form) {

	var query = "";

    var f = form.elements;

	for(var i=0; i<f.length; i++)
	{
		if(f[i].type == 'button') {
			if(f[i].className=='marc') { 
				var key = f[i].name;
				var value = getElementValue(f[i]);
				if(key!="" && value!="") {query += key +"="+ value +"&";}
			}
		}
		else
		{
			var key = f[i].name;
			var value = getElementValue(f[i]);
			if(key!="" && value!="") {query += key +"="+ value +"&";}
		}
	}
	return query;
}

function postMonitor(evento,param)
{
	post = 'evento='+evento+'&param='+param;
	ajaxx = new objetoAjax(); 
	ajaxx.open("POST", 'ajax_monitor.php', true);
	ajaxx.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
	ajaxx.send(post);
}

function posteoAjax(url,f,chang,loader,fade,evale)
{
	var ajax = new Array(1000);

	var r = parseInt(Math.random()*1000);

	if(!chang)
	{
		var cambio = document.getElementById('cambio');
		cambio.innerHTML = '<div class="loadinggg"><img src="imagenes/load.gif" /></div>';
	}
	else
	{
		var cambio = document.getElementById(chang);
		if(loader) {cambio.innerHTML = '<span class="loadinggg"><img src="imagenes/load.gif" /></span>';}
	}

	var post = "";

	if(f)
	{
		a_buscar = /=/g;
	
		if(a_buscar.test(f))
		{
			post = f;
		}
		else
		{
			post = generoQuery(f);
		}
	}
	
	ajax[r] = new objetoAjax(); 
	ajax[r].open("POST", url, true);
	ajax[r].setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');

	ajax[r].onreadystatechange=function()
	{
		if (ajax[r].readyState == 4)
		{
			cambio.style.display = 'none';
			cambio.innerHTML = ajax[r].responseText;
			if(fade) {
				new Effect.Appear(cambio, {duration: 0.2} );		
			}
			else
			{
				cambio.style.display = '';			
			}
			if(evale) {eval(evale);}
		}
	}
	ajax[r].send(post);
}

var contador_seleccionados;

function macarTodosCheck(f)
{
	ch = f.form.getElementsByTagName("input");
	
	for(i=0; i< ch.length; i++)
	{
		if(ch[i].type=="checkbox")
		{
			if(f.checked) {ch[i].checked=true;} else {ch[i].checked=false;}
		}
	}
}

function contar_fotos_seleccionadas(){
	contador_seleccionados++;
}

function restar_fotos_seleccionadas(){
	contador_seleccionados--;
}

function cargando() 
{
	if(document.getElementById('cargando'))
	{
		document.getElementById('cargando').style.display = "block";
	}
}

function gc_load() {
	
	if(document.getElementById('mailh'))
	{
		var mh = document.getElementById('mailh').value;
	}
	else
	{
		var mh = '';
	}
	
	if( mh != document.getElementById('maill_M').value ) {
		cargando();
	} 
}

function cambiar_fondo(id,color,revisacion){	
	if(color == 0 )
	{
		input = document.getElementById(id).getElementsByTagName("input").value=1;
		document.getElementById(id).innerHTML = 
		"<img src='videos/"+revisacion+"' style='border: 2px solid #00FF00' width='100' height='75' " +
		"onclick=\"cambiar_fondo('"+id+"','1','"+revisacion+"'); restar_fotos_seleccionadas();\" style='cursor:pointer;' /> " +
		"<input type='hidden' value='1' name='"+id+"_sel'>";		
	}
	else
	{
		input = document.getElementById(id).getElementsByTagName("input")[0].value=0;
		document.getElementById(id).innerHTML =  "<img src='videos/"+revisacion+"' style='border: 2px solid #FF0000' width='100' height='75' " +
		"onclick=\"cambiar_fondo('"+id+"','0','"+revisacion+"'); contar_fotos_seleccionadas();\" style='cursor:pointer;' /> " +
		"<input type='hidden' value='0' name='"+id+"_sel'>";
	}
}

function tog(div,asd) {
		div = document.getElementById(div);
		signo = getElementsByClassName('signo',asd)[0];

		Effect.toggle(div, 'blind', {duration: 0.20} );

		if ( signo.innerHTML=="+") {signo.innerHTML = "-";}
		else {signo.innerHTML = "+";}
}

function chequear_cantidad_fotos(){
	
	if(contador_seleccionados == 0)
	{
		alert("No ha seleccionado ninguna foto, por favor elija 6.");
		return false;
	}
	if(contador_seleccionados < 6)
	{
		alert("Solamente selecciono "+contador_seleccionados+" fotos, por favor elija 6.");
		return false;
	}
	if(contador_seleccionados > 6)
	{
		alert("Selecciono "+contador_seleccionados+" fotos, por favor elija solamente 6.");
		return false;
	}
	
	return true;
}

function cambiar_noticia(inicio){
	var Resultado;
		Resultado = document.getElementById('noticia');
		nav = document.getElementById('nav_noticia');
		ajax=objetoAjax();
		ajax.open("GET", "leer_noticias.php?inicio="+inicio,true);
		ajax.onreadystatechange=function() {
	
			if (ajax.readyState!=4)
			{
				nav.innerHTML = '<img src="imagenes/ajax-loader.gif">';
				if(!(navigator.appName == "Microsoft Internet Explorer") && !(navigator.appVersion > 5))
				{
				new Effect.Opacity(Resultado, {from: 1, to: 0, duration: 0});
				}
			}
			if (ajax.readyState==4) 
			{
				Resultado.innerHTML = ajax.responseText;
				if(!(navigator.appName == "Microsoft Internet Explorer") && !(navigator.appVersion > 5))
				{
				new Effect.Opacity(Resultado, {from: 0, to: 1, duration: 1});
				}
			}			
		}	
		ajax.send(null);
}

function ver_costos_lote(id){
	var Resultado;
		Resultado = document.getElementById('ver_lote');
		ajax=objetoAjax();
		ajax.open("GET", "ver_lote_costos.php?id="+id,true);
		ajax.onreadystatechange=function() {
	
			if (ajax.readyState!=4)
			{
				Resultado.innerHTML = '<img src="imagenes/ajax-loader.gif">';
			}
			if (ajax.readyState==4) 
			{					
				Resultado.innerHTML = ajax.responseText;	
			}			
		}
		ajax.send(null);	
}

function flete_(){	
	if($('flete').style.display=='none')
	{
		new Effect.Fade('ver_lote', {duration: 0.15});
		if($('0810')) new Effect.Fade('0810', {duration: 0.15});
		setTimeout("new Effect.Appear('flete', { duration: 0.3 });",300);
	}
	else
	{
		new Effect.Fade('flete', {duration: 0.15});
		setTimeout("new Effect.Appear('ver_lote', { duration: 0.3 }); if($('0810')) new Effect.Appear('0810', { duration: 0.3 });",300);
	}
}
function lote_media(param,thi){

	v = $('video');
	links = document.getElementById('m_barra').getElementsByTagName('a');
	for ( var i=0; i<links.length; i++ ) {links[i].className = '';} // quito estilo a todos
	thi.className = 'selected';	

	if(param!='f') {new Effect.Fade('fotos_lote', {duration: 0});}
	if(param!='m') {new Effect.Fade('mapa_lote', {duration: 0});}
	if(param!='v') {v.style.visibility = 'hidden';v.style.zIndex = -1;}

	if(param=='f') {new Effect.Appear('fotos_lote', {duration: 0.3});}
	if(param=='m') {new Effect.Appear('mapa_lote', {duration: 0.3});}
	if(param=='v') {v.style.visibility = 'visible';v.style.zIndex = 998;}
}
function alerta_login_registracion(){
	
		var rev = document.getElementById("revisacion").value;
		
		Shadowbox.open
		({
	        content:    'nuevo_decampoacampo.php?revisacion='+rev,
	        player:     "iframe",
	        height:     "385",
	        width:      "710"
	    });
}
	
function aviso_de_registro(revisacion)
{
	var Resultado;
		Resultado = document.getElementById('boton_interes');
		ajax=objetoAjax();
		ajax.open("GET", "interes.php?revisacion=" + revisacion ,true);
		ajax.onreadystatechange=function() {
	
			if (ajax.readyState!=4)
			{
				Resultado.innerHTML = '<img src="imagenes/ajax-loader.gif">';
			}
			if (ajax.readyState==4) 
			{					
					 ajax.responseText;	
					if(ajax.responseText == 1)
					{
						Resultado.style.background = "none";
						Resultado.innerHTML = "<b>Se Ha Registrado su inter&eacute;s por este lote</b>";
					}
					else
					{
						Resultado.style.background = "none";
						Resultado.innerHTML = "<b>Ya se ha registrado su inter&eacute;s por este lote</b>";
					}					
			}			
		}	
		ajax.send(null)	
}

function aviso_de_registro_mas_usuario(revisacion)
{
	var Resultado;
	if(document.getElementById('boton_interes')) {
		Resultado = document.getElementById('boton_interes');
	}
		ajax=objetoAjax();
		ajax.open("GET", "interes.php?revisacion=" + revisacion +"&reg" ,true);
		ajax.onreadystatechange=function() {
	
		if(document.getElementById('boton_interes')) {
			if (ajax.readyState!=4)
			{
				Resultado.innerHTML = '<img src="imagenes/ajax-loader.gif">';
			}
			if (ajax.readyState==4) 
			{					
					ajax.responseText;	
					if(ajax.responseText == 1)
					{Resultado.innerHTML = "";}
					else
					{Resultado.innerHTML = "";}					
			}			
		}
		}
		ajax.send(null)	
}

function desplegar() {	
	var perfil = document.getElementById('perfil');	
	var li_perfil = document.getElementById('li_perfil');
		Effect.toggle(perfil, 'blind', {duration: 0.15} );
		
	if (perfil.style.display=="")
	{
		setTimeout("document.getElementById('li_perfil').className = 'borde';",135);
	}
	else {
		li_perfil.className = 'li_perfil sub';
	}
	
}

function liniers(fecha,url){

	var Resultado;
		Resultado = document.getElementById('resultados');
		ajax=objetoAjax();
		ajax.open("GET", url+"?fecha="+fecha,true);
		ajax.onreadystatechange=function() {
	
			if (ajax.readyState!=4)
			{
				Resultado.innerHTML = '<div class="loading"><img src="imagenes/ajax-loader.gif" /><br />Generando listado, Aguarde por favor..</div>';
			}
			if (ajax.readyState==4) 
			{					
				Resultado.innerHTML = ajax.responseText;	
			}
			
		}	
		ajax.send(null);
}

function datos_clima(icao){
    var Resultado;
        Resultado = document.getElementById('datos_clima');
        ajax=objetoAjax();
        ajax.open("GET", "datos_clima.php?icao="+icao,true);
        ajax.onreadystatechange=function() {
   
            if (ajax.readyState!=4)
            {
                Resultado.innerHTML = '<img src="imagenes/ajax-loader.gif">';
            }
            if (ajax.readyState==4)
            {                   
                    Resultado.innerHTML = ajax.responseText;   
            }
           
        }   
        ajax.send(null);   
}

function poner_decimales(numero) 
{ 
if(numero.indexOf(".")==-1)  {numero += ".00"} else { 
   if(numero.indexOf(".") == numero.length - 2) {numero += "0"} 
} 
return numero; 
}

function modificar_input_selector(tipo_var) {
	if (tipo_var==null) {tipo_var = 0.05;}
	if (document.getElementsByTagName) {
		// Obtengo los elementos INPUT
		var objs = document.getElementsByTagName("INPUT");
		
		// Los modifico para incluir el selector a los que tenga el atributo rel = "selector"
		for (var i=0; i<objs.length; i++) {
			if (objs[i].getAttribute("rel") != null && 
				objs[i].getAttribute("rel").toLowerCase().match(/^selector(\[\-?\s*\d+\s*,\s*\-?\s*\d+\])?$/) &&
			    objs[i].type.toLowerCase() == "text") {
				// Creamos id si no lo tiene
				if (!objs[i].id) {
					objs[i].id = Math.random();
				}
				// Hayamos el m�ximo y el m�nimo
				var params = objs[i].getAttribute("rel").replace(/(^selector\[)|(\]$)/g, "").split(",");
				var min = parseFloat(params[0]);
				var max = parseFloat(params[1]);
				if (max<min) {
					max = min;
				}
				objs[i].max = max;
				objs[i].min = min;
			
				// Empezamos con la barra
				// Lo incluimos dentro de una capa
				var contenedor = document.createElement("SPAN");
				contenedor.className = "contenedor-controles-input-selector";

				// Se a�ade el contenedor antes de la barra
				objs[i].parentNode.insertBefore( contenedor,objs[i]);
				
				// Aumentar
				// Se crea el enlace
				var a = document.createElement("A");
				a.id = objs[i].id+"_AUMENTAR";
                               
				a.style.cursor='pointer';
				// Se le a�aden atributos para luego poder hacer referencia
				a.cajaTexto = objs[i];
				a.max = max;
				a.min = min;
				// No se usa click por si se quiere que vaya 
				// cambiando mientras se tiene pulsado el boton del raton
				a.onmousedown = function() {
					// Si es numero
					if (!isNaN(parseFloat(this.cajaTexto.value))) {
						// Si es mas peque�o que el valor m�ximo
						if (parseFloat(this.cajaTexto.value) < this.max) {
							// Si es menor que el valor minimo se pone este
							if (parseFloat(this.cajaTexto.value) < this.min) {
								this.cajaTexto.value = this.min;
							} else {
								// Se incrementa el valor en 1
								this.cajaTexto.value = parseFloat(this.cajaTexto.value)+parseFloat(tipo_var);
								var result=Math.round(this.cajaTexto.value*100)/100; 
								this.cajaTexto.value = parseFloat(result,2);
								if (tipo_var==0.05 || tipo_var==0.10) {this.cajaTexto.value = poner_decimales(this.cajaTexto.value);}
							}
						} else {
							// Se pone el valor m�ximo si es mayor que este
							this.cajaTexto.value = this.max;
						}
					} else {
						// Si no es numerico se pone el valor minimo
						this.cajaTexto.value = this.min;
					}
					// Se repite el evento mientras se tenga pulsado el raton
					this.idEvento = setTimeout('document.getElementById("'+this.id+'").onmousedown()', 175); // <- velocidad
				};
				// Se deja de repetir el evento al soltar el boton del raton
				a.onmouseup = a.onmouseout = function() {
					clearTimeout(this.idEvento);
				}
				// Las flechas usan una imagen transparente para 
				// poder usar un background y hacer el efecto hover 
				// usando una �nica im�gen
				a.innerHTML = '<img src="imagenes/botones/sp.gif" alt="Aumentar" title="Aumentar" />';
				a.className="aumentar-input-selector";
				// Incluyo la imagen despues de la caja de texto
				objs[i].parentNode.insertBefore(a, objs[i].nextSibling);
				//insertBefore insertAfter
				// Me quedo con este objeto para luego
				// incluir a continuaci�n de este la otra flecha
				var a_aumentar = a;
				
				// Disminuir
				// Se crea el enlace
				a = document.createElement("A");
				a.id = objs[i].id+"_DISMINUIR";
				a.style.cursor='pointer';
				// Se le a�aden atributos para luego poder hacer referencia
				a.cajaTexto = objs[i];
				a.max = max;
				a.min = min;
				// No se usa click por si se quiere que vaya 
				// cambiando mientras se tiene pulsado el boton del raton
				a.onmousedown = function(evt) {
					// Si es numero
					if (!isNaN(parseFloat(this.cajaTexto.value))) {
						// Si es mas peque�o que el valor m�ximo
						if (parseFloat(this.cajaTexto.value) > this.min) {
							// Si es menor que el valor minimo se pone este
							if (parseFloat(this.cajaTexto.value) > this.max) {
								this.cajaTexto.value = this.max;
							} else {
								// Se reduce el valor en 1
								this.cajaTexto.value = parseFloat(this.cajaTexto.value)-parseFloat(tipo_var);
								var result=Math.round(this.cajaTexto.value*100)/100; 
								this.cajaTexto.value = parseFloat(result,2);
								if (this.cajaTexto.value < 0) {this.cajaTexto.value = 0;}
								if (tipo_var==0.05 || tipo_var==0.10) {this.cajaTexto.value = poner_decimales(this.cajaTexto.value);}
							}
						} else {
							// Se pone el valor m�ximo si es mayor que este
							this.cajaTexto.value = this.min;
						}
					} else {
						// Si no es numerico se pone el valor minimo
						this.cajaTexto.value = this.min;
					}
					// Se repite el evento mientras se tenga pulsado el raton
					this.idEvento = setTimeout('document.getElementById("'+this.id+'").onmousedown()', 175); // <- velocidad
				};
				// Se deja de repetir el evento al soltar el boton del raton
					a.onmouseup = a.onmouseout = function() {
					clearTimeout(this.idEvento);
				}
				// Las flechas usan una imagen transparente para 
				// poder usar un background y hacer el efecto hover 
				// usando una �nica im�gen
				a.innerHTML = '<img src="imagenes/botones/sp.gif" alt="Disminuir" title="Disminur" />';
				a.className="disminuir-input-selector";
				// Incluyo la imagen despues de la primera flecha
				objs[i].parentNode.insertBefore(a, a_aumentar.nextSibling);
			}
		}
	}
}

// solo numeros y punto - llamar onkeypress="return onlyNumbers(event)"
function soloNum(e)
{
	var k;
	if(window.event) {k = e.keyCode} else if(e.which) {k = e.which}
	return !(k > 31 && (k < 48 || k > 57) && (k != 46));
}

var i = 0;
function fadecab(fade) {
	var img = $$('#animacion img');
	if(fade==null) {fade = 1.5;}	
	new Effect.Fade(img[i], {duration: fade});	
	i++;if(i==img.length) {i = 0;}	
	new Effect.Appear(img[i], {duration: fade});
}

function anim(time,fade) {
	t = time * 1000;
	fadecab(fade);setInterval('fadecab('+fade+')',t);
}

function ver_oferta(oferta_id, lote, cerrar)
{
	if(cerrar) {cerrar = '&cerrar'} else {cerrar = '';}

	Shadowbox.open
	({
        content:    'fragmentos/ver_oferta.php?oferta=' + oferta_id + '&revisacion=' + lote + cerrar,
        player:     "iframe",
        width:      445
    });
}

function farafafa(){
	alert("Funcion en java2");
}

function ver_oferta_directo(oferta_id, directoo, cerrar)
{
	if(cerrar) {cerrar = '&cerrar'} else {cerrar = '';}

	Shadowbox.open
	({
        content:    'fragmentos/ver_oferta.php?oferta=' + oferta_id + '&directo=' + directoo + cerrar,
        player:     "iframe",
        width:      445
    });
}


function ofertar(lote, precio)
{
	Shadowbox.open
	({
        content:    'form_ofertar.php?precio=' + precio + '&revisacion=' + lote,
        player:     "iframe",
        height:     432,
        width:      445
    });
	
}

function login_ofertar(lote, precio)
{
	parent.Shadowbox.open
	({
		content:    'login_oferta.php?precio=' + precio + '&revisacion=' + lote,
		player:     'iframe',
		height:     385,
		width:      710
	 });
}

function cerrar_shadow_refresh()
{
//	location.reload(false);
	window.location=window.location;
	Shadowbox.close();
}

function comp(id_form)
{	
	this.id = id_form;
	var cont, campos_en_formulario, textarea_en_formulario, selects_en_formulario, adv, remarcar;
	var errores = focusear = 0;
	formulario = document.getElementById(this.id);

	if(document.getElementById("advert")) {
		adv = document.getElementById("advert");
		if(adv.style.display == "none") {remarcar = 1;} else {remarcar = 0;}
	}
	if(getElementsByClassName('adv',formulario)[0]) {
		adv = getElementsByClassName('adv',formulario)[0];
		if(adv.style.display == "none") {remarcar = 1;} else {remarcar = 0;}
	}

	if(err==1 && id_form!='log') {return false;}

	if(id_form == "log" || id_form == "nl") {remarcar = 2;}

	formulario.onkeyup = function() {if(adv) {if(adv.style.display != "none") {comp(id_form);}}}

	if(getElementsByClassName('inputfecha',formulario)[0]) {getElementsByClassName('inputfecha',formulario)[0].onchange = function() {comp(id_form);}}

	selects_en_formulario = formulario.getElementsByTagName("select");
	for(cont = 0; cont < selects_en_formulario.length; cont ++)
	{
		if(selects_en_formulario[cont].getAttribute('onchange')!=null)
		{
			onch = selects_en_formulario[cont].getAttribute('onchange');
			selects_en_formulario[cont].setAttribute('onchange',onch+'; comp(\''+id_form+'\');');
		}
		else
		{
			selects_en_formulario[cont].onchange = function() {if(adv.style.display != "none") {comp(id_form);}}
		}
			
		RegExpNormal = /_I$/i;
		if (RegExpNormal.test(selects_en_formulario[cont].id))
		{
			nombreclass = selects_en_formulario[cont].className.replace(" error_input", "");
			if (selects_en_formulario[cont].selectedIndex == 0 && selects_en_formulario[cont].style.display != "none")
			{
				if(remarcar==1) {new Effect.Highlight(selects_en_formulario[cont], {startcolor: '#F8E0E0', endcolor: '#ffffff'} )}
				selects_en_formulario[cont].className = nombreclass + " error_input";
				errores++;
			}
			else
			{				
				selects_en_formulario[cont].className = nombreclass;
			}
		}
	}	

	textarea_en_formulario = formulario.getElementsByTagName("textarea");
	for(cont = 0; cont < textarea_en_formulario.length; cont ++)
	{
		
		RegExpNormal = /_I$/i;
		if (RegExpNormal.test(textarea_en_formulario[cont].id))
		{
			nombreclass = textarea_en_formulario[cont].className.replace(" error_input", "");
			if (textarea_en_formulario[cont].value.length < 3 && textarea_en_formulario[cont].style.display != "none")
			{
				if(remarcar==1) {new Effect.Highlight(textarea_en_formulario[cont], {startcolor: '#F8E0E0', endcolor: '#ffffff'} )}
				textarea_en_formulario[cont].className = nombreclass + " error_input";
				errores++;
			}
			else
			{
				textarea_en_formulario[cont].className = nombreclass;
			}
		}
	}	
		
	campos_en_formulario = formulario.getElementsByTagName("input");
	for(cont = 0; cont < campos_en_formulario.length; cont ++)
	{
		RegExpNormal = /_N$/i;
		if (RegExpNormal.test(campos_en_formulario[cont].id))
		{
			nombreclass = campos_en_formulario[cont].className.replace(" error_input", "");
			if(!IsNumeric(campos_en_formulario[cont].value) || campos_en_formulario[cont].value.length < 1)
			{
				if(remarcar==1) {new Effect.Highlight(campos_en_formulario[cont], {startcolor: '#F8E0E0', endcolor: '#ffffff'} )}
				campos_en_formulario[cont].className = nombreclass + " error_input";
				errores++;
			}
			else
			{
				campos_en_formulario[cont].className = nombreclass;
			}
		}
		
		RegExpNormal = /_I$/i;
		if (RegExpNormal.test(campos_en_formulario[cont].id))
		{
			nombreclass = campos_en_formulario[cont].className.replace(" error_input", "");
			if((campos_en_formulario[cont].value.length < 3 && campos_en_formulario[cont].style.display != "none") ||
				campos_en_formulario[cont].value == '************' || campos_en_formulario[cont].value == 'Ingrese su clave..')
			{
				if(remarcar==1) {new Effect.Highlight(campos_en_formulario[cont], {startcolor: '#F8E0E0', endcolor: '#ffffff'} )}
				campos_en_formulario[cont].className = nombreclass + " error_input";
				errores++;
			}
			else
			{				
				campos_en_formulario[cont].className = nombreclass;
			}			
		}		
		
		RegExpNormal = /_P$/i;
		if (RegExpNormal.test(campos_en_formulario[cont].id))
		{
			nombreclass = campos_en_formulario[cont].className.replace(" error_input", "");
			if((campos_en_formulario[cont].value.length < 1 && campos_en_formulario[cont].style.display != "none"))
			{
				if(remarcar==1) {new Effect.Highlight(campos_en_formulario[cont], {startcolor: '#F8E0E0', endcolor: '#ffffff'} )}
				campos_en_formulario[cont].className = nombreclass + " error_input";
				errores++;
			}
			else
			{				
				campos_en_formulario[cont].className = nombreclass;
			}			
		}
		
		RegExpNormal = /_PW$/i;
		if (RegExpNormal.test(campos_en_formulario[cont].id))
		{
			nombreclass = campos_en_formulario[cont].className.replace(" error_input", "");
			if((campos_en_formulario[cont].value.length < 6 && campos_en_formulario[cont].style.display != "none"))
			{
				if(remarcar==1) {new Effect.Highlight(campos_en_formulario[cont], {startcolor: '#F8E0E0', endcolor: '#ffffff'} )}
				campos_en_formulario[cont].className = nombreclass + " error_input";
				errores++;
			}
			else
			{				
				campos_en_formulario[cont].className = nombreclass;
			}			
		}

		RegExpMail = /_M$/i;
		if (RegExpMail.test(campos_en_formulario[cont].id))
		{
			nombreclass = campos_en_formulario[cont].className.replace(" error_input", "");
			if ((!comp_mail(campos_en_formulario[cont].value) || campos_en_formulario[cont].value == 'Ingrese su e-mail') && campos_en_formulario[cont].style.display != "none")
			{
				if(remarcar==1) {new Effect.Highlight(campos_en_formulario[cont], {startcolor: '#F8E0E0', endcolor: '#ffffff'} )}
				campos_en_formulario[cont].className = nombreclass + " error_input";
				errores++;
			}
			else
			{
				campos_en_formulario[cont].className = nombreclass;
			}
		}
				
		RegExpMail = /_MV$/i;
		if (RegExpMail.test(campos_en_formulario[cont].id))
		{
			nombreclass = campos_en_formulario[cont].className.replace(" error_input", "");
			if (campos_en_formulario[cont].value != "" && (!comp_mail(campos_en_formulario[cont].value) || campos_en_formulario[cont].value == 'Ingrese su e-mail' ))
			{
				if(remarcar==1) {new Effect.Highlight(campos_en_formulario[cont], {startcolor: '#F8E0E0', endcolor: '#ffffff'} )}
				campos_en_formulario[cont].className = nombreclass + " error_input";
				errores++;
			}
			else
			{				
				campos_en_formulario[cont].className = nombreclass;
			}
		}
	}
	
	if(id_form == "log" || adv==null) {
		if(errores != 0) {return false;}
	}
	else
	{			
		if(errores == 0)
		{
			adv.style.display = "none";
			if(document.getElementById("ocultar_si_error")) {document.getElementById("ocultar_si_error").style.display = '';}
			if(document.getElementById("load") && remarcar==1) {document.getElementById("load").style.display = '';}
			if(document.getElementById("loading") && remarcar==1) {document.getElementById("loading").style.display = '';}
			err2=0;
			return true;
		}
		else
		{
		//	adv.innerHTML = "Por favor revise los campos en rojo.";
			if(document.getElementById("ocultar_si_error")) {document.getElementById("ocultar_si_error").style.display = 'none';}
			if(remarcar==1) {Effect.Appear(adv, {duration: 0.30} );} else {adv.style.display = "";}

			for(cont = 0; cont < formulario.length; cont ++)
			{				
				errclass = /error_input/;
				if(errclass.test(formulario.elements[cont].className) && focusear==0 && remarcar==1) {formulario.elements[cont].focus();focusear++;}
			}
			err2=1;
			return false;
		}
	}
}

function ejem_login(t) {

	var div = document.getElementById('ingrese_pass');

	div.style.display = 'none';

	t.onblur=function() {
		if(t.value=='') {
			div.style.display = '';
		}
	}
}

function ejem(input,texto,si) {
	
	if(texto) {		
		if(input.value==texto){
			input.className = input.className.replace("ejemplo", "");
			if(input.value=='Ingrese su clave..') {input.type="password";}
			input.value='';
		}
	}
	
	if(si==1) {
		input.onblur=function() {
			if(input.value=='' && err2==0 && err==0) {
				input.value=texto;
				if(texto=='Ingrese su clave..') {input.type="text";}
				input.className='ejemplo';
			}
		}
	}
}

function ajax_guardar_sociedad(cliente, sociedad)
{
	var Resultado;
	Resultado = document.getElementById("sociedad_editable");
	
	var razon_social = document.getElementById("razon_social").value;
	var cuit = document.getElementById("cuit").value;
	var direccion = document.getElementById("direccion").value;
	var codigo_postal = document.getElementById("codigo_postal").value;
	var provincia = document.getElementById("provincia_I").value;
	var partido = document.getElementById("partido_I").value;
	var telefono = document.getElementById("telefono").value;
	var condicion_iva = document.getElementById("condicion_iva").value;
	var nro_ingresos_brutos = document.getElementById("nro_ingresos_brutos").value;

	var cadenaFormulario = "razon_social=" + razon_social + "&cuit=" + cuit + "&direccion=" + direccion + "&codigo_postal=" + codigo_postal + "&provincia=" + provincia + "&partido=" +partido + "&telefono=" + telefono + "&condicion_iva=" + condicion_iva + "&nro_ingresos_brutos=" +nro_ingresos_brutos;

	ajax=objetoAjax();
	ajax.open("POST", 'fragmentos/usuario/guardar_cambios_sociedad.php?cliente='+cliente+'&sociedad='+sociedad, true);
	ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
	ajax.onreadystatechange=function()
	{
		if (ajax.readyState==4) 
		{
			if(ajax.responseText != "")
			{
				Resultado.innerHTML = ajax.responseText;
			}
			else
			{							
				Resultado.innerHTML = "<h5>No hay respuesta</h5>";
			}
		}
	}
	ajax.send(cadenaFormulario);
}

function ajax_cancelar_edicion_sociedad(cliente, sociedad)
{	
	var Resultado;
	Resultado = document.getElementById("sociedad_editable");

	ajax=objetoAjax();
	ajax.open("GET", 'fragmentos/usuario/guardar_cambios_sociedad.php?cliente='+cliente+'&sociedad='+sociedad+'&cancel=1', true);
	ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
	ajax.onreadystatechange=function()
	{
		if (ajax.readyState==4) 
		{
			if(ajax.responseText != "")
			{
				Resultado.innerHTML = ajax.responseText;
			}
			else
			{							
				Resultado.innerHTML = "<h5>No hay respuesta</h5>";
			}
		}
	}
	ajax.send(null);
}
function convertir_usuario(t) {
	t.parentNode.style.display='none';
	document.getElementById('maill_M').style.display='';
	document.getElementById('maill_M').focus();
}
function ajax_editar_cliente_admin(id)
{
	var Resultado;
		Resultado = document.getElementById("cliente_editable");
	var cadena = "fragmentos/usuario/editar_cliente_admin.php?cliente=" +id;
	ajax=objetoAjax();
	ajax.open("GET", cadena,true);
	ajax.onreadystatechange = function()
	{
		if (ajax.readyState == 4)
		{
				Resultado.innerHTML = ajax.responseText;
		}
	}
	ajax.send(null);
	return;
}

function ajax_cancelar_edicion_usuario(cliente)
{
	var Resultado;
	Resultado = document.getElementById("cliente_editable");

	ajax=objetoAjax();
	ajax.open("GET", 'fragmentos/usuario/guardar_cambios_cliente.php?cliente='+cliente+'&cancel=1', true);
	ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
	ajax.onreadystatechange=function()
	{
		if (ajax.readyState==4) 
		{
			if(ajax.responseText != "")
			{
				Resultado.innerHTML = ajax.responseText;
			}
			else
			{							
				Resultado.innerHTML = "<h5>No hay respuesta</h5>";
			}
		}
	}
	ajax.send(null);
	if(document.getElementById('advert')) {document.getElementById('advert').style.display = "none";}
}

function ajax_guardar_cliente(cliente)
{
	var Resultado;
	Resultado = document.getElementById("cliente_editable");
	
	var nombre = document.getElementById("nombre").value;
	var apellido = document.getElementById("apellido").value;
	var telefono = document.getElementById("telefono").value;
	var perfil = document.getElementById("perfil").value;
	var maill = document.getElementById("maill_M").value;

	var cadenaFormulario = "nombre=" + nombre + "&apellido=" + apellido + "&telefono=" + telefono + "&perfil=" + perfil + "&maill=" + maill;
	
	if(document.getElementById("mailh")) {var mailh = document.getElementById("mailh").value;cadenaFormulario += "&mailh=" + mailh;}

	ajax=objetoAjax();
	ajax.open("POST", 'fragmentos/usuario/guardar_cambios_cliente.php?cliente='+cliente, true);
	ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
	ajax.onreadystatechange=function()
	{
		if (ajax.readyState==4) 
		{
			if(ajax.responseText != "")
			{
				Resultado.innerHTML = ajax.responseText;
			}
			else
			{							
				Resultado.innerHTML = "<h5>No hay respuesta</h5>";
			}
		}
	}
	ajax.send(cadenaFormulario);
}

function ajax_editar_sociedad_admin(id)
{
	var Resultado;
		Resultado = document.getElementById("sociedad_editable");
	var cadena = "fragmentos/usuario/editar_sociedad_admin.php?cliente=" +id;
	ajax=objetoAjax();
	ajax.open("GET", cadena,true);
	ajax.onreadystatechange = function()
	{
		if (ajax.readyState == 4)
		{
				Resultado.innerHTML = ajax.responseText;								
		}
	}
	ajax.send(null);
	return;
}

function mic(v)
{
	new Effect.toggle('floto', 'appear', {duration: 0.2});
/*
	if(v==1)
	{
		new Effect.Appear('floto', { duration: 0.1 });
	}
	else
	{
		new Effect.Fade('floto', { duration: 0.1 });	
	}

/*
	if($('floto').style.display=="none")
	{
		new Effect.toggle('floto', 'appear', { duration: 0.2 });
		new Effect.Opacity('floto', { from: 0, to: 0.92, duration: 0.3 });
		new Draggable('floto',{ handle: 'box1' });
	}
	else
	{
		new Effect.Opacity('floto', { from: 0.92, to: 0, duration: 0.3 });
		setTimeout("$('floto').style.display = 'none';", 400);
	}
*/
}
function trimText(string, largo)
 {
   largo = largo-3;
   var newst = string.split(" ");
   var contador = 0;
   var finalstr = '';
 
   for(var lar=0; lar<newst.length; ++lar) {
    if(contador >= largo)
      break;
    else
     {
      contador += newst[lar].length;
      finalstr += newst[lar]+' ';
      if(finalstr.length-1 > largo)
       {
        finalstr = finalstr.substr(0, finalstr.indexOf(newst[lar], 0));
        break;
       }
     }
   }
  return (finalstr != string) ?
         finalstr.substr(0, finalstr.length-1)+'..' :
         finalstr;
 }
