/*
*	Lista de navegadores malnacidos
*/
var ie52mac = (
	navigator.userAgent.indexOf('MSIE 5.2') != -1 &&
	navigator.userAgent.indexOf('Mac') != -1
);
/*
*	Funciones DHTML compatibles con el estándar DOM
*/
// Función para obtener el valor de un estilo dado el id del elemento
function getStyleById(id, style)
{
	var elm = document.getElementById(id);
	return getStyle(elm, style);
}
// Función para obtener el valor de un estilo dado el elemento
function getStyle(elm, style)
{
	if(typeof(document.defaultView) == 'object') return document.defaultView.getComputedStyle(elm, null).getPropertyValue(style);
	else if(elm.currentStyle) return elm.currentStyle[style];
}
// Función para establecer el valor de un estilo dado el id del elemento
function setStyleById(id, style, value)
{
	var elm = document.getElementById(id);
	setStyle(elm, style, value);
}
// Función para establecer el valor de un estilo dado el elemento
function setStyle(elm, style, value)
{
	elm.style[style] = value;
}
/*
*	Función para inicializar diferentes módulos
*/
var window_onload = [];
window.onload = function()
{
	for(var i in window_onload) {
		eval(window_onload[i]);
	}
}
/*
*	Activar el boton del menú
*/
function MenuInit()
{
	if(typeof(activar) != 'undefined') {
		var elm = document.getElementById('menu' + activar + 'bot');
		elm.className = 'on';
	}
}
window_onload[window_onload.length] = 'MenuInit()';
/*
*	Funciones para Rollovers
*/
// Función para inicializar los rollovers
function RollInit()
{
	var imgs = document.getElementsByTagName('IMG');
	for(var i = 0; i != imgs.length; ++i) {
		if(/(\w+)ROLL$/.test(imgs[i].id)) {
			var roll_id = RegExp.$1;
			if(/(\w+)FOTO$/.test(roll_id)) {
				// ...
			} else {
				var elm = imgs[i];
				elm.img_over = new Image();
				elm.img_over.src = elm.src.replace(/(.gif|.jpg|.png)$/, '_over$1');
				elm.img_orig = new Image();
				elm.img_orig.src = elm.src;
				if(/(\w+)MENU$/.test(roll_id)) {
					elm.MyRollOver = RollOver;
					elm.MyRollOut = RollOut;
				} else {
					elm.onmouseover = RollOver;
					elm.onmouseout = RollOut;
				}
			}
		}
	}
}
window_onload[window_onload.length] = 'RollInit()';

// Función para hacer rollover de una imagen
function RollOver()
{
	this.src = this.img_over.src;
}
// Función para restaurar una imagen
function RollOut()
{
	this.src = this.img_orig.src;
}
function setOpacityById(id, alfa)
{
	var elm = document.getElementById(id);
	return setOpacity(elm, alfa);
};
function setOpacity(elm, alfa)
{
	if(alfa == 0) {
		elm.style.visibility = 'hidden';
	} else if(elm.style.visibility == 'hidden') {
		elm.style.visibility = 'inherit';
	}
	if(typeof(elm.style.opacity) != 'undefined') elm.style.opacity = (alfa == 1) ? '0.999' : alfa;
	else if(typeof(elm.style.MozOpacity) != 'undefined') elm.style.MozOpacity = (alfa == 1) ? '0.999' : alfa;
	else if(typeof(elm.style.KhtmlOpacity) != 'undefined') elm.style.KhtmlOpacity = alfa;
	else if(!ie52mac && typeof(elm.style.filter) != 'undefined') elm.style.filter = (alfa == 1) ? '' : 'alpha(opacity=' + (alfa*100) + ')';
};
function BlendById(id, alfa0, alfa1)
{
	var elm = document.getElementById(id);
	return Blend(elm, alfa0, alfa1);
};
var blend_elm = null;
var blend_alfa1 = 0;
var blend_tmr = null;
var blend_t = 50;
function Blend(elm, alfa0, alfa1)
{
	if(blend_tmr) {
		clearTimeout(blend_tmr);
		blend_tmr = null;
	}
	if(blend_elm) {
		setOpacity(blend_elm, blend_alfa1);
	}
	blend_elm = elm;
	blend_alfa1 = alfa1;
	blend_tmr = setTimeout('cicloBlend(' + alfa0 + ')', blend_t);
};
function cicloBlend(alfa0)
{
	blend_tmr = null;
	if(blend_elm) {
		setOpacity(blend_elm, alfa0);
		var tmp = 0.333 * (blend_alfa1 - alfa0);
		if(Math.abs(tmp) <= 0.01) {
			setOpacity(blend_elm, blend_alfa1);
			blend_elm = null;
		} else {
			alfa0 += tmp;
			blend_tmr = setTimeout('cicloBlend(' + alfa0 + ')', blend_t);
		}
	}
};
/*
	Función para abrir una ventana. Puede recibir los siguientes parámetros:

	url	-> Página web que mostrará la ventana. Por defecto página en blanco. Ejemplo: 'aviso.phpl'.
	target	-> Ventana en la que se abrirá la url. Por defecto en una nueva ventana cada vez. Ejemplo: '_blank'.
	width	-> Ancho en píxeles de la ventana. Por defecto 250 píxeles. Ejemplo: 300
	height	-> Alto en píxeles de la ventana. Por defecto 250 píxeles. Ejemplo: 125
	left	-> Distancia en píxeles al borde izquierdo de la pantalla. Por defecto centrada horizontalmente. Ejemplo: 100
	top	-> Distancia en píxeles al borde superior de la pantalla. Por defecto centrada verticalmente. Ejemplo: 100
	resizable	-> Indica si el usuario puede modificar el tamaño de la ventana. Por defecto no. Ejemplo: 'yes' o true
		Valores posibles: 'yes', 'no', '1', '0', true, false.
	scrollbars	-> Indica si la ventana tendrá barras de scroll. Por defecto no. Ejemplo: 'no' o false
		Valores posibles: 'yes', 'no', '1', '0', true, false.

	Poner un parámetro a null o no pasarlo es lo mismo.

	Ejemplo:

	// Abrir aviso.phpl en una nueva ventana, con tamaño 250x125, centrada horizontalmente
	// pero a 100 píxeles del borde superior.

	AbrirVentana('aviso.php', '_blank', 250, 125, null, 100);
*/
function AbrirVentana(url, target, width, height, left, top, resizable, scrollbars)
{
	if(typeof(url) == 'undefined' || url == null) url = '';
	if(typeof(target) == 'undefined' || target == null) target = '';

	if(typeof(width) == 'undefined' || width == null) width = 275;
	if(typeof(height) == 'undefined' || height == null) height = 275;

	if(typeof(window.screen) == 'undefined') {
		var sw = 800;
		var sh = 600;
	} else {
		var sw = window.screen.width;
		var sh = window.screen.height;
	}

	if(typeof(left) == 'undefined' || left == null) left = Math.round(0.5 * (sw - width));
	if(typeof(top) == 'undefined' || top == null) top = Math.round(0.5 * (sh - height));

	if(typeof(resizable) == 'undefined' || resizable == 'no' || !resizable) resizable = 0;
	else resizable = 1;

	if(typeof(scrollbars) == 'undefined' || scrollbars == 'no' || !scrollbars) scrollbars = 0;
	else scrollbars = 1;

	var win = window.open(url, target, 'left=' + left + ',top=' + top + ',width=' + width + ',height=' + height + ',directories=0,location=0,menubar=0,resizable=' + resizable +',scrollbars=' + scrollbars + ',status=0,toolbar=0');
	win.focus();
}
/*
*	Funciones auxiliares comúnmente usadas
*/
// Función para mostrar un elemento
function Muestra(id)
{
	setStyleById(id, 'visibility', 'inherit');
}
// Función para ocultar un elemento
function Oculta(id)
{
	setStyleById(id, 'visibility', 'hidden');
}
// Función para ir a una url
function IrA(url)
{
	location.href = url;
};
// Función para los combos que saltan a urls
function Saltar(elm)
{
	var url = elm[elm.selectedIndex].value;
	if(url == '') elm.selectedIndex = 0;
	else location.href = url;
}
/*
*	Funciones para chequear formularios
*/
var errores = '';
function ValidarRequerido(campo, titulo, formulario)
{
	if(typeof(formulario) == 'undefined') formulario = 'formulario';
	var form = document.getElementById(formulario);
	if(form[campo].value == '') {
		if(errores == '') form[campo].focus();
		errores += '- ' + titulo + '.\n';
		setStyle(form[campo], 'backgroundColor', '#FFF');
		setStyle(form[campo], 'color', '#000');
	} else {
		setStyle(form[campo], 'backgroundColor', '');
		setStyle(form[campo], 'color', '');
	}
};

function ValidarRequeridoGestion(campo, titulo, formulario)
{
	if(typeof(formulario) == 'undefined') formulario = 'formulario';
	var form = document.getElementById(formulario);
	if(form[campo].value == '') {
		if(errores == '') form[campo].focus();
		errores += '- ' + titulo + '.\n';
		setStyle(form[campo], 'backgroundColor', '#e0e0e0');
		setStyle(form[campo], 'color', '#000');
	} else {
		setStyle(form[campo], 'backgroundColor', '');
		setStyle(form[campo], 'color', '');
	}
};

function ValidarSelectRequerido(campo, titulo, formulario)
{

	if(typeof(formulario) == 'undefined') formulario = 'formulario';
	var form = document.getElementById(formulario);
	if(form[campo].selectedIndex==0) {
		if(errores == '') form[campo].focus();
		errores += '- ' + titulo + '.\n';
		setStyle(form[campo], 'backgroundColor', '#FFF');
		setStyle(form[campo], 'color', '#000');
	} else {
		setStyle(form[campo], 'backgroundColor', '');
		setStyle(form[campo], 'color', '');
	}
};

function ValidarCheckbox(campo, titulo,  formulario) {

	if(typeof(formulario) == 'undefined')
	{
		formulario = 'formulario';
	}
	var form = document.getElementById(formulario);
	if(!form[campo].checked)
		errores += '- ' + titulo + '.\n';
};

function ValidarEmail(campo, titulo, formulario)
{
	if(typeof(formulario) == 'undefined') formulario = 'formulario';
	var form = document.getElementById(formulario);
	if(form[campo].value == '' || !isEmail(form[campo].value)) {
		if(errores == '') form[campo].focus();
		errores += '- ' + titulo + '.\n';
		setStyle(form[campo], 'backgroundColor', '#FFF');
		setStyle(form[campo], 'color', '#000');
	} else {
		setStyle(form[campo], 'backgroundColor', '');
		setStyle(form[campo], 'color', '');
	}
};
// Función para comprobar el formato de una dirección de correo
function isEmail(str) {
	// are regular expressions supported?
	var supported = 0;
	if(window.RegExp) {
		var tempStr = 'a';
		var tempReg = new RegExp(tempStr);
		if(tempReg.test(tempStr)) supported = 1;
	}
	if(!supported) return (str.indexOf('.') > 2) && (str.indexOf('@') > 0);
	var r1 = new RegExp('(@.*@)|(\\.\\.)|(@\\.)|(^\\.)');
	var r2 = new RegExp('^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$');
	return (!r1.test(str) && r2.test(str));
};
// Función para comprobar el formato de la fecha: dia/mes/año (año >= 1970)
function CheckDate(fecha){
	if(fecha == '' || fecha == null) return(2);
	fecha_date = fecha.match(/^(\d+)\/(\d+)\/(\d+)$/);
	if(fecha_date == '' || fecha_date == null ) return(0);
	fecha_dia = Number(fecha_date[1]);
	fecha_mes = Number(fecha_date[2]);
	fecha_ano = Number(fecha_date[3]);
	if(isNaN(fecha_dia) || isNaN(fecha_mes) || isNaN(fecha_ano)) return(0);
	if(fecha_ano > 70 && fecha_ano <= 99 ) fecha_ano = fecha_ano + 1900
	if(fecha_ano < 1970 || fecha_ano > 9999) return(0);
	if(fecha_ano % 4 == 0) bisiesto = true; // año bisiesto
	else bisiesto = false;
	if(fecha_mes == 2) {
		if(!bisiesto) {
			if(fecha_dia > 28 || fecha_dia < 1) return (0);
		} else {
			if(fecha_dia > 29 || fecha_dia < 1) return (0);
		}
	} else if(fecha_mes==1 || fecha_mes==3 || fecha_mes==5 || fecha_mes==7 || fecha_mes==8 || fecha_mes==10 || fecha_mes==12) {
		if(fecha_dia > 31 || fecha_dia < 1) return (0);
	} else if(fecha_mes==9 || fecha_mes==4 || fecha_mes==6 || fecha_mes==11) {
		if(fecha_dia > 30 || fecha_dia < 1) return (0);
	} else return (0);
	return(1);
};

function CheckTime(str)
{
	hora = str;
	if (hora=='') return(0);
	if (hora.length > 5) return(0);
	a = hora.charAt(0); //<=2
	b = hora.charAt(1); //<4
	c = hora.charAt(2); //:
	d = hora.charAt(3); //<=5
	if ((a==2 && b>3) || (a>2)) return(0);
	if (d>5) return(0);
	if (c!=':') return(0);
	return(1);
}

function replaceAll( str, from, to ) {
    var idx = str.indexOf( from );

    while ( idx > -1 ) {
        str = str.replace( from, to );
        idx = str.indexOf( from );
    }

    return str;
}


 /*****************INICIO DE LAS FUNCIONES DE GOOGLE MAPS******************
  // Llamar a esta funcion cuando la página haya cargado
	Funciones para cargar google maps en la página
	y para posidionar los marcadores de las obras en su correspondiente punto geográfico
*********************************************************************/
function iniciar(id, nombre, pais, ciudad, direccion, latitud, longitud, centro_latitud, centro_longitud, zoom, tipo_fabrica,mas_info) {
var html = [];
var tipo;

var Arr_imag=new Array();

for (var i=0; i < tipo_fabrica.length; i++)
{
	tipo = tipo_fabrica[i];
	var tinyIcon = new GIcon();
	tinyIcon.shadow = "../images/marcador_google_sombra.png";
	//alert(tipo);

	switch(tipo)
	{
		case "1":
			tinyIcon.image = "../images/marcador_google.png";
			tinyIcon.iconSize = new GSize(53, 30);
			tinyIcon.shadowSize = new GSize(53, 30);
			tinyIcon.iconAnchor = new GPoint(17 , 29);
			Arr_imag[i] = tinyIcon;
			break;
		case "2":
			tinyIcon.image = "../images/marcador_google.png";
			tinyIcon.iconSize = new GSize(53, 30);
			tinyIcon.shadowSize = new GSize(53, 30);
			tinyIcon.iconAnchor = new GPoint(17 , 29);
			Arr_imag[i] = tinyIcon;
			break;
		case "3":
			tinyIcon.image = "../images/marcador_google_distribuidores.png";
			tinyIcon.iconSize = new GSize(53, 30);
			tinyIcon.shadowSize = new GSize(53, 30);
			tinyIcon.iconAnchor = new GPoint(17 , 29);
			Arr_imag[i] = tinyIcon;
			break;
		case "4":
			tinyIcon.image = "../images/marcador_google_instalaciones.png";
			tinyIcon.iconSize = new GSize(53, 30);
			tinyIcon.shadowSize = new GSize(53, 30);
			tinyIcon.iconAnchor = new GPoint(17 , 29);
			Arr_imag[i] = tinyIcon;
			break;
		case "5":
			tinyIcon.image = "../images/marcador_google_instalaciones.png";
			tinyIcon.iconSize = new GSize(53, 30);
			tinyIcon.shadowSize = new GSize(53, 30);
			tinyIcon.iconAnchor = new GPoint(17 , 29);
			Arr_imag[i] = tinyIcon;
			break;
	}


}


var map = new google.maps.Map2(document.getElementById("map"));
map.setCenter(new google.maps.LatLng(centro_latitud, centro_longitud), zoom);


      /***************FUNCIONES PARA CREAR BOTONES DE ZOOM PERSONALIZADOS*****************************/
function TextualZoomControl() {
}

// To "subclass" the GControl, we set the prototype object to
// an instance of the GControl object
TextualZoomControl.prototype = new GControl();


// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.
TextualZoomControl.prototype.initialize = function(map) {
  var container = document.createElement("div");

  /*var zoomInDiv = document.createElement("div");
  this.setButtonStyle_(zoomInDiv);
  container.appendChild(zoomInDiv);
  zoomInDiv.appendChild(document.createTextNode("Acercarse"));
  GEvent.addDomListener(zoomInDiv, "click", function() {
    map.zoomIn();
  });

  var zoomOutDiv = document.createElement("div");
  this.setButtonStyle_(zoomOutDiv);
  container.appendChild(zoomOutDiv);
  zoomOutDiv.appendChild(document.createTextNode("Alejarse"));
  GEvent.addDomListener(zoomOutDiv, "click", function() {
    map.zoomOut();
  });*/

  map.getContainer().appendChild(container);
  return container;
}

// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
TextualZoomControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10, 66));
}

// Sets the proper CSS for the given button element.
TextualZoomControl.prototype.setButtonStyle_ = function(button) {
  button.style.textDecoration = "none";
  button.style.color = "#000000";
  button.style.backgroundColor = "white";
  button.style.font = "small Arial";
  button.style.fontSize = "10px";
  button.style.border = "1px solid black";
  button.style.padding = "0px";
  button.style.marginBottom = "3px";
  button.style.marginLeft = "30px";
  button.style.textAlign = "center";
  button.style.width = "5em";
  button.style.cursor = "pointer";
}
map.addControl(new TextualZoomControl());
/***************FIN DE FUNCIONES PARA CREAR BOTONES DE ZOOM PERSONALIZADOS*****************************/
map.addControl(new GSmallMapControl());




/***************************************************/
	if (id!=null)
	{
		 for (i = 0; i< id.length; i++)
		 {
		 	if (latitud [i]!=0, latitud[i]!=0)
		 	{
				html[i] = '<span class="titulo">'+nombre[i]+'</span><br/><span class="situacion">';

				if(pais[i]!='' && ciudad[i]!='')
					html[i] += pais[i]+' ('+ciudad[i]+')';
				if(direccion!=null)
				{
					html[i] +='<br/>'+direccion[i];
				}
				html[i] +='</span><br/><a href="#" onclick="javascript:mensaje('+id[i]+')">' + mas_info + '</a>';

				var point = new google.maps.LatLng(latitud[i], longitud[i]);

				markerOptions = { icon: Arr_imag[i] };
				map.addOverlay(createMarker(point, markerOptions, html[i]));
			}
		}
	}
	/**************************************************/
	function createMarker(point, markerOptions, html) {

	  var marker = new GMarker(point, markerOptions);
	  GEvent.addListener(marker, "click", function() {
	    map.openInfoWindowHtml(point, html);
	  });
	  return marker;
	}
  }

/***************FIN DE LAS FUNCIONES DE GOOGLE MAPS************************************/

  /***************INICIO DE LAS FUNCIONES PARA IMPRIMIR EL MAPA DE GOOGLE*******************
  Funcion para imprimir el mapa de google maps
  *********************************************************************************/
  function imprimirMapa(nombre, nombre2)
{
	var elm = document.getElementById (nombre).innerHTML;
	var elm2 = document.getElementById (nombre2).innerHTML;
	document.getElementById ('imprimir').innerHTML = elm+'<div style="position: absolute; top: 500px; left: 0;">'+elm2+'</div>';
	print();
}

function imprimir()
{
	window.print();
}

/***************FIN DE LAS FUNCIONES PARA IMPRIMIR GOOGLE MAPS************************************/

/*
*	Funciones Ajax
*	http://microformats.org/wiki/rest/ahah
*/
function ajaxGet(url, target, atend) {
	if(window.XMLHttpRequest) {
		var req = new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		var req = new ActiveXObject('Microsoft.XMLHTTP');
	}

	if(req) {
		document.getElementById(target).value = 'GET ' + url;
		req.onreadystatechange = function() { ajaxDone(req, target, atend); };
		req.open('GET', url, true);
		req.send(null);
	}
}
function ajaxPost(url, parameters, target, atend) {
	if(window.XMLHttpRequest) {
		var req = new XMLHttpRequest();

       	// set type accordingly to anticipated content type
         if(http_request.overrideMimeType) {
            // http_request.overrideMimeType('text/xml');
            http_request.overrideMimeType('text/html');
         }
	} else if(window.ActiveXObject) {
		var req = new ActiveXObject('Microsoft.XMLHTTP');
	}
	if(req) {
		document.getElementById(target).value = 'POST ' + url;
		req.onreadystatechange = function() { ajaxDone(req, target, atend); };
		req.open('POST', url, true);
		req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
		req.setRequestHeader('Content-length', parameters.length);
		req.setRequestHeader('Connection', 'close');
		req.send(parameters);
	}
}
function ajaxDone(req, target, atend) {
	if(req.readyState == 4) {
		if(req.status == 200 || req.status == 304) {
			document.getElementById(target).value = req.responseText;
			if(typeof(atend) != null) eval(atend);
		} else {
			document.getElementById(target).value = 'ajax error:\n' + req.statusText;
		}
	}
}

/************************************/
function ahah(url, target) {
	//document.getElementById(target).innerHTML = 'sending... ' + url;
	if(window.XMLHttpRequest) {
		var req = new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		var req = new ActiveXObject("Microsoft.XMLHTTP");
	}
	if(req) {
		req.onreadystatechange = function() { ahahDone(req, target); };
		req.open("GET", url, true);
		req.send(null);
	}
}
function ahahDone(req, target) {
	if(req.readyState == 4) {
		if(req.status == 200 || req.status == 304) {
			document.getElementById(target).innerHTML = req.responseText;
		} else {
			document.getElementById(target).innerHTML = "ahah error:\n" + req.statusText;
		}
	}
}

/**********************/
function AbreAsesoramiento()
{
	AbrirVentana("asesoramiento.php", "asesoramiento", 500, 550);
};
function AbreAsistencia()
{
	AbrirVentana("asistencia.php", "asistencia", 500, 550);
};

function AbrePrivacidad()
{
	AbrirVentana("privacidad.php", "privacidad", 750, 825);
};

function carga_site(web)
{
	if (web!="")
	{
		document.forms["frm_otras_web"].web.value=web;
		document.forms["frm_otras_web"].submit();
	}
}

function siteOver()
{
	document.getElementById("site").style.display="block";
}

function siteOut()
{
	document.getElementById("site").style.display="none";
}
