$(document).ready(
 	function(){
		if (document.all&&document.getElementById) {
			navRoot = document.getElementById("nav");
			for (i=0; i<navRoot.childNodes.length; i++) {
				node = navRoot.childNodes[i];
				if (node.nodeName=="LI") {
					node.onmouseover=function() {
					this.className+=" over";
					}
					node.onmouseout=function() {
					this.className=this.className.replace(" over", "");
					}
				}
			}
		}
 		
 		
	 		try{
	 			reconstruirCategorias();
	 		}catch(e){}
	 		
	 		$("#AgregarComentario").click(function(){
				if ($("#AddComentario").val() != ""){
					if ($("#iduser").val() != ""){
						AgregarComentario($("#AddComentario").val(),$("#idusuarioLog").val(),$("#idaviso").val());
					}else{
						alert('Por favor Ingrese con un usuario valido para poder enviar un mensaje');
					}
				}else{
					alert('Complete el campo de comentarios para poder ingresar el mismo');
				}
			});
	 		/*
	 		$("input[type=file]").filestyle({ 
	 		    image: "/images/bt_archivo.jpg",
	 		    imageheight : 22,
	 		    imagewidth : 70,
	 		    width : 320
	 		});*/
 			// Arranco con un banner yt despues pongo los demas
			$.get('/avisos/avisosdestacados',{pagina:$("#avisosND").val()}, function(data){
				$("#contenedor_avisos").html(data);
				$("#avisosND").val($("#avisosND").val() +1);
			});
			$.get('/avisos/serviciosdestacados',{pagina:$("#avisosNS").val()}, function(data){
				$("#contenedor_servicios").html(data);
				$("#avisosNS").val(parseInt($("#avisosNS").val()) +1);
			});
			setTimeout("moverWhite('avisosD','contenedor_avisos','avisosND','/avisos/avisosdestacados')",14000);
			setTimeout("moverWhite('avisosS','contenedor_servicios','avisosNS','/avisos/serviciosdestacados')",9000);
			// saco por ahora el intercambio de publicidad para ponder los banner de errores y demas
			//setTimeout("moverWhite('cpublicidadS','center_publicidadFlag','cpublicidadNS','/publicidad/center')",3000);
			//agrega un comentario
			
			// avisos destacados
			$("#pararD").click(function (){
					pararbaner('avisosD');
			});
			$("#anteriorD").click(function (){
				irbaner('-1','avisosD');
			});
			$("#siguienteD").click(function (){
				irbaner('1','avisosD');
			});
			
			// servicios destacados
			
			$("#pararS").click(function (){
				pararbaner('avisosS');
			});

			
			$("#anteriorS").click(function (){
				irbaner('-1','avisosS');
			});
			$("#siguienteS").click(function (){
				irbaner('1','avisosS');
			});
			$("#IrBuscar").click(function (){
				if ($("#inputBuscar").val()=='Ingrese lo que desea buscar...' || $("#inputBuscar").val()==''){
					alert('Por favor complete lo que desea buscar');
				}else{
					document.location.href="/busqueda/index/tipo/basica/buscar/" + $("#inputBuscar").val();	
				}
				
			});
			$("#logo").click(function (){
				document.location.href="/";
			});
			
			$(".btn-slide").click(function(){
				  if ($('#refinarB').val() == ""){
					  $('#principal2').css('margin-top','-400px');
					  setTimeout("$('#contenedor_aviso').slideToggle('slow');",1000);
					  setTimeout("$(this).toggleClass('active');",1000);
					  setTimeout("$('#refinarB').val('change');",1000);
				  }else{
					  setTimeout("$('#principal2').css('margin-top','-550px');",1000);
					  $("#contenedor_aviso").slideToggle("slow");
					  $(this).toggleClass("active");
					  $('#refinarB').val("");
				  }
			});

			if ($('#publicado').val()=='confirmado' && $('#tipoAviso').val()!='modificacion'){
				tb_show("Test",null,"../images/confirmacion_aviso_popup_ES.png?&height=480&width=640");
			}
			
			

	}
 	
);

function checkFiltros(){
		var precioDesde = parseInt($('#PrecioDesde :selected').text());
		var PrecioHasta = parseInt($('#PrecioHasta :selected').text());
		if (precioDesde != "" && PrecioHasta != ""){
			if (precioDesde > PrecioHasta){
				alert('El precio "desde" no debe ser mayor al precio "hasta"');
				return false;
			}else{
				document.busquedaRefinada.submit();
			}
		}else{
			document.busquedaRefinada.submit();
		}
		
}

/********************************************************************
*
*		Funcion de llamado HTTPRequest
*
*********************************************************************/
function setTraduccion(popupName,TextTT){
	
	var width = '300';
	var height = '300';
	var left ='20';
	var top ='20';
	var html = "";
	var newdiv = document.createElement('div');
   newdiv.setAttribute('id', 'traduccion');
   
   if (width) {
       newdiv.style.width = width;
   }
   
   if (height) {
       newdiv.style.height = height;
   }
   
   if ((left || top) || (left && top)) {
       newdiv.style.position = "absolute";
       
       if (left) {
           newdiv.style.left = left;
       }
       
       if (top) {
           newdiv.style.top = top;
       }
   }
  	ajax.open("GET", "/traducciones/view/text/" + TextTT + "/popupName/" + popupName, true);
	ajax.onreadystatechange = function (){
		 if (ajax.readyState == 4) {
				if (ajax.status == 200) {
						if (ajax.responseText) {
							
					       newdiv.innerHTML = ajax.responseText;
					       document.getElementById(popupName).appendChild(newdiv);
					   } else {
					       newdiv.innerHTML = "nothing";
					   }
					  
					}
				}
	};
	ajax.send(null);
   
   
   //document.body.appendChild(newdiv);

	
}

function modificarTraduccion(){
	var parametros = 	'?pt_BR=' + document.getElementById('Portugues').value.replace(/\n/g,'<br>')+
						'&Original=' + document.getElementById('Original').value.replace(/\n/g,'<br>')+ 
						'&en_US=' + document.getElementById('Ingles').value.replace(/\n/g,'<br>') +
						'&es_AR=' + document.getElementById('Espanol').value.replace(/\n/g,'<br>') +
						'&es_MX=' + document.getElementById('Mexico').value.replace(/\n/g,'<br>');

  	ajax.open("GET", "/traducciones/post/text//" + parametros, true);
	ajax.onreadystatechange = function (){
		 if (ajax.readyState == 4) {
				if (ajax.status == 200) {
						if (ajax.responseText) {
							if (ajax.responseText != ''){
								try{
									document.getElementById('trSin' + document.getElementById('Original').value.substring(0,4)).innerHTML =  ajax.responseText;
								}catch(e)
								{
									if (confirm('Esto es un campo dinamico, debemos actualizar la pagina para ver la modificacion, desea realizarlo ahora ??'))
									{
										top.location.reload();
										//document.location.href=document.getElementById('urlActual').value;
									}
								}
							}
					   } else {
						   alert('error');
					   }
					}
				}
	};
	ajax.send(parametros);
	
}
/********************************************************************************
 * 
 * 	Parametros de animaciones
 * 
 *******************************************************************************/
var TimeFade = 500;
var TimeCall = 8000;


/********************************************************************************
 * 
 * 	Funcion para manejar el ir o volver a un banner
 * 
 *******************************************************************************/
function pararbaner(aviso){
	$("#" + aviso).val('false');
	
}


/********************************************************************************
 * 
 * 	Funcion que se utiliza para frenar los banner que se encuentran corriendo en
 *  la Home
 * 
 *******************************************************************************/
function irbaner(npage,aviso){
	if (aviso == 'avisosD'){// necesito
			$("#" + aviso).val('false'); // siempre se abandona el carrusel
			var numberPage = $("#avisosND").val();
			$.get("/avisos/avisosdestacados",{pagina:numberPage}, function(data){
				$("#contenedor_avisos").html(data);//alert("Data Loaded: " + data);
			});
			numberPage = parseInt(numberPage) + parseInt(npage);
			if (numberPage < 1){numberPage = $('#nextPage').val();}
			else
			if (numberPage > $('#nextPage').val()){numberPage = 1;}
			$("#avisosND").val(parseInt(numberPage));
	}else{
		$("#" + aviso).val('false'); // siempre se abandona el carrusel
		var numberPage = $("#avisosNS").val();
		$.get("/avisos/serviciosdestacados",{pagina:numberPage}, function(data){
			$("#contenedor_servicios").html(data);//alert("Data Loaded: " + data);
			
		});
		numberPage = parseInt(numberPage) + parseInt(npage);
		if (numberPage < 1){numberPage = $('#nextPage2').val();}
		else
		if (numberPage > $('#nextPage2').val()){numberPage = 1;}
		$("#avisosNS").val(parseInt(numberPage));
	}
}
/********************************************************************************
 * 
 * 	Datos a pasar al mover
 *  SiMuevo -> id del input que controla si se mueve o no true - false
 *  contenedor -> id del contenedor a donde se colocaran los datos
 *  pageN -> contenedor donde se encuentran las cantidad de paginas
 *  url -> direccion de donde voy a realizar la llamada ajax ara obtener los datos
 * 
 *******************************************************************************/
function moverWhite(SiMuevo,contenedor,pageN,url){
	if($("#" + SiMuevo).val() == 'true'){
		$("#" + contenedor).fadeTo(TimeFade, 0);
		var numberPage = $("#" + pageN).val(); // numero de paginas
		$.get(url,{pagina:numberPage}, function(data){
			$("#" + contenedor).html(data);//alert("Data Loaded: " + data);
			moverBlack(SiMuevo,contenedor,pageN,url);
			if (url == '/avisos/avisosdestacados'){
				if ($('#nextPage').val() == numberPage){
					$("#" + pageN).val(1);
				}else{
					$("#" + pageN).val(parseInt($("#" + pageN).val()) + 1);
				}
			}else{
				if ($('#nextPage2').val() == numberPage){
					$("#" + pageN).val(1);
				}else{
					$("#" + pageN).val(parseInt($("#" + pageN).val()) + 1);
				}
			}
		});
		//setTimeout("moverBlack('" + SiMuevo + "','" + contenedor + "','" + pageN + "','" + url + "')",TimeCall);
		
	}else{
		moverBlack(SiMuevo,contenedor,pageN,url);
	}
}

function moverBlack(SiMuevo,contenedor,pageN,url){
	if($("#" + SiMuevo).val() == 'true'){
		$("#" + contenedor).fadeTo(TimeFade, 1);
		setTimeout("moverWhite('" + SiMuevo + "','" + contenedor + "','" + pageN + "','" + url + "')",TimeCall);
	}else{
		$("#" + contenedor).fadeTo(1, 1);
	}
}

/********************************************************************************
 * 
 * 	Se verifica las imagenes, se ponen en display inline la que viene por 1 parametro
 *  y el segundo parametro es la longitud de todas las imagenes a poner en display none
 * 
 *******************************************************************************/
function verImagen(imagenVer,CantidadImagenes){
	
	var ImgActual =$("#actualImagen").val();
	if (imagenVer == 'siguiente'){
		if (ImgActual < CantidadImagenes-1){
			imagenVer = parseInt($("#actualImagen").val()) + 1;
		}else{
			imagenVer = parseInt($("#actualImagen").val());
		}
		
	}else if (imagenVer == 'anterior'){
		if (ImgActual > 0){
			imagenVer = parseInt($("#actualImagen").val()) - 1;
		}else{
			imagenVer = parseInt($("#actualImagen").val());
		}
	}
	for (var i =0; i <= CantidadImagenes;i++){
		$("#" + i).hide();
	}
	$("#" + imagenVer).show();
	$("#actualImagen").val(imagenVer);
}

/********************************************************************************
 * 
 * 	Funcion que realiza toda la configuracion correspondiente al login del usuario
 * 
 *******************************************************************************/

function loginConfig(msg){
	 $('#nameUser').show();
	 $('#registerUser').hide();
	 
	 try{
			$("#yalogueoComentario").show();
			$("#logueoComentario").hide();
	}catch(E){}
	 $('#iduser').val(msg.split('/')[0]);
	 $("#userName").html(msg.split('/')[1]);
	 $("#imgLogin").attr("src", function() {
		 if (msg.split('/')[2] != ''){
			 return "/images/repository/usuario/" + msg.split('/')[2]; 
		 }
       });
	 $("#viewImgLogin").attr("href", function() {
		 if (msg.split('/')[2] != ''){
			 return "/images/repository/usuario/" + msg.split('/')[2]; 
		 }
       });
	 tb_remove();
	 if ($('#history').val() != ""){
		 document.location.href = $('#history').val();
		 $('#history').val("");
	 }else{
		 window.location.reload();
	 }
	 
}

/********************************************************************************
 * 
 * 	Funcion que realiza el logout del usuario
 * 
 *******************************************************************************/
function logout(){
	 $.ajax({
		   type: 'POST',
		   url: '/login/desconectar',
		   data: '',
		   success: function(msg){
		 				$('#loginform').hide();
		 				$('#iduser').val('');
		 				$("#userName").html('');
		 				try{
		 					$("#yalogueoComentario").hide();
		 					$("#logueoComentario").show();
		 					alert('Se ha desconectado satisfactoriamente de su cuenta en 4Sail.\n Muchas gracias por visitarnos,\n Equipo 4Sail. ');
		 					document.location.href='/';
		 				}catch(E){}
		   			}
		 });
}


function AgregarComentario(Comentario,idusuario,idaviso){
	$.ajax({
		   type: 'POST',
		   url: '/avisos/comentar',
		   data: 'comentario=' + Comentario + '&idusuario=' + idusuario + '&idaviso=' + idaviso,
		   success: function(msg){
						var navegador = navigator.appName;
						alert('Tu comentario se ingreso exitosamente');
						window.location.reload();
/* 
						$("#textoComentarios").fadeTo(2, 0);
						document.getElementById("textoComentarios").innerHTML = msg + $("#textoComentarios").html();
						$("#textoComentarios").fadeTo(2000, 1);
*/
		   			}
		 });
	
}

/********************************************************************************
 * 
 * 	Funcion que devuelve los filtros para los combos de busqueda refinada
 * 
 *******************************************************************************/
function buscarFiltros(combo){
	$("#combosFiltros").html("");
	switch(combo.value){
	 case '1-1':
	 case '1-12':
	 case '2-13':
	 case '2-6':
	 case '2-5':
	 case '2-4':
	 case '1-9':{
		$("#combosFiltros").attr('style','width:390px;');
		break;}
	 default:
		$("#combosFiltros").attr('style','width:250px;');
	 	break;
	 }
	$.ajax({
		   type: 'GET',
		   url: '/categoria/filtrobusqueda',
		   data: 'filtro=' + combo.value,		
		   success: function(msg){
					$("#combosFiltros").html(msg);
		   			}
		 });
}

/********************************************************************************
 * 
 * 	Funcion que devuelve los filtros para los combos la publicacion
 * 
 *******************************************************************************/
function buscarFiltrosPublicar(combo){
	var campoSelect ="";
	var selectCombos ="";
	var valorSeleccionado = "";
	var selectValue ="";
	var camposCategoria = $('#camposCategoria').val().split(',');
	
	var texto = "";
	$("#combosFiltros").html("");
	switch(combo.value){
	 case '1-1':
	 case '1-12':
	 case '2-13':
	 case '2-6':
	 case '2-5':
	 case '2-4':
	 case '1-9':{
		$("#combosFiltros").attr('style','margin-top:10px;width:500px;');
		break;}
	 default:
		$("#combosFiltros").attr('style','margin-top:10px;width:330px;');
	 	break;
	 }
	$("#tags_top").html('<span id="TipoNombreTag&quot;" name="TipoNombreTag&quot;">' + document.getElementById('Categoria').options[document.getElementById('Categoria').selectedIndex].text + '</span>');
	
	$.ajax({
		   type: 'POST',
		   url: '/categoria/filtro',
		   data: 'filtro=' + combo.value + '&ano=list',
		   success: function(msg){
				$("#combosFiltros").html(msg);
   			}
		 });
}


/**
 * Busqueda de Tags para poder poner en la busqueda refinada.
 */
function buscarTags(combo){
	$.ajax({
		   type: 'POST',
		   url: '/categoria/tags',
		   data: 'filtro=' + combo.value,
		   success: function(xmls){
					$("#tagNumber").html(xmls);
					}				
			}); 
}

/**
 * Busqueda de Tags para poder poner en la busqueda refinada.
 */
function buscarTagsPublicar(combo){
	var combos = "";
	$.ajax({
		   type: 'POST',
		   url: '/categoria/tagspublicar',
		   data: 'filtro=' + combo.value,

		   success: function(xml){
					var combo = "";
					$("#tags_center").html(xml);
					var arrayTags = $('#camposTag').val().split(',');
						for(var i=0; i < arrayTags.length;i++){
							$("option[value='" + arrayTags[i] + "']").attr("selected","selected");
						}
		   			}
		 });
		 
}


/**
 * Agrega otra imagen para realizar el upload de imagenes de 4sail
 */

function subirOtraImagen(){
	var numeroImg = $('#numeroImg').val();
	if(numeroImg < 5){
		$('#uploadImges').append('<input type="file" name="uploadImg' + numeroImg + '" id="uploadImg' + numeroImg + '"/><br><br>');
		
		$("#uploadImg" + numeroImg).filestyle({ 
			    image: "/images/bt_archivo.jpg",
			    imageheight : 22,
			    imagewidth : 70,
			    width : 320
			});
		$('#numeroImg').val(parseInt($('#numeroImg').val()) + 1);
	}else{
		alert('No es posible subir mas de 5 imagenes');
	}
}






function agregarFiltro(objSelect,TextoSelect,IdSelect){
	if(IdSelect.replace("í","i") == "Pais"){
		$.ajax({
			   type: 'POST',
			   url: '/categoria/filtro/tipo/ciudad/',
			   data: 'pais=' + objSelect.options[objSelect.selectedIndex].value,
			   success: function(xml){
								$("#skinnedSelectModelo").html(xml);
						}
			});
	}
}

/**
 * Funcion que intercambia los checkbox por medio de un hidden
 * Se pasan como obj la imagen y el hidden para vender y la imagen debe tener el mismo id + img
 */
function cambiarCheckBox(objImg,inputName){
	var imagen = "";
	if ($("#" + inputName).val() == '1'){
		$("#"  + inputName).val('0');
		imagen = "botonesAccion_24.gif";
	}else{
		$("#"  + inputName).val('1');
		imagen = "botonesAccion_26.gif";		
	}
	$("#" + inputName + 'img').attr("src","/images/4SailIMGS/images/" + imagen);
}

/**
 * Filtro de Tags
 */
function filtrarTag(idTag){
	$("#valueTag").val(idTag);
	$("#busquedaRefinada").submit();
}


/**
 * Para la publicacion de avisos, y verificacion de login
*/
function publicarAviso(){
	if ($("#iduser").val() != '')
	{
		document.location.href='/publicar/index';
	}else{
		$('#history').val('/publicar/index');
		tb_show('Login','/login/login/?KeepThis=true&TB_iframe=true&height=308&width=273',null);
		//alert('Debes estar logueado para poder publicar');
	}
}

function publicarNecesito(){
	if ($("#iduser").val() != '')
	{
		document.location.href='/necesito/index';
	}else{
		$('#history').val('/necesito/index');
		tb_show('Login','/login/login/?KeepThis=true&TB_iframe=true&height=308&width=273',null);
		//alert('Debes estar logueado para poder publicar una Necesidad');
	}
}

/**
 * Para la publicacion de avisos, y verificacion de login
*/
function verCuenta(){
	if ($("#iduser").val() != '')
	{
		document.location.href='/usuario/avisos';
	}else{
		$('#history').val('/usuario/avisos');
		tb_show('Login','/login/login/?KeepThis=true&TB_iframe=true&height=308&width=273',null);
		//alert('Debes estar logueado para poder ver su cuenta');
	}
}


/**
 * Funcion que regenera las categorias a modo de memoria
 */
function reconstruirCategorias(){
	//try{
	//alert("*" + document.getElementById('CategoriaCampo').value + "*");
	if (document.getElementById('CategoriaCampo').value != "-"){
		buscarFiltrosPublicar(document.getElementById('CategoriaCampo'));
		buscarTagsPublicar(document.getElementById('CategoriaCampo'));
	}
		//alert($('#camposCategoria').val());
	//}catch(e){
		
	//}
}

function BuscarCiudadModificar(idPais){
	objSelect = document.getElementById('Pais');
	//var camposCategoria = $('#camposCategoria').val().split(',');
	$.ajax({
		   type: 'POST',
		   url: '/categoria/filtro/tipo/ciudad/pais/',
		   data: 'pais=' + idPais,
		   success: function(xml){
							var combos = "";
							texto = "Ciudad";
							$(xml).find('NODO').each(function(){
								for(var ij = 0; ij < camposCategoria.length; ij++){
									if (camposCategoria[ij] == $(this).attr('value')){
										selectValue = camposCategoria[ij];
										texto = $(this).attr('texto');
										break;
									}
								}
							});
							$(xml).find('NODO').each(function(){
								$(this).find('options').each(function(){
									combos = combos + 	'<option value="' + $(this).attr('value') + '"  >' + $(this).attr('texto') + '</option>';
								});
							});
							$("#CIUDAD1").html(texto);
							$("#CIUDAD").html(combos);
					}
		});
	
	
}

/**
 * Eliminar Imagenes
 */
function eliminarThumb(imagen){
	$('#' + imagen).hide();
	$('#numeroImg').val($('#numeroImg').val() - 1);
	$.ajax({
		   type: 'POST',
		   url: '/Galeria/deshabilitar/',
		   data: 'imagen=' + imagen,
		   success: function(msg){
							
					}
		});
	
	
}

function  verificarPublicacion(){
	if ($('#uploadVdo').val() == ""){
		alert("Por favor complete el Titulo");
		return;
	}
	if($('#Precio').val() == ""){
		alert("Por favor complete el Precio");
		return;
	}
	if ($('#Categoria').val() == "0-0" || $('#Categoria').val() == ""){
		alert("Por favor seleccion� una categoria");
		return;
	}	
	if ($('#descripcionPublicar').val() == ""){
		alert("Por favor completa la descripci�n");
		return;
	}
	if(!($('#tagEtiquetas').val())){
		alert("Por favor seleccion� una etiqueta");
		return;
	}
	
	if ($('#tagEtiquetas').val() == "null" || $('#tagEtiquetas').val() == ""){
		alert("Por favor seleccion� una etiqueta");
		return;
	}
	document.publicarAviso.submit();
}
