var windowWidth = 0;
var windowHeight = 0;
var resized = false;

/*************************************************************************
  This code is from Dynamic Web Coding at http://www.dyn-web.com/
  See Terms of Use at http://www.dyn-web.com/bus/terms.html
  Permission granted to use this code
  as long as this entire notice is included.
*************************************************************************/

function getDocHeight(doc) {
	var docHt = 0, sh, oh;
	if (doc.height) docHt = doc.height;
	else if (doc.body) {
		if (doc.body.scrollHeight) docHt = sh = doc.body.scrollHeight;
		if (doc.body.offsetHeight) docHt = oh = doc.body.offsetHeight;
		if (sh && oh) docHt = Math.max(sh, oh);
	}
	return docHt;
}

function setIframeHeight(iframeName) {
	var iframeWin = parent.window.frames[iframeName];
	var iframeEl = parent.document.getElementById? parent.document.getElementById(iframeName): parent.document.all? parent.document.all[iframeName]: null;
	if ( iframeEl && iframeWin ) {
		iframeEl.style.height = "auto"; // helps resize (for some) if new doc shorter than previous
		var docHt = getDocHeight(iframeWin.document);
		// need to add to height to be sure it will all show
		if (docHt) iframeEl.style.height = docHt + 30 + "px";
	}
	windowWidth = parent.document.body.clientWidth;
	windowHeight = parent.document.body.clientHeight;
}

function goSetHeight() {
	if ( windowWidth == parent.document.body.clientWidth && windowHeight == parent.document.body.clientHeight ) return;
	if ( resized ) {
		resized = false;
		windowWidth = parent.document.body.clientWidth;
		windowHeight = parent.document.body.clientHeight;
		return;
	}
	else
		resized = true;
	if (parent == window) return;
	// no way to obtain id of iframe object doc loaded into? no parentNode or parentElement or ...
	else setIframeHeight('ifrm');
}
/*************************************************************************
*************************************************************************/





// Dynamic Layer Object
// sophisticated layer/element targeting and animation object which provides the core functionality needed in most DHTML applications
// 19990604

// Copyright (C) 1999 Dan Steinman
// Distributed under the terms of the GNU Library General Public License
// Available at http://www.dansteinman.com/dynapi/
var ns4 = (document.layers)? true : false;
var ie4 = (document.all)? true : false;
var ns6 = (document.getElementById && !document.all) ? true : false;
////////////////////////////////////////////////////////////////////////////


function showParent(id) {
	if (ns4) parent.document.layers[id].visibility = "show";
	else if (ie4 | ns6) parent.document.getElementById(id).style.visibility = "visible";
}

function hideParent(id) {
	if (ns4) parent.document.layers[id].visibility = "hide";
	else if (ie4 | ns6) parent.document.getElementById(id).style.visibility = "hidden";
}

function show(id) {
	if (ns4) document.layers[id].visibility = "show";
	else if (ie4 | ns6) document.getElementById(id).style.visibility = "visible";
}

function hide(id) {
	if (ns4) document.layers[id].visibility = "hide";
	else if (ie4 | ns6) document.getElementById(id).style.visibility = "hidden";
}

function copySource(idFrom,idTo) {
	if (ns4) {
		parent.document.layers[idTo].document.open();
		parent.document.layers[idTo].document.write("Hi");
		parent.document.layers[idTo].document.close();

	}
	else if (ie4 | ns6) parent.document.getElementById(idTo).innerHTML = parent.document.getElementById(idFrom).innerHTML;

}

function clearSource(id) {
	if (ns4) {
		parent.document.layers[id].document.open();
		parent.document.layers[id].document.write("");
		parent.document.layers[id].document.close();
	}
	else if (ie4 | ns6) parent.document.getElementById(id).innerHTML = "";
}

function clipValues(obj,which) {
	if (ns4) {
		if (which=="t") return obj.clip.top
		if (which=="r") return obj.clip.right
		if (which=="b") return obj.clip.bottom
		if (which=="l") return obj.clip.left
	}
	else if (ie4 | ns6) {
		var clipv = obj.clip.split("rect(")[1].split(")")[0].split("px")
		if (which=="t") return Number(clipv[0])
		if (which=="r") return Number(clipv[1])
		if (which=="b") return Number(clipv[2])
		if (which=="l") return Number(clipv[3])
	}
}

function clipTo(obj,t,r,b,l) {
	alert (obj.clip)
	if (ns4) {
		obj.clip.top = t
		obj.clip.right = r
		obj.clip.bottom = b
		obj.clip.left = l
	}
	else if (ie4 | ns6) obj.clip = "rect("+t+"px "+r+"px "+b+"px "+l+"px)"
}

function moveTo(obj,x,y) {
	obj.xpos = x;
	obj.left = obj.xpos;
	obj.ypos = y;
	obj.top = obj.ypos;
}



/*************************************************************************
  Codigo añadido por Jose Alberto Martinez
*************************************************************************/


var whichButton = null;  // presently clicked or zoomed image
var activeButton = false;
var whichBocadillo = null;
var activeBocadillo = false;

if (ns6) { document.captureEvents(Event.MOUSEOVER); }
// define NS click capture
document.onmouseover = overButton // set up NS/IE click capture

function overButton(E) {
  if (ns6)
    test = E.target;
  else
    test = event.srcElement;
  if (activeButton) {  
    // Si hay uno activo y no forma parte del boton activo
    if (test.id.substr(0,14) != whichButton.id.substr(0,14)) {
      unhiliteButton();
      hideSubMenu(); //  whichButton;      Esto es para quitar el ultimo que  ha estado activo
      activeButton = false;
      whichButton = null;
    }
  }
  if (activeBocadillo) {
    // Si hay uno activo y no es la casilla del dia
    if ( (test.id != whichBocadillo.id) && (test.id.substr(0,12) != "cal_dia_nume") ) {
      hideBocadillo();
      activeBocadillo = false;
      whichBocadillo = null;
    }
  }
  isButton = ((test.tagName == "DIV" || test.tagName == "IMG" || test.tagName == "A") && test.id.substr(0,9) == "menu_vert" && test.id.substr(15,4) != "cont") ? 1 : 0;
  // Si es un boton del menu y no estaba ya encendido
  if (isButton) {
    whichButton = test;
    hiliteButton();
    showSubMenu();
    activeButton = true;
  }
  isCalDia = ((test.tagName == "DIV" || test.tagName == "TD") && test.id.substr(0,14) == "calendario_dia") ? 1 : 0;
  if (isCalDia) {
    whichBocadillo = test;
    showBocadillo();
    activeBocadillo = true;
  }
  if (isButton || isCalDia)
    return false;
  return true
}

function hiliteButton() {
  show(whichButton.id.substr(0,14) + "_ee6b01");
}

function unhiliteButton() {
  hide(whichButton.id.substr(0,14) + "_ee6b01");
}

function hideBocadillo() {
  // lo mas facil es ocultarlos todos
  hide("cal_dia_l_t");
  hide("cal_dia_r_t");
}

function showBocadillo() {  
  var whereNumber;
  var margenX = 3;
  var margenY = 3;
  switch(whichBocadillo.id.substr(15,1)) {
    case "0":
      // correccion del margen en lunes por la columna del numero de semana
      margenX = margenX - 14;
    case "1":
    case "2":
    case "3":
      whereNumber="l_t";
      break;
    case "4":
    case "5":
    case "6":
      whereNumber="r_t";
      break;
  }
  // si hay algo dentro y no es el tag del numero de semana (calendario_dia_X_X_w)
  hayAlgo = ( (whichBocadillo.innerHTML.length > 0 ) && (whichBocadillo.id.length < 19) )? 1 : 0;
  if (hayAlgo) {
    dia = parseInt(whichBocadillo.innerHTML);
    var numeDivObj = new getObj("cal_dia_nume_"+whereNumber);
    numeDivObj.obj.innerHTML = whichBocadillo.innerHTML;
    var diaContDivObj = new getObj("cal_dia_"+whereNumber+"_cont_text");
		var vacio = true;
		var entrenoHTML = "";
		var competiHTML = "";
    var cumplesHTML = "";
		var grupoEntrenoActual = "";
		var maskActual = parseInt("00000001",2);
		
		// Vaciamos el bocadillo
		diaContDivObj.obj.innerHTML = "";
		
		// el arrayEntrenos esta definido en carga_entr.php
		for( maskActual ; maskActual ; maskActual = ( maskActual << 1 ) & parseInt("11111111",2) ) {
			if( maskGrupoEntreno & maskActual ) {
				for( i=0 ; i < arrayEntrenos.length ; i++ ) {
					if( arrayEntrenos[i]['dia'] == dia && ( arrayEntrenos[i]['mask'] & maskActual ) ) {
						if( vacio ) {
							vacio = false;
						}

						if( grupoEntrenoActual != maskActual ) {
							j = 0;
							while( arrayGrupos[j]['mask_tipo'] != maskActual ) {
								j++;
							}
							
							entrenoHTML += "<div class='calendario_dia_cont_grupo'>Entrenamiento grupo " + arrayGrupos[j]['tipo'] + "</div>";
							grupoEntrenoActual = maskActual;
						}
				
						if( arrayEntrenos[i]['prioritario'] == "1" ){
							entrenoHTML += "<div class='calendario_dia_cont_titu_entr_p'>";
						}
						else {
							entrenoHTML += "<div class='calendario_dia_cont_titu_entr'>";
						}

						if( arrayEntrenos[i]['disciplina'] == "Descanso" ) {
							entrenoHTML += "Descanso.";
						}
						else {
							entrenoHTML += arrayEntrenos[i]['disciplina'];
							if( arrayEntrenos[i]['ritmo'] != "" ) {
								entrenoHTML += " (" + arrayEntrenos[i]['ritmo'] + ")";
							}
							entrenoHTML += ":";
						}	
						entrenoHTML += "</div>"
				
						if( arrayEntrenos[i]['prioritario'] == "1" ){
							entrenoHTML += "<div class='calendario_dia_cont_entr_p'>";
						}
						else {
							entrenoHTML += "<div class='calendario_dia_cont_entr'>";
						}
						entrenoHTML += (arrayEntrenos[i]['descripcion']).replace(/, /g,',<br>');
						entrenoHTML += "</div>"
	
						entrenoHTML += "<div class='calendario_dia_cont_entr_resu'>";
						if( arrayEntrenos[i]['minutos']!="0" ) {
							entrenoHTML += arrayEntrenos[i]['minutos'] + "', ";
						}
						
						if( arrayEntrenos[i]['distancia']!="0" ) {
							entrenoHTML += arrayEntrenos[i]['distancia'];
							switch ( arrayEntrenos[i]['disciplina'] ) {
								case "Bici":
									entrenoHTML += " km.<BR>";
									break;
								case "Carrera":
								case "Natación":
									entrenoHTML += " m.<BR>";
									break;
								case "Trabajo Muscular":
									entrenoHTML += " rep.<BR>";
									break;
							}
						}
						entrenoHTML += "</div>"
						
					}
				}
			}
		}

		// el arrayCompeticiones esta definido en carga_comp.php
		for( i=0 ; i < arrayCompeticiones.length ; i++ ) {
			if( arrayCompeticiones[i]['dia'] == dia ) {
				if( vacio ) {
					vacio = false;
				}

				competiHTML += "<div class='calendario_dia_cont_comp'>" + arrayCompeticiones[i]['nombre'] + "</div>";
				if( arrayCompeticiones[i]['cantidad_disciplinas'] ) {
					competiHTML += "<div class='calendario_dia_cont_entr_resu'>" 
					for( j=0 ; j < arrayCompeticiones[i]['cantidad_disciplinas'] ; j++ ) {
						competiHTML += arrayCompeticiones[i][ 'distancia' + (j + 1) ];
						switch ( arrayCompeticiones[i][ 'tipo' + (j + 1) ] ) {
							case "Bike":
								competiHTML += "km";
								break;
							case "Swim":
							case "Run":
								competiHTML += "m";
								break;
						}
						if( ( j + 1 ) != arrayCompeticiones[i]['cantidad_disciplinas'] ) {
							competiHTML += "/";
						}
					}
					competiHTML += "</div>";
				}
			}
		}

    // el arrayCumpleanyos esta definido en carga_cumples.php
    for( i=0 ; i < arrayCumpleanyos.length ; i++ ) {
      if( arrayCumpleanyos[i]['dia'] == dia ) {
        if( vacio ) {
          vacio = false;
        }

        cumplesHTML += "<div class='calendario_dia_cont_cumple'>" + arrayCumpleanyos[i]['nombre'] + " " + arrayCumpleanyos[i]['apellido'] + " cumple " + arrayCumpleanyos[i]['anyos'] + " a&#241;os</div>";
      }
    }
		
		if( !vacio ) {
			diaContDivObj.obj.innerHTML += entrenoHTML + competiHTML + cumplesHTML;
		}

		while( diaContDivObj.obj.offsetHeight < 60 ) {
			diaContDivObj.obj.innerHTML += "<BR>";
		}
		
		var bocadillo = new getObj("cal_dia_"+whereNumber);
    switch(whereNumber) {
      case "l_t":
        bocadilloPosX = findPosX(whichBocadillo) + margenX;
        bocadilloPosY = findPosY(whichBocadillo) + margenY;
        break;
      case "r_t":
        bocadilloPosX = findPosX(whichBocadillo) - bocadillo.obj.offsetWidth + whichBocadillo.offsetWidth - margenX;
        bocadilloPosY = findPosY(whichBocadillo) + margenY;
        break;
    }
    
    moveTo(bocadillo.style, bocadilloPosX, bocadilloPosY);
    show("cal_dia_"+whereNumber);
  }
}

function showSubMenu() {
  var margenSombra = 3;
  var subMenuObj = new getObj(whichButton.id.substr(0,14) + "_cont");
  var subMenuObj_fg = new getObj(whichButton.id.substr(0,14) + "_cont_fg");
  var subMenuObj_bg = new getObj(whichButton.id.substr(0,14) + "_cont_bg");
  var subMenuPosX = findPosX(whichButton) + whichButton.offsetWidth;
  var subMenuPosY = findPosY(whichButton) + whichButton.offsetHeight - subMenuObj.obj.offsetHeight;
  
  moveTo(subMenuObj.style, subMenuPosX, subMenuPosY);
  show(whichButton.id.substr(0,14) + "_cont");
  
  // Submenu sombra igual que el submenu
  subMenuObj_bg.style.height = subMenuObj_fg.obj.offsetHeight;
  subMenuObj_bg.style.width = subMenuObj_fg.obj.offsetWidth;
  subMenuPosX = findPosX(subMenuObj_fg.obj) + margenSombra; 
  subMenuPosY = findPosY(subMenuObj_fg.obj) + margenSombra; 
  moveTo(subMenuObj_bg.style, subMenuPosX, subMenuPosY);
  show(whichButton.id.substr(0,14) + "_cont_bg");
}    

function hideSubMenu() {
  hide(whichButton.id.substr(0,14) + "_cont");
  hide(whichButton.id.substr(0,14) + "_cont_bg");
}    

function showHelp() {
  showParent("help");
  copySource("help" + whichButton.id.substr(4), "helpText" );
  showParent("helpText");
}

function hideHelp() {
  hideParent("helpText");
  clearSource("helpText");
  hideParent("help");
}

function setHeadWidth() {
  //show("cabeceraFixed");
  //document.getElementById("cabeceraFixed").width = 100;
  //document.getElementById("cabeceraFixed").height = 100;
  //document.getElementById("cabeceraFixed").innerHTML = document.getElementById("tablaContent").contentWindow.document.body.innerHTML;
  //alert(document.getElementById("cabeceraFixed").width +" " + document.getElementById("tablaContent").contentWindow.document.body.scrollWidth);
  //alert( document.getElementById("cabeceraFixed").id + " " + document.getElementById("cabeceraFixed").style.clip );
  //cabeceraFixed.style.clip = "rect(0px 50px 50px 0px)"
  //alert( document.getElementById("cabeceraFixed").style.clip );
  //clipTo( cabeceraFixed.style , 0 , 100 , 100 , 0 );
  //  alert( document.getElementById("cabeceraFixed").style.clip );
}

function setSizes() {
  goSetHeight();
  setHeadWidth();
}

function init() {
  showMenuVertical();
}

function showMenuVertical() {
  var arrayObj = new Array();  
  var margenInferior = 50; // Margen entre el último boton y el minilogo prat-triatlo - Margen entre botones
  var margenEntreBoton = 8;
  var altoBoton = 20;
  var minilogoObj = new getObj("minilogo")
  
  for( i = arrayBotonesMenu.length - 1 ; i >= 0 ; --i ) {
    arrayObj[i] = new getObj(arrayBotonesMenu[i]);
    button_positionY = findPosY(minilogoObj.obj) - margenInferior - ((arrayBotonesMenu.length - i) * (altoBoton + margenEntreBoton));
    moveTo(arrayObj[i].style, 0, button_positionY);
    show(arrayBotonesMenu[i]);
  }
}

function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

var activeHistorial = false;
function showHistorial( triatleta ) {
  var historialActivoObj = new getObj("historial_activo");
  var historialTriatletaObj = new getObj("historial_"+triatleta+"_text");
  var nombreTriatletaObj = new getObj("historial_"+triatleta);

  if( activeHistorial != triatleta ) {
    if( activeHistorial ) {
      var activeTriatletaObj = new getObj("historial_"+activeHistorial);
      activeTriatletaObj.style.color = "#00214C";
    }
    activeHistorial = triatleta;
    historialActivoObj.obj.innerHTML = historialTriatletaObj.obj.innerHTML;

    nombreTriatletaObj.style.color = "#ffffff"
  }
}

// Funciones para rotar imagenes
function showNextNoticiaImage(images,destino,n,thumbSTR) {
  if ( !images[n] ) {
    if ( n <= 1 ) return;
    else n=0;
  }

  var contenedorDestino = new getObj(destino);
  var thumbOrigen = new getObj("foto_thumb"+thumbSTR+"_"+n);

  if ( thumbOrigen.obj.offsetHeight > thumbOrigen.obj.offsetWidth ) {
    contenedorDestino.obj.innerHTML = "<a href='" + images[n] + "' border=0 target='_blank'><img border=0 height=300 src='" + images[n] + "'></a>";
  }
  else {
    contenedorDestino.obj.innerHTML = "<a href='" + images[n] + "' border=0 target='_blank'><img border=0 width=300 src='" + images[n] + "'></a>";
  }
  setTimeout("showNextNoticiaImage( images" + thumbSTR + " , '" + destino + "', " + (++n) + ",'" + thumbSTR + "');",10000);
}

/******
var clipTop = 0;
var clipWidth = 170;
var clipBottom = 50;
var topper = 300;
var lyrheight = 0;
var time,amount,theTime,theHeight,DHTML;

function init()
{
	DHTML = (document.getElementById || document.all || document.layers)
	if (!DHTML) return;
	var x = new getObj('example');
	if (document.layers)
	{
		lyrheight = x.style.clip.bottom;
		lyrheight += 20;
		x.style.clip.top = clipTop;
		x.style.clip.left = 0;
		x.style.clip.right = clipWidth;
		x.style.clip.bottom = clipBottom;
	}
	else if (document.getElementById || document.all)
	{
		lyrheight = x.obj.offsetHeight;
		x.style.clip = 'rect('+clipTop+'px,'+clipWidth+'px,'+clipBottom+'px,0)';
	}
}

function scrollayer(layername,amt,tim)
{
	if (!DHTML) return;
	thelayer = new getObj(layername);
	if (!thelayer) return;
	amount = amt;
	theTime = tim;
	realscroll();
}

function realscroll()
{
	if (!DHTML) return;
	clipTop += amount;
	clipBottom += amount;
	topper -= amount;
	if (clipTop < 0 || clipBottom > lyrheight)
	{
		clipTop -= amount;
		clipBottom -= amount;
		topper += amount;
		return;
	}
	if (document.getElementById || document.all)
	{
		clipstring = 'rect('+clipTop+'px,'+clipWidth+'px,'+clipBottom+'px,0)';
		thelayer.style.clip = clipstring;
		thelayer.style.top = topper + 'px';
	}
	else if (document.layers)
	{
		thelayer.style.clip.top = clipTop;
		thelayer.style.clip.bottom = clipBottom;
		thelayer.style.top = topper;
	}
	time = setTimeout('realscroll()',theTime);
}

function stopScroll()
{
	if (time) clearTimeout(time);
}

******************************************************/

/*********************
  Ojo que los atributos y el style van por separado
  en dos objetos contenidos diferentes .obj y .style
*********************/
function getObj(name)
{
  if (document.getElementById)
  {
  	this.obj = document.getElementById(name);
	this.style = document.getElementById(name).style;
  }
  else if (document.all)
  {
	this.obj = document.all[name];
	this.style = document.all[name].style;
  }
  else if (document.layers)
  {
	this.obj = getObjNN4(document,name);
	this.style = this.obj;
  }
}

function getObjNN4(obj,name)
{
	var x = obj.layers;
	var foundLayer;
	for (var i=0;i<x.length;i++)
	{
		if (x[i].id == name)
		 	foundLayer = x[i];
		else if (x[i].layers.length)
			var tmp = getObjNN4(x[i],name);
		if (tmp) foundLayer = tmp;
	}
	return foundLayer;
}

