//-----------------------------------------
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

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_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function openLink(URI){
	win = window.open(URI,"secWin","");
	win.focus;
}		

//-----------------------------------------
function replaceSubstring(inputString, fromString, toString) {
   // Goes through the inputString and replaces every occurrence of fromString with toString
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring" function


//-----------------------------------------
function expandirMenu(id) {

	try {
		if(document.getElementById(id).style.display == "none") {
			document.getElementById(id).style.display = "";
		} else{
			document.getElementById(id).style.display = "none";
		}
	}
	catch(e){
		// alert(e);
	}
}
//-----------------------------------------
function buscar_productos(criterio, criterio_id)
{
	var f2 = document.formulario_buscar;
	f2.criterio.value = criterio;
	f2.criterio_id.value = criterio_id;	

	var str_filtros = "0@";
	try {
		str_filtros += f2.filtro_tipo_producto.value;
	} catch (e) {
		str_filtros += "0";
	}
	str_filtros += "@";
	try {
		str_filtros += f2.filtro_marca.value;
	} catch (e) {
		str_filtros += "0";
	}
	f2.filtros.value = str_filtros;
	
	if (criterio_id == "") {
		alert(TXT_ALERTS_INDICAR_TERMINO);
		return false;		
	} else {
		f2.submit();	
	}
}
//-----------------------------------------
function filtrar_productos()
{
	var f1 = document.formulario_filtrar;

  // Campos variables	
	var valores = new Array();
	
	// Radios
    var mytags  = document.getElementsByTagName("input");

    for (i=0;i<mytags.length;i++){
		var pos_valores=mytags[i].id.indexOf("alores_");
		if (pos_valores >= 0) {	
			eval("valor = getSelectedRadioValue(f1."+mytags[i].id+");");
			if ((valor > 0) && (valor != undefined)) {
				valores.push(valor);
			}
		}
   }

	// Combos
    var mytags  = document.getElementsByTagName("select");

    for (i=0;i<mytags.length;i++){
		var pos_valores=mytags[i].id.indexOf("alores_");
		if (pos_valores >= 0) {	
			eval("valor = f1."+mytags[i].id+".value;");
			if ((valor > 0) && (valor != undefined)) {
				valores.push(valor);
			}
		}
   }

   var filtro_camvariables = "";
   if (valores.length > 0) {
	   valores = valores.unique();
	   for (i=0;i<valores.length;i++){
	      filtro_camvariables += valores[i];
		  if (i < (valores.length-1)) {
			filtro_camvariables += ",";
		  }
	   }
   }
   if (filtro_camvariables == "") {
	filtro_camvariables = "0";
   }

	f1.filtros.value = f1.filtrado_precio.value+"@"+f1.filtrado_tipo.value+"@"+f1.filtrado_marca.value+"@"+filtro_camvariables+"@"+f1.filtrado_macrotipo.value;
	f1.submit();
}
//-----------------------------------------
function filtrar_actividades()
{
	var f1 = document.formulario_filtrar;

	f1.submit();
}
//-----------------------------------------
function buscar_cms(criterio, criterio_id)
{
	var f2 = document.formulario_buscar;
	f2.criterio.value = criterio;
	f2.criterio_id.value = criterio_id;	

	if (criterio_id == "") {
		alert(TXT_ALERTS_INDICAR_TERMINO);
		return false;
	} else {
		f2.submit();	
	}
}
//-----------------------------------------
function buscar_comunicados(criterio, criterio_id)
{
	var f2 = document.formulario_buscar;
	f2.criterio.value = criterio;
	f2.criterio_id.value = criterio_id;	

	if (criterio_id == "") {
		alert(TXT_ALERTS_INDICAR_TERMINO);
		return false;
	} else {
		f2.submit();	
	}
}
//-----------------------------------------
function buscar()
{
	var f1 = document.formulario_buscar;

	switch(f1.tipo_busqueda.value) {
		case '0':
			alert(TXT_ALERTS_SELECCIONAR_AREA_BUSCAR);
			return false;
		break;
		case '1':
			f1.action = f1.url_action_1.value;
			return buscar_productos('buscador', f1.filtro_texto.value);
		break;
		case '2':
			f1.action = f1.url_action_2.value;
			return buscar_cms('buscador', f1.filtro_texto.value);
		break;
		case '3':
			f1.action = f1.url_action_3.value;
			return buscar_comunicados('buscador', f1.filtro_texto.value);			
		break;
	}
}
//-----------------------------------------
function submitenter_buscar(myfield,e)
{
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;
	if (keycode == 13)
	{
		var f1 = document.formulario_buscar;
		if (f1.tipo_busqueda.value == 0) {
			alert(TXT_ALERTS_SELECCIONAR_AREA_BUSCAR);
			return false;
		} else {
			return buscar();
		}
	} else{
		return true;
	}
}
//-----------------------------------------
function submitenter_login(myfield,e,tipo)
{
	var keycode;

	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;

	if (keycode == 13)
	{
		CompruebaFormulario_login(tipo);
		return false;
	} 
	else
	{
	}

	return true;
}
//-----------------------------------------
function buscar_clientes()
{
	var f1 = document.formulario_buscar_clientes_modulo;

	switch(f1.tipo_busqueda.value) {
		case '0':
			alert(TXT_ALERTS_SELECCIONAR_AREA_BUSCAR);
			return false;
		break;
		case '1':
			f1.action = f1.url_action_1.value;
			return buscar_productos('buscador', f1.filtro_texto.value);
		break;
		case '2':
			f1.action = f1.url_action_2.value;
			return buscar_cms('buscador', f1.filtro_texto.value);
		break;
		case '3':
			f1.action = f1.url_action_3.value;
			return buscar_comunicados('buscador', f1.filtro_texto.value);			
		break;
	}
}
//-----------------------------------------
function solicitar_informacion()
{
	document.getElementById("solicitar_info_div").style.display = "";
	document.getElementById("enviar_amigo_div").style.display = "none";
	try {
		document.getElementById("valorar_producto_div").style.display = "none";
	} catch(e) {
		null;
	}
}
//-----------------------------------------
function enviar_amigo()
{
	document.getElementById("solicitar_info_div").style.display = "none";
	document.getElementById("enviar_amigo_div").style.display = "";
	try {
		document.getElementById("valorar_producto_div").style.display = "none";
	} catch(e) {
		null;
	}
}
//-----------------------------------------
function valorar_producto()
{
	document.getElementById("solicitar_info_div").style.display = "none";
	document.getElementById("enviar_amigo_div").style.display = "none";
	try {
		document.getElementById("valorar_producto_div").style.display = "";
	} catch(e) {
		null;
	}
}
//-----------------------------------------
function MM_swapImage_puntuacion(num, puntuacion, url_img)
{
	var img_;
	for (i=1;i<=5;i++) {
		if (i<=num) {
			img_ = "ico_principal_on.gif";
		} else {
			img_ = "ico_principal_off.gif";		
		}
		document.getElementById("puntuacion_"+i).src = url_img+img_;						
	}
}
//-----------------------------------------
function MM_swapImgRestore_puntuacion(num, puntuacion, url_img)
{
	var img_;
	for (i=1;i<=5;i++) {
		img_ = "ico_principal_off.gif";		
		document.getElementById("puntuacion_"+i).src = url_img+img_;						
	}
}
//-----------------------------------------
function puntuar_producto(num, puntuacion, url_img)
{
	var f1 = document.formulario_valoracion;
	f1.puntuacion.value = num;	

	var img_;
	var html_ = "";
	
	for (i=1;i<=5;i++) {
		if (i<=num) {
			img_ = "ico_principal_on.gif";
		} else {
			img_ = "ico_principal_off.gif";		
		}		
		html_ += "<img src=\""+url_img+img_+"\" border=\"0\"> ";
	}
	
	document.getElementById("div_puntuacion").innerHTML = html_;	
}
//-----------------------------------------
function marcar_empresa_registro() {
	
	var f1=document.formulario;
	var enviar=true;

	if (f1.check_empresa.checked) {
		document.getElementById("empresa").className="";		
		f1.empresa.focus();
	} else {
		document.getElementById("empresa").className="campoInactivo";		
		f1.empresa.value = "";
	}
}
//-----------------------------------------
function MouseOver_menu_superior(imagen, id)
{
	var elemento = document.getElementById(id);
	elemento.style.background = "url("+imagen+") no-repeat";
}

//-----------------------------------------
function MouseOut_menu_superior(imagen, id)
{
	var elemento = document.getElementById(id);
	elemento.style.background = "url("+imagen+") no-repeat";
}
//-----------------------------------------
function cargar_megaeditor(id_){

	var oFCKeditor = new FCKeditor(id_);
	oFCKeditor.BasePath = "/FCKeditor/";
	oFCKeditor.Height = 350;
	oFCKeditor.Width = 375;
	oFCKeditor.ToolbarSet = "Medio";
	oFCKeditor.ReplaceTextarea();
}
//-----------------------------------------
function confirmar_accion(url_accion)
{
	var confirmar = confirm(TXT_ALERTS_ESTA_SEGURO);
	
	if (confirmar) {
		document.location.href = url_accion;
	}
}
//-----------------------------------------
function confirmar_cerrar_sesion(url_accion) {
	
	var confirmar = confirm(TXT_ALERTS_CERRAR_SESION_USUARIO+"\n\n"+TXT_ALERTS_ESTA_SEGURO);
	
	if (confirmar) {
		document.location.href = url_accion;
	}
}
// -----------------------------------------------------------------------------------
function redirect_url(url_) {
	if (url_ != 0) {
		document.location.href = url_;
	}
}
//-----------------------------------------
function enviar_amigo_comunicado()
{
	try {
		document.getElementById("comentar_comunicado_div").style.display = "none";
	} catch(e) {
		null;
	}
	
	document.getElementById("enviar_amigo_div").style.display = "";
	location.href="#enviar_amigo";
	
}
//-----------------------------------------
function comentar_comunicado()
{
	try {
		document.getElementById("enviar_amigo_div").style.display = "none";
	} catch(e) {
		null;
	}
	
	document.getElementById("comentar_comunicado_div").style.display = "";
	location.href="#comentar_comunicado";
}

// -----------------------------------------------------------------------------------
function checkIt(string) {
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}
// -----------------------------------------------------------------------------------
function fireEvent(obj,evt){
	
	var fireOnThis = obj;
	if( document.createEvent ) {
	  var evObj = document.createEvent('MouseEvents');
	  evObj.initEvent( evt, true, false );
	  fireOnThis.dispatchEvent(evObj);
	} else if( document.createEventObject ) {
	  fireOnThis.fireEvent('on'+evt);
	}
}
// -----------------------------------------------------------------------------------
function cambia_mes_calendario_eventos(url_){
	operaciones.document.location = url_;
}
// -----------------------------------------------------------------------------------
function filtra_anyo_comunicados(url_, anyo) {
	if (url_ != "") {

	  	var url_anyo = new String(url_);		
		if (anyo > 0) {
	  		url_anyo=replaceSubstring(url_anyo, "999999", anyo);
		} else {
	  		url_anyo=replaceSubstring(url_anyo, "-a-999999", "");
		}
		document.location.href = url_anyo;
	}
}
// -----------------------------------------------------------------------------------
function delay(milisegundos)
{
	for(i=0;i<=milisegundos;i++) {
		setTimeout('',1);
	}
}
// -----------------------------------------------------------------------------------
function CreateBookmarkLink(title, url) {

	if (window.sidebar) { 
		// Mozilla Firefox
		window.sidebar.addPanel(title, url, "");
	} else if( window.external ) { 
		// IE
		window.external.AddFavorite(url, title); 
	} else if(window.opera && window.print) { 
		// Opera
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',title);
		elem.setAttribute('rel','sidebar');
		elem.click();
	}
}
// -----------------------------------------------------------------------------------
function mostrar_filtros_buscador(tipo_busqueda)
{
	document.getElementById("div_filtro_tipo_producto").style.display = "none";
	document.getElementById("div_filtro_marca").style.display = "none";
			
	switch(tipo_busqueda) {
		case '0':
			//
		break;
		case '1':
			document.getElementById("div_filtro_tipo_producto").style.display = "";
			document.getElementById("div_filtro_marca").style.display = "";
		break;
		case '2':
			//
		break;
		case '3':
			//
		break;
	}
}
// -----------------------------------------------------------
function imprimir_pagina() {

	var navegador = new String(navigator.userAgent);
	
   if (navegador.indexOf('Firefox') > 0) {
		alert(TXT_ALERTS_MOZILLA_NO_IMPRIME);
	} 
	print();
}

// -----------------------------------------------------------
function genera_pdf_factura(idfac){
	
	permiso=confirm("La factura no dispone de PDF, ¿Desea vd generarlo?");
	if(permiso){
	formulari=document.formulario_facturas;
	
	formulari.idfact.value=idfac;
	formulari.submit();
	}
}

// -----------------------------------------------------------
function mostrarCapa_clientes(div_id)
{
	// --
	var array_capas = new Array ("presentacion", "localizacion", "otros_datos", "galeria_fotos");

	for(i=0;i<array_capas.length;i++) {
		
		try {
			document.getElementById("div_cliente_"+array_capas[i]).style.display = "";
			document.getElementById("enlace_"+array_capas[i]).className = "";
		} catch(e) {
			null;
		}

		if (div_id != array_capas[i]) {
			try {
				document.getElementById("div_cliente_"+array_capas[i]).style.display = "none";
			} catch(e) {
				null;
			}
		} else {
			try {
				document.getElementById("enlace_"+array_capas[i]).className = "activo";
			} catch(e) {
				null;
			}
		}
	}
	// Correción google maps
	if (div_id == "localizacion") {
		google_maps_resize_and_center();
	}
}

// -----------------------------------------------------------
function cambiar_foto_producto(grande, mediana, jqzoom) {
	
	html = "";
	html += "<a href=\"/productos/imagenes/"+grande+"\"";
	if (jqzoom) {
		html += " class=\"jqzoom\"";
	}
	html += "><img width=\"265\" title=\"\" style=\"cursor: pointer;\" class=\"fotoPrincipal\" src=\"/productos/imagenes/"+mediana+"\"></a>";
	
	document.getElementById("foto_principal").innerHTML = html;
	
    $('#fotos a').lightBox();
	$(".jqzoom").jqzoom();

}
// -----------------------------------------------------------------------------------
function arbol_combo_id(url_, id_) {

	if ((url_ != "") && (id_ > 0)) {
		
	  	var url_aux = new String(url_);		
  		url_aux=replaceSubstring(url_aux, "999999", id_);

		document.location.href = url_aux;
	}
}
// -----------------------------------------------------------
function google_maps_initialize(zoom, map_id) {
  geocoder = new google.maps.Geocoder();
  //var latlng = new google.maps.LatLng(39.466725,-0.392525);
  var latlng = new google.maps.LatLng(40.31384,-3.836842);
  var myOptions = {
    zoom: zoom,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.HYBRID
  }
  map = new google.maps.Map(document.getElementById(map_id), myOptions);
}
// -----------------------------------------------------------
function google_maps_codeAddress(address_name, address_value) {
  var address = address_value;
  if (geocoder) {
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
		  // --
		//alert(results[0].geometry.location);
		
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: map, 
            position: results[0].geometry.location,
			title: address_name,
	        icon: icono_google_maps
        });
		  // --
	      var infowindow = new google.maps.InfoWindow();
	      infowindow.setContent(address_name);
	      google.maps.event.addListener(marker, 'click', function() {
	        infowindow.open(map, marker);
	      });
		  // --

      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }
}

// -----------------------------------------------------------
function codeLatLng(input) {
    //var input = document.getElementById("latlng").value;
    var latlngStr = input.split(",",2);
    var lat = parseFloat(latlngStr[0]);
    var lng = parseFloat(latlngStr[1]);
    var latlng = new google.maps.LatLng(lat, lng);
    map.setZoom(5);
    
    marker = new google.maps.Marker({
        position: latlng, 
        map: map,
        icon: icono_google_maps
    }); 
    
   
    
    /*
    if (geocoder) {
      geocoder.geocode({'latLng': latlng}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (results[1]) {
            map.setZoom(5);
            marker = new google.maps.Marker({
                position: latlng, 
                map: map
            }); 
            //infowindow.setContent(results[1].formatted_address);
            //infowindow.open(map, marker);
          }
        } else {
          alert("Geocoder failed due to: " + status);
        }
      });
    }*/
  }

// -----------------------------------------------------------
function placeMarker(location) {
	  var clickedLocation = new google.maps.LatLng(location);
	  var marker = new google.maps.Marker({
	      position: location, 
	      map: map,
          icon: icono_google_maps
	  });

	  map.setCenter(location);
	}
	
// -----------------------------------------------------------
function codeLatLngaddress(input,addres,nummarker) {
    //var input = document.getElementById("latlng").value;
    var latlngStr = input.split(",",2);
    var lat = parseFloat(latlngStr[0]);
    var lng = parseFloat(latlngStr[1]);
    var latlng = new google.maps.LatLng(lat, lng);
    map.setZoom(6);
    
    marker = new google.maps.Marker({
        position: latlng, 
        map: map,
        icon: icono_google_maps
    }); 
    
    variable="marker"+nummarker+"=marker";
    eval(variable);
    
    
    
    var infowindow = new google.maps.InfoWindow();
    infowindow.setContent(addres);
  
   // infowindow.open(map, marker);
    google.maps.event.addListener(marker, 'click', function() {infowindow.open(map, marker);});
    varb="google.maps.event.addListener(marker"+nummarker+", 'click', function() {infowindow.open(map, marker"+nummarker+");});";
    eval(varb);
    
    /*
    if (geocoder) {
      geocoder.geocode({'latLng': latlng}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (results[1]) {
            map.setZoom(5);
            marker = new google.maps.Marker({
                position: latlng, 
                map: map
            }); 
            //infowindow.setContent(results[1].formatted_address);
            //infowindow.open(map, marker);
          }
        } else {
          alert("Geocoder failed due to: " + status);
        }
      });
    }*/
  }


// -----------------------------------------------------------
function google_maps_codeLatLng(input, address_name) {

    var latlngStr = input.split(",",2);
    var lat = parseFloat(latlngStr[0]);
    var lng = parseFloat(latlngStr[1]);

	var latlng = new google.maps.LatLng(lat, lng);
	map.setCenter(latlng);
	map.setZoom(16);

    // --
    var marker = new google.maps.Marker({
        position: latlng, 
        map: map,
		title: address_name,
        icon: icono_google_maps
    });
	  // --
      var infowindow = new google.maps.InfoWindow();
      infowindow.setContent(address_name);
      google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(map, marker);
      });
	  // --

}

// -----------------------------------------------------------
function google_maps_resize_and_center() {
	
  	var centro = new String(map.getCenter());		
    var latlngStr = centro.split(",");

	var latitud = new String(latlngStr[0]);
	latitud = latitud.replace("(","");
	latitud = latitud.replace(" ","");		
	
	var longitud = new String(latlngStr[1]);
	longitud = longitud.replace(")","");
	longitud = longitud.replace(" ","");
	
	// Si no ponemos esto el mapa se verá MAL
	google.maps.event.trigger(map, 'resize');
	
	// Si no ponemos esto no saldrá la marca en el centro del mapa
    var latlng = new google.maps.LatLng(latitud, longitud);
	map.setCenter(latlng);
}
