// Selecciona todos los checkbox de una vez
function seleccionarTodo(idTabla){
   for (i=0;i<document.mostrarRegistros.elements.length;i++){
	  if(document.mostrarRegistros.elements[i].type == "checkbox"){
	    	var idCheck=document.mostrarRegistros.elements[i].id;
	    	//alert(idCheck +"*****"+document.mostrarRegistros.elements[i].className);
	  	if (document.mostrarRegistros.elements[i].className!=idCheck) {
			document.mostrarRegistros.elements[i].checked=1;
			var td = document.mostrarRegistros.elements[i].parentNode;
			var tr=td.parentNode;
			pintarFila(tr, '#ffffff', '#ffff94');
	}
   }

} 
}




// Deselecciona todos los checkbox de una vez
function deseleccionarTodo(idTabla){
for (i=0;i<document.mostrarRegistros.elements.length;i++){
      if(document.mostrarRegistros.elements[i].type == "checkbox"){
	    	var idCheck=document.mostrarRegistros.elements[i].id;
	    	//alert(idCheck +"*****"+document.mostrarRegistros.elements[i].className);
	  	if (document.mostrarRegistros.elements[i].className==idCheck) {
			//Manipulate this in whatever way you want
			var td = document.mostrarRegistros.elements[i].parentNode;
			var tr=td.parentNode;
			//pintarFila(tr, '#70e5e5', '#ffff94');
		}else{
			document.mostrarRegistros.elements[i].checked=0
			var td = document.mostrarRegistros.elements[i].parentNode;
			var tr=td.parentNode;
			pintarFila(tr, '#ffffff', '#ffff94');
		}
	}
}

} 

// Selecciona un checkbox haciendo click en cualquier lugar de la fila
function seleccionarFilaCheckbox(idCheckbox){
    if ( document.getElementById(idCheckbox) ) {
        document.getElementById(idCheckbox).checked = (document.getElementById(idCheckbox).checked ? false : true);
        if ( document.getElementById(idCheckbox + 'r') ) {
            document.getElementById(idCheckbox + 'r').checked = document.getElementById(idCheckbox).checked;
        }
    }
    else {
        if ( document.getElementById(idCheckbox + 'r') ) {
            document.getElementById(idCheckbox + 'r').checked = (document.getElementById(idCheckbox +'r').checked ? false : true);
            if ( document.getElementById(idCheckbox) ) {
                document.getElementById(idCheckbox).checked = document.getElementById(idCheckbox + 'r').checked;
            }
        }
    }
    marcarFilasPorClase(idCheckbox, document.getElementById(idCheckbox).checked);
}

//Create an array 
var allPageTags = new Array(); 

function marcarFilasPorClase(theClass, pintar) {
	//Populate the array with all the page tags
	var allPageTags=document.getElementsByTagName("input");
	//Cycle through the tags using a for loop
	for (i=0; i<allPageTags.length; i++) {
		//Pick out the tags with our class name
		if (allPageTags[i].className==theClass) {
			//Manipulate this in whatever way you want
			var td = allPageTags[i].parentNode;
			var tr=td.parentNode;
			pintarFila(tr, '#70e5e5', '#ffff94');
		}
	}
} 
function rgbAHex(cadenaRgb){
	var cadena = "0123456789abcdef";
	
	if ( cadenaRgb.substring(-1, 1) == "#" ){color = cadenaRgb;}
	
	if ( cadenaRgb.substring(-1, 3) == "rgb" ){		/* Si el color esta en formato rgb, lo paso a hexadecimal */
		
		vector = cadenaRgb.substring(4,(cadenaRgb.length-1)).split(", ");
		
		if ( vector.length == 1 ){vector = cadenaRgb.substring(4,(cadenaRgb.length-1)).split(",");}
		
		color = "#";
		
		var i;
		for(i=0; i<3; i++){
			bajo = vector[i] % 16;
			alto = (vector[i] - bajo) / 16;
			color += cadena.charAt(alto) + cadena.charAt(bajo);
		}
	}
return color;
}

// Selecciona una fila cambiando el color de esta al pasar sobre ella o al hacer click en ella
function seleccionFila(fila, accion){
// accion = 'over', 'out', 'click'

	var color = fila.style.backgroundColor;
	var colorDefecto = '#ffffff';
	var colorOver = '#ff6347';
	var colorSeleccion = '#ffff94';

	if ( color ){	/* Si el color esta en formato rgb, lo paso a hexadecimal */
		color = rgbAHex(color);
	}
	else {			/* Si el color es indefinido le asigno el color por defecto */
		fila.style.backgroundColor = colorDefecto;
		color = colorDefecto;
	}

	
// Accion de pasar el mouse sobre la fila
	if ( accion == 'over' ){

		if ( color == colorDefecto ){
			fila.style.backgroundColor = colorOver;
			color = colorOver;
		}
	}

// Accion de sacar el mouse de la fila
	if ( accion == 'out' ){

		if ( color == colorOver ){
			fila.style.backgroundColor = colorDefecto;
			color = colorDefecto;
		}
	}

// Accion de hacer click sobre la fila
	if ( accion == 'click' ){

		if ( color == colorOver ){fila.style.backgroundColor = colorSeleccion;}	/* Fila no seleccionada */
		if ( color == colorSeleccion ){fila.style.backgroundColor = colorOver;}	/* Fila ya seleccionada */
	}
}

function pintarFila(fila, color1, color2){
	var color = fila.style.backgroundColor;
	if ( color ){	/* Si el color esta en formato rgb, lo paso a hexadecimal */
		color = rgbAHex(color);
	}
	else {			/* Si el color es indefinido le asigno el color por defecto */
		fila.style.backgroundColor = color1;
		color = color1;
	}
	if ( color == color1 ){fila.style.backgroundColor = color2;}	/* Fila no seleccionada */
	if ( color == color2 ){fila.style.backgroundColor = color1;}	/* Fila ya seleccionada */
}

// habilita y deshabilita los input tipo "file"
function habilitarDesabilitar(check, file){
	var archivo = document.getElementById(file);
	var checkbox = document.getElementById(check);
	
	if(checkbox.checked){archivo.disabled=false;}
	else{archivo.disabled=true;}
}

function win(fileName) {
  myFloater = window.open('','myWindow','scrollbars=yes,status=no,width=530,height=550');
  myFloater.location.href = fileName;
}


//muestra la primer foto de un anuncios en la pagina del Anuncio
function mostrarFotoGrande(fotito, idAlfa){
	//document.getElementById("fotoGrande").alt='cargando...';
	idDiv = "fotoGrande-"+ idAlfa;
	//alert (idDiv);
	document.getElementById(idDiv).innerHTML='<img src='+fotito+' alt="cargando Imagen..."/>';
}

//prgunta por el banner, as� no muestra la foto grande en la moderacion
function fotoGrande(urlImagen, idAlfa){

   var banner = document.getElementById('cabeza')//si existe la cabeza, estamos mostrando un anuncio
   if (banner) {//se usaba para que no muestra la foto grande al moderar anuncios
   	   mostrarFotoGrande(urlImagen, idAlfa)
   }
}



function MM_findObj(n, d) { //v4.01
  var p,i,x;if(!d) d=document;if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document;n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n];for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n);return x;
}


function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  var email1='',email2='';

  for (i=0; i<(args.length-2); i+=3) {test=args[i+2];val=MM_findObj(args[i]);
	if(val.name=="emailPersona") email1=val.value;
	if(val.name=="confEmailPersona") email2=val.value;
	if(val.name=="pass"){
		var validaPass = true;
		 pass=val.value;
	}
	if(val.name=="passR") passR=val.value;
		//alert(test+'***'+test.indexOf('isEmail'));
    if (val) { 
    	if(args[i+1]!=""){//despues del name del input puede ir un nombre para el input
    		nm=args[i+1];
    	}else{
    		nm=val.name; 
    	}
    	if ((val=val.value)!="") {
	    		//alert(val+'***'+test.indexOf('isEmail'));
	      if (test.indexOf('isEmail')!=-1) {p=val.indexOf('@');
	      var objRE = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	      	//var objRE = /^[\w-\.\']{1,}\@([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,}$/;
			//alert(val+'***'+ !(objRE.test(val)));
	        if (!(objRE.test(val))) errors+='- '+nm+' debe ser una direccion de email.\n\n';
	      } else if (test!='R') {num = parseFloat(val);
	        if (isNaN(val)) errors+='- '+nm+' debe ser un numero.\n\n';
	        if (test.indexOf('inRange') != -1) {p=test.indexOf(':');
	          min=test.substring(8,p);max=test.substring(p+1);
	          if (num<min || max<num) errors+='- '+nm+' debe ser un numero entre '+min+' y '+max+'.\n\n';
	    }}
     } else if (test.charAt(0) == 'R') errors += '- '+nm+' debe ser ingresado.\n\n';}
  } 
  if(email1!=email2){errors += 'Email y Confirmar Email deben coincidir.\n\n';}
  if(validaPass){
  	    if(pass!=passR){errors += 'Las contrase\xF1as no coinciden.\n\n';}
  }

  
  if (errors) alert('Tiene los siguientes errores:\n\n'+errors);
  document.MM_returnValue = (errors == '');
}


function remove(theVar){
	var theParent = theVar.parentNode;
	theParent.removeChild(theVar);
}
function addEvent(obj, evType, fn){
	if(obj.addEventListener)//si es Mozilla
	    obj.addEventListener(evType, fn, true)
	if(obj.attachEvent)////si es Microsoft
	    obj.attachEvent("on"+evType, fn)
}
//agrega un evento
function removeEvent(obj, type, fn){
	if(obj.detachEvent){//si es Microsoft
		obj.detachEvent('on'+type, fn);
	}else{//si es Mozilla
		obj.removeEventListener(type, fn, false);
	}
}

function isWebKit(){
	return RegExp(" AppleWebKit/").test(navigator.userAgent);
}

function $m(theVar){
	return document.getElementById(theVar)
}


function subirImagen(inputFile, clave, imgSubiendo, limite, url)
{
	var detectWebKit = isWebKit();
	var copia = inputFile;
	var c=document.getElementById('imagenesSubidas');
	var cantImgSubidas=c.getElementsByTagName('img').length;
	//alert(cantImgSubidas +"***"+ limite);
	if(cantImgSubidas < limite){
		var form = document.createElement("form");
		with(form) {
		setAttribute("name", "formSubirImagen"); 
		setAttribute("id", "formSubirImagen");
		setAttribute("action", "");
		setAttribute("method", "post");
		setAttribute("enctype", "multipart/form-data");
		}
		form.appendChild(copia);
		var input = document.createElement("input");
		with(input) {
		setAttribute("name", "claveImg");
		setAttribute("type", "hidden");
		setAttribute("value", clave);
		}
		form.appendChild(input);
		
		document.getElementById('seleccionarImg').appendChild(form);

		
		
		var fName = 'f' + Math.floor(Math.random() * 99999);
		var dName = 'd' + Math.floor(Math.random() * 99999);
		var d = document.createElement("iframe");
		d.setAttribute("id",fName);
		d.setAttribute("name",fName);
		d.setAttribute("width","0");
		d.setAttribute("height","0");
		d.setAttribute("border","0");
		d.setAttribute("style","width: 0; height: 0; border: none;");
		var nuevaImagen = document.createElement('DIV');  // '," f35790="" )=""> Borrar </a>
		nuevaImagen.setAttribute("id",dName);
		nuevaImagen.setAttribute("name",dName);
		nuevaImagen.setAttribute("class","miniFoto");
		nuevaImagen.innerHTML = '<img src="'+imgSubiendo+'" /><strong> Subiendo ...</strong>';
		c.appendChild(nuevaImagen)
		form.parentNode.appendChild(d);
		window.frames[fName].name=fName;
		var iframe=document.getElementById(fName);
		var doUpload = function(){
			removeEvent(iframe,"load", doUpload);
			var cross = "javascript: ";
			cross += "window.parent.$m('"+dName+"').innerHTML = document.body.innerHTML; void(0);";
			iframe.src = cross;
			if(detectWebKit){
	        		remove(iframe);
	        	}else{
	        		setTimeout(function(){remove(iframe)}, 250);
	       	 }
		}
		addEvent(iframe,"load", doUpload);
		form.setAttribute('target', fName);
		//url="xaja-asecorp?action=subirImg";
		form.action=url;
		//document.body.appendChild(form); // aade el formulario al documento 
		//alert(form.action);
		form.submit();
		copia.value="";
		remove($m('formSubirImagen'));
		var divI=document.getElementById('seleccionarImg');
		divI.appendChild(copia);
		//document.myform.submit();
	}else{
		alert('Disculpe, no se permite subir m\u00e1s im\u00e1genes');
		copia.value="";
	}

}

//para borrar imagenes
function borrarImg(anchor, url){
	var divContainer = anchor.parentNode.id;
	//alert(anchor.parentNode.id);
	//var id=divContainer.id.value;
	//url="xaja-asecorp?action=borrarImg&file="+file;
	CargarPagina(url, divContainer);
	remove($m(divContainer));
	//var f=window.document.getElementById(name);
	//f.setAttribute('style', 'display:none');
}

function agregarImg(src){
	var form=window.parent.$m('altaAnuncio');
	var input = document.createElement("input"); // Crea un elemento input
	with(input) {
	setAttribute("name", "imagenes[]"); //nombre del input
	setAttribute("type", "hidden"); // tipo hidden
	setAttribute("value", src); // valor por defecto 
	}
	form.appendChild(input); // a�ade el input al formulario
}
//######################################
//####### funciones ajax
//######################################

function dispara_evento(url,id_contenedor){
	var contenedor = document.getElementById(id_contenedor);
	if(contenedor.innerHTML == "") {
		CargarPagina(url, id_contenedor);
	}
}

function cargarSelect(id_contenedor, url){
	var selectedId = eval(document.getElementById('rubro'));
	var selectValue = document.getElementById('rubro').options[selectedId.selectedIndex].value;

	//var urlConIdSelect="xaja-asecorp?action=cargarSelect&id="+selectValue;
	var urlConIdSelect=url+'&id='+selectValue;
	CargarPagina(urlConIdSelect, id_contenedor);
}

function cargarSelectLocalidad(id_contenedor, url, elementW, selectName){
	var selectedId = eval(elementW);
	var selectValue = elementW.options[selectedId.selectedIndex].value;
	//url="xaja-asecorp?action=cargarSelectLocalidad&id="+selectValue;
	var urlConIdSelect=url+'&id='+selectValue;
	if(selectName!=''){
		urlConIdSelect=urlConIdSelect+'&nameSelect='+selectName;
	}
	//alert(urlConIdSelect + '-' +id_contenedor);
	CargarPagina(urlConIdSelect, id_contenedor);
}


function CargarPagina(url, id_contenedor) { 
	var peticion=nuevoAjax();
	var div = document.getElementById(id_contenedor); 
	div.innerHTML = '<strong>Procesando... </strong>';
	peticion.open("get", url); 
	peticion.onreadystatechange = function() {
		if (peticion.readyState == 4) {
			//alert(peticion.responseText);
			div.innerHTML = peticion.responseText;
		}
	}
   peticion.send(null);
}

function nuevoAjax(){
	var xmlhttp=false;
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP","Msxml2.XMLHTTP.4.0","Msxml2.XMLH TTP.5.0","Msxml2.XMLHTTP.3.0");
	}catch (e) {
		try{
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} 
		catch (E){
			xmlhttp = false;
		}
	}
    
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		xmlhttp = new XMLHttpRequest();
	}
	return xmlhttp;
}

function autofitIframe(id_iframe){
document.getElementById(id_iframe).width = document.frames.id_iframe.document.body.offsetWidth + document.frames.id_iframe.document.body.scrollWidth;
document.getElementById(id_iframe).height = document.frames.id_iframe.document.body.offsetHeight + document.frames.id_iframe.document.body.scrollHeight;
}






	function tr(str, from, to) {
		for(var i = 0; i < from.length; i++) {
			str = str.replace(new RegExp(from.charAt(i),'g'), to.charAt(i));
		}
	return str;
	}

	function reemplazar(ingresado, item){
		var copiaIngresado=tr(ingresado,'ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ','AAAAAAaaaaaaOOOOOOooooooEEEEeeeeCcIIIIiiiiUUUUuuuuyNn').toLowerCase();
		var copiaItem=tr(item,'ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ','AAAAAAaaaaaaOOOOOOooooooEEEEeeeeCcIIIIiiiiUUUUuuuuyNn').toLowerCase();

		var offset=0;
		var pos=-1;

		while(copiaItem.indexOf(copiaIngresado, pos+1)!=-1){
				pos=copiaItem.indexOf(copiaIngresado, pos+1);
				if(true ){
						var palabra=item.substring(pos+offset,pos+offset+ingresado.length);
						var cabeza=item.substring(0,pos+offset);
						var cola=item.substring(pos+offset+ingresado.length,item.length)
						item=cabeza.concat('<strong>',palabra,'</strong>',cola);
						offset+=17;
				}
		}

		return item;
	}

	$(document).ready(function() {

			jQuery('.blka').click(function(e){
				window.open(jQuery(this).find('.cnt .t a').attr('href'));
				return false
			});
			jQuery('.ela').click(function(e){
				if (e.metaKey || e.which === 2) window.open(jQuery(this).find('a').attr('href'));
				else window.location = jQuery(this).find('a').attr('href');
				return false
			});
/*
			jQuery('.thumb img').each(function(){
				var h=jQuery(this).attr('height');
				
				var ctn=jQuery('.thumb').css('height');
				ctn = ctn.substr(0, 3);
				var sob=ctn-h;
				if(sob>0){
					var hal=sob/2;
				}else{
					hal=0;
				}
				jQuery(this).css({
					marginTop: hal+'px'
				});
			});
*/

	// define the initialValue() function
	  $.fn.initialValue = function(value) {
		if (value) {
		  return this.attr('data-initial-value', value);
		} else {
		  return this.attr('data-initial-value');
		}
	  };

	  $.fn.clearInput = function() {
		return this
		  .focus(function(){
			if (this.value == $(this).initialValue()) {
			  this.value = '';
			}
		  })
		  .blur(function(){
			if (this.value == '') {
			  this.value = $(this).initialValue();
			}
		  })
		  .each(function(index, elt) {
			$(this).initialValue(this.value);
		  });
	  };

		$(".locSearch").clearInput();
		$("input.locSearch").autocomplete({
			minLength: 3,
			source: "an-autocomplete-localidades.php",
			autoFocus: true,
			open: function(e,ui) {
						var acData = $(this).data('autocomplete');
						var termTemplate = '<strong>%s</strong>';

						acData
						.menu
						.element
						.find('a')
						.each(function() {
						var me = $(this);
						var ingresado = acData.term;
						var item = me.text();
						me.html(reemplazar(ingresado,item));
						//matched es la palabra escrita.
						//function (matched) retorna el lo escrito en negrita.
						});
						$('#opnd').val('1');
						
			},


		   select: function(event, ui) {
					$('#iLs').val(ui.item.id);
					$('#chn').val('1');


			},

			//create: function(event, ui) {}
			focus: function(event, ui) {
				if(ui.item.value=="No hay coincidencias"){
					return false;
				}
			},
			close: function(event, ui) {
				//alert('5555');
			}


		});
		$(".locSearchGo").clearInput();
		$("input.locSearchGo").autocomplete({
			minLength: 3,
			source: "an-autocomplete-localidades.php",
			open: function(e,ui) {
						var acData = $(this).data('autocomplete');
						var termTemplate = '<strong>%s</strong>';

						acData
						.menu
						.element
						.find('a')
						.each(function() {
						var me = $(this);
						var ingresado = acData.term;
						var item = me.text();
						me.html(reemplazar(ingresado,item));
						$('#lopnd').val('1');
						//matched es la palabra escrita.
						//function (matched) retorna el lo escrito en negrita.
						});
			},


		   select: function(event, ui) {
					$('#iLocSearch').val(ui.item.id);
					$('#lchn').val('1');
					$('#sLoc').submit();
					
				if(ui.item.value=="No hay coincidencias"){
					return false;
				}
			},

			//create: function(event, ui) {}
			focus: function(event, ui) {
				if(ui.item.value=="No hay coincidencias"){
					return false;
				}
			},


		});
	  });

