/** Variable global que dice si el navegador es IExplorer */
var isIExplorer = navigator.appName.indexOf("Microsoft") != -1;
/** Variable global que dice si el navegador es IExplorer 6 o 7 */
var IEVersion = (navigator.userAgent.toLowerCase().indexOf("msie ") > -1) ? parseInt(navigator.userAgent.toLowerCase().replace(/^.*msie ([0-9]+).*$/g,'$1'), 10) : -1;
/** Variable global que dice si el navegador es Firefox */
var isFirefox = navigator.userAgent.indexOf("Firefox") != -1;
/** CONFIGURACION */
/** si estan activos los botones del navegador mediante javascript */
var navigationActivated = true;

/**
 *  Comprueba periodicamente si el objeto Flash ha cambiado
 *  de pagina, mirando el valor de la variable _root.newFlashPage
 *  de la pelicula Flash y comparandolo con el actual valor
 *  del ancla (location.hash)
 *
 *  Ademas, comprueba periodicamente si ha cambiado el ancla de
 *  la pagina. En ese caso, si la nueva ancla corresponde
 *  a una pagina distinta de la mostrada en el objeto Flash,
 *  solicita a dicho objeto el cambio de pagina
 *  (usando la variable flash '_root.newWebPage')
 *
 *  ATENCION: "none" es valor reservado para newFlashPage y newWebPage
 */
var hashOldValue=""; // Ultimo valor del ancla sin #
function checkPageChanges(){

	var currentHash = location.hash;
	if( currentHash && currentHash.length>0 ){
	    currentHash = currentHash.substr(1);
	}

	// Primero miramos si hay cambios en la pagina Flash
	if( document.theMovie.GetVariable("newFlashPage") ){
		var newVal = document.theMovie.GetVariable("newFlashPage");
	    if( newVal!="none" && newVal!=currentHash ){
			// Detectado cambio en la pagina Flash, tenemos que actualizar el hash
		    log("Detectado cambio de pagina en la pelicula "+currentHash+"-->"+newVal);
			// Una vez leido el valor, borramos la peticion
			document.theMovie.SetVariable("newFlashPage","none");
			if( currentHash!=newVal ){
				hashOldValue = newVal;
				location.hash = "#"+newVal;
				if( isIExplorer ){
					// Cambiamos la URL del iframe oculto para que se almacene en el historico
					document.getElementById("hiddenFrame").src="historyFrame.html?page="+newVal;
				}
			}
			return; // Intentamos que las dos cosas no ocurran simultaneamente
		}
	}

	// Tambien comprobamos cambios en la URL (hash) de la pagina
	if( currentHash!=hashOldValue){
	    log("CheckHashChanges: detectado nuevo hash "+currentHash);
		hashOldValue = currentHash;
		if( document.theMovie &&
			document.theMovie.GetVariable("newFlashPage") &&
			document.theMovie.GetVariable("newFlashPage")!=currentHash ){
		    log("solicitando cambio a pelicula flash "+currentHash);
			document.theMovie.SetVariable( "newWebPage", currentHash );
		}
	}
}

/**
 *  Pone una tarea para comprobar si hemos cambiado de pagina
 *  cada 0.05 segundos.
 *  La manera correcta de hacer esto en EcmaScript es usar
 *  watch, pero no funciona en IE y no siempre en Mozilla.
 *
 *  En el caso de que al iniciar la pagina ya haya un ancla
 *  llamamos a la pelicula flash para que se dirija a esa posicion.
 *
 *  @param foo Parametro de mentiras para poder usarla desde Flash
 *				mediante FSCOMMAND
 **/
function init( foo ){
	log("Funcion init(). Primera llamada desde Flash");

	// Detectamos si hay un ancla inicial
	if( location.hash && location.hash.length>0 ){
	    var newVal = location.hash.substr(1);
	    log("Estableciendo pagina inicial "+newVal);
		document.theMovie.SetVariable( "newWebPage", newVal );
		hashOldValue = newVal;
		if( isIExplorer ){
			// Cambiamos la URL del iframe oculto para que se almacene en el historico
			document.getElementById("hiddenFrame").src="historyFrame.html?page="+newVal;
		}
	} else {
		// Ponemos la URL de la pagina actual a disposicion de Flash
		document.theMovie.SetVariable( "pageURL", document.URL );
	}
	// Ponemos el proceso en marcha
    if( navigationActivated ){
		window.setInterval("checkPageChanges()",100); // Tiempo en milisegundos
	}
}

/* ----------------------------------------------------------------------------------------- */

/**
 *  Va a la página que se le pasa por parámetro añadiendo el hash
 *  como parámetro
 */
function goWithHash( sHref ){
	if( document.location.hash ){
		document.location = sHref + "?hash=" + document.location.hash.substring(1);
	} else {
		document.location = sHref;
	}
}

/**
 *  Inserta en la pagina la pelicula Flash
 **/
function showFlashContent(){
	// Modificamos los enlaces "Visual Mode", "Estándares" y "Porqual"
	// para que funcione correctamente el cambio de versión Flash a
	// versión HTML
	var aLinks = new Array("visualModeLink","waiLink","porqualLink");
	for( n=0; n<document.links.length; n++ ){
	    if( document.links[n].id ){
			for( i in aLinks ){
			    if( document.links[n].id == aLinks[i] ){
					var sOldHref = document.links[n].href;
					var sNewHref = "javascript:goWithHash('" + sOldHref + "')";
					document.links[n].href = sNewHref;
				}
			}
		}
	}

	// Cambiamos de hoja de estilos
	try {
		document.styleSheets[0].rel="alternate stylesheet";
		document.styleSheets[0].disabled=true;
		document.styleSheets[1].rel="stylesheet";
		document.styleSheets[1].disabled=false;
	} catch(e) {
		log("Error cambiando css"+e);
	}
	if( isIExplorer ){
		// Bug: cambiamos el fondo a mano
		var imgAux = new Image();
		imgAux.onreadystatechange = function(){
			if( imgAux.readyState == "complete" ){
				document.body.background = "images\/fondo.gif";
			}
		}
		imgAux.src="images\/fondo.gif";
	}

	// Mostramos el engine Flash
	var sBgcolor="#ffffff";
	if( document.bgColor ){
		sBgcolor = document.bgColor;
	}

	// IE
	document.getElementById("theMovie").movie="swf/engine.swf";
	document.getElementById("theMovie").bgcolor=sBgcolor;
	document.getElementById("theMovie").width="100%";
	document.getElementById("theMovie").height="100%";

	// Mozilla, ...
	document.getElementById("theMovieEmbed").src="swf/engine.swf";
	document.getElementById("theMovieEmbed").bgcolor=sBgcolor;
	document.getElementById("theMovieEmbed").width="100%";
	document.getElementById("theMovieEmbed").height="100%";

	// IFrame necesario para la navegación en IE
	var content = document.getElementById("flashContent");
	if( isIExplorer ){
	    var div = document.createElement("div");
		div.innerHTML = '<iframe id="hiddenFrame" src="about:blank" width="0" height="0"><\/iframe>';
		content.appendChild( div );
	}
	content.style.display = 'inline';
}

/**
 *	 Devuelve true si se detecta flashplayer
 **/
function hasFlashPlayer(){
	return flashinstalled==2;
}

/**
 *	 Devuelve true si detecta flashplayer version es mayor que 7;
 **/
function correctFlashVersion(){
	return flashinstalled==2 && flashversion>=7;
}

/**
 *	 Devuelve true si se detecta algun navegador para ciegos
 **/
function isTextBrowser(){
	return navigator.IBM_HPR; // IBM Home Page Reader
}

/**
 *	Devuelve true si la página se encuentra dentro de una caché
 *	de Google, Yahoo o MSN Search, basándose en los parámetros de
 *	la URL
 **/
function isInSearchEngineCache(){
	var sURL = document.location.href;
	return( sURL.indexOf( "search?q=cache" )!=-1 ||
		sURL.indexOf( "cache.asp" )!=-1 ||
		sURL.indexOf( "search/cache" )!=-1 );
}

/**
 *	 Devuelve true si el usuario ha elegido modo XHTML por defecto
 * 	 o la URL acaba con forceHtml=true
 **/
function htmlMode(){
	var vm = readCookie("visualMode")
	return (vm && vm=="XHTML") ||
	( document.location.search.indexOf("forceHtml=true")>=0 );
}

/**
 *	 Devuelve true si el usuario ha elegido modo FLASH por defecto
 **/
function flashMode(){
	var vm = readCookie("visualMode")
	return vm && vm=="FLASH" &&
	document.location.search.indexOf("forceHtml=true")<0;
}

/**
 *   Detecta las capacidades del navegador y, si
 *   es compatible, carga la pelicula Flash
 **/
function detectBrowserCapabilities(){
	if( document.getElementById &&
		document.createElement &&
		!htmlMode() &&
		!isTextBrowser() &&
		!isInSearchEngineCache() &&
		hasFlashPlayer() &&
		( IEVersion>=6 || isFirefox ) ){

		if( correctFlashVersion() ){
			showFlashContent();
		} else {
			if( confirm( "Para ver la version Flash de esta web necesita\n"+
				"una version mas moderna del plug-in de Flash. \n"+
				"Su descarga e instalacion le llevara pocos minutos\n"+
				"¿Desea ir a la pagina de instalacion ahora?" ) ) {
				document.location =
			"http://www.macromedia.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash&Lang=Spanish";
			}
		}
	}
}

