/*////////////////////////*/
/*Google Boooks Preview*/
/*////////////////////////*/

function ProcessGBSBookInfo(booksInfo) {
	
    for (isbn in booksInfo) {
        var element = document.getElementById(isbn);
        var bookInfo = booksInfo[isbn];
          
        if (bookInfo) {
  
            //element.href = bookInfo.preview_url;
            if (bookInfo.preview == "full" ||
                bookInfo.preview == "partial") {
                element.style.display = '';
            }
        }
    }
}



/*////////////////////////*/
/*Coloco elementos con POSICION ABSOLUTA contenidos en elementos de ANCHO/ALTO IMPAR (Explorer) */
/*////////////////////////*/

adjustFrameBorders = function(classN) {
	
	//Obtengo todos los Tag SPAN de los elementos con CLASE "classN"
	var spanTags = new Array();
	
	//alert("adjustFrameBorders");

	docDivs = document.getElementsByTagName("div");
	for (var i=0; i<docDivs.length; i++) {
		//docDivs[i].style.background = "#00ff00";
		if (docDivs[i].className == classN) {
			
			//alert("target found!!" + docDivs[i].innerHTML);

			var frameTag = docDivs[i];
			var frameSpanTags = docDivs[i].getElementsByTagName("SPAN");
			
			setCornerPosition(frameTag,frameSpanTags);

			
		}
		
	}
	
}


setCornerPosition = function(frameTag,frameSpanTags)	{
	
	//alert("setCornerPosition");

	//coloco apropiadamente
	for (var i=0; i<frameSpanTags.length; i++) {
		if (frameSpanTags[i].className == "topRight") {
			var parentWidth = frameSpanTags[i].parentNode;
			parentWidth = parentWidth.offsetWidth;
			//alert("parentWidth = " + parentWidth);
			var spanWidth = frameSpanTags[i].offsetWidth;
			//alert("spanWidth = " + spanWidth);
			frameSpanTags[i].style.left = (parentWidth - spanWidth) + "px";
		}
		if (frameSpanTags[i].className == "bttmLeft") {
			var parentHeight = frameSpanTags[i].parentNode;
			parentHeight = parentHeight.offsetHeight;
			//alert("parentHeight = " + parentHeight);
			var spanHeight = frameSpanTags[i].offsetHeight;
			//alert("spanHeight = " + spanHeight);
			//alert((parentHeight - spanHeight) + "px");
			frameSpanTags[i].style.top = (parentHeight - spanHeight) + "px";
		}
		if (frameSpanTags[i].className == "bttmRight") {
			frameSpanTags[i].style.left = (parentWidth - spanWidth) + "px";
			frameSpanTags[i].style.top = (parentHeight - spanHeight) + "px";
		}
		
		//Un bordes solamente (Items Derecha (Noticias)/Publicidad Derecha)
		if (frameSpanTags[i].className == "bttm") {
			var parentHeight = frameSpanTags[i].parentNode;
			parentHeight = parentHeight.offsetHeight;
			var spanWidth = frameSpanTags[i].offsetWidth;
			var spanHeight = frameSpanTags[i].offsetHeight;
			/*
			alert("parentHeight = " + parentHeight);
			alert("spanHeight = " + spanHeight);
			alert("Top = " + (parentHeight - spanHeight));
			*/
			frameSpanTags[i].style.top = (parentHeight - spanHeight) + "px";
		}
		
	}
}


/*////////////////////////*/
/*Busqueda rapida*/
/*////////////////////////*/

setUpSimpleSearch = function () {
	
	//Init Vars
	var defaultText = "buscar...";
		
	var searchContainer = document.getElementById("buscar");
	var searchForms = searchContainer.getElementsByTagName("form");
	var containerTags = searchContainer.getElementsByTagName("input");
	var inputTextFields = new Array;
	
	searchForm = searchForms[0];
	
	//alert(containerTags.length);
	
	//Busco campo y formateo y aņado eventos
	for(var i=0; i<containerTags.length; i++) {
		var tagAttributes = containerTags[i].attributes;
		//alert(tagAttributes.length);
		for(var j=0; j<tagAttributes.length; j++) {
			if(tagAttributes[j].name == "type" && tagAttributes[j].value == "text") {
				containerTags[i].value = defaultText;
				containerTags[i].defaultText = defaultText;
				
				inputTextFields.push(containerTags[i]);
				
				addEvent(containerTags[i]);
			}
		}
	}
	
	//aņado eventos al formulario
	searchForm.onsubmit = function () {
		
		for(var i=0; i<inputTextFields.length; i++) {
			if(inputTextFields[i].value == defaultText) {
				inputTextFields[i].value = "";
				//alert(inputTextFields[i].value);	
			}
		}
		
	}

}

//Eventos del campo "input text"
addEvent = function(field) {
	
	field.onclick = function () {
		field.value = "";
	}
	field.onblur = function () {
		if (field.value == "") {
			field.value = field.defaultText;
		}
	}
	
}


///////////////////////////////////////////////////
//MENU TIPO FICHA EN EXPLORER ("Efecto Folder")
///////////////////////////////////////////////////

//Se aņade una clase a los LI para que el efecto en CSS funcione
startList = function() {
	if (document.all&&document.getElementById && document.getElementById("mainMenu") != null) {
		navRoot = document.getElementById("mainMenu");
		//alert (document.getElementById("mainMenu"));
		for (var 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", "");
				}
				node.onmouseout=function() {
					this.className=this.className.replace(" over", "");
				}
				//alert (i);
			}
		}
	}
}


///////////////////////////////////////////////////
//FORMULARIO BOLETIN
///////////////////////////////////////////////////

setUpCheckBoxEvents = function (leadCheckBox, checkBoxes) {
	
		//alert(checkBoxes);
		
		var checkBoxes = checkBoxes.split(",");
		
		//alert("click!! " + checkBoxes.length);
		

		if(leadCheckBox.checked == true) {
			for (var i=0; i<checkBoxes.length; i++) {
				var checkBoxTag = document.getElementById(checkBoxes[i]);
				checkBoxTag.checked = true;
			}
		}
		else {
			for (var i=0; i<checkBoxes.length; i++) {
				var checkBoxTag = document.getElementById(checkBoxes[i]);
				checkBoxTag.checked = false;
			}
		}

	
}


///////////////////////////////////////////////////
//CAROUSEL
///////////////////////////////////////////////////

//Init Vars
var slides = new Array();
var slidesID = new Array();
var initSlides = new Array();
var initPos = 0;
var setPos = initPos;
var incPos = 1;
var slideBottom = 15;
var slideSep = 6;
var slideSpeed = 8.5;
var distance = 0;
var carousel;
var carouselMoving = false;

		
startCarousel = function() {
	
	if (document.getElementById("carouselContainer") != null) {
	
		carousel = document.getElementById("carouselContainer");
		carouselWidth = carousel.offsetWidth;
		
		carouselVisibleArea = carousel.offsetWidth;
		//alert("carouselVisibleArea = " + carouselVisibleArea);
		
		//Extraigo los tags DIV del carousel ARRAY
		divTags = carousel.getElementsByTagName("div");
		divTagsLength = divTags.length;
		
		//Obtengo DIV con ID Los guardo en un ARRAY "slides"
		for (i=0; i<divTagsLength; i++) {
			//solo aņado los elementos que tienen ID
			if (divTags[i].id != "") {
				slideToPush = document.getElementById(divTags[i].id);
				slides.push(slideToPush);
			}
		}
		slidesLength = slides.length;
		
		//Obtengo el ID de los Slides y Lo guardo en un ARRAY
		for (i=0; i<slidesLength; i++) {
			//slides[i].style.width = slides[i].firstChild.width + "px";
			slidesID.push(slides[i].id);
		}
		
		//defino la distancia a recorrer cada vez que avanza el carrusel
		//sera menor que el ancho del carrusel menos el de un slide menos el separador
		for (i=0; i<slidesLength; i++) {
			if (distance < (carouselWidth - (slides[i].offsetWidth + slideSep))) {
				distance += (slides[i].offsetWidth + slideSep);
			}
		}
		//alert("distance = " + distance);
			
		//Compongo Array Multidimensional
		for (i=0; i<slides.length; i++) {
				initSlides.push(new Array(slidesID[i], slides[i].offsetWidth, slides[i].offsetHeight));
				initSlides[i].moving = false;
				
				//alert("initSlides = " + initSlides);
				
				if (i != slides.length - 1) {//si NO es el ultimo ordeno secuelcialmente
					initSlides[i].position = setPos;
					setPos = setPos + slides[i].offsetWidth + slideSep;
				}
				else {//si SI es el ultimo coloco antes del primero
					initSlides[i].position = initSlides[0].position - initSlides[i][1] - slideSep;
					//alert("initSlides[1].position = " + initSlides[i].position); 
				}
		
		}
		
		//alert(slidesID);
		//alert(initSlides[1]);
		
		//posiciono y defino propiedades para cada SLIDE
		for (i=0; i<slides.length; i++) {
			slides[i].style.position = "absolute";
			slides[i].style.display = "block";
			slides[i].style.bottom = slideBottom + "px";
			slides[i].style.left = initSlides[i].position + "px";
		}
		
		//alert (firstSlide[1] + "||" + lastSlide[0]);	
			
		//compruevo los valores
		//testVars(initSlides[0].position,"--","--","--","--");
		
		//Defino BOUNDS del carousel
		//alert(initSlides.length - 1);
		rightBound = initSlides[initSlides.length - 2].position + initSlides[initSlides.length - 2][1] + slideSep;
		leftBound = (initPos - initSlides[0][1] - slideSep);
		//alert ("rightBound established = " + rightBound);
		
	}
}


function updatePos(){
	 
	var stoppingCount = 0;
		
	for (i=0; i<initSlides.length; i++) {
		initSlides[i].position = initSlides[i].startMove.moveIt()[1];
		initSlides[i].target = initSlides[i].startMove.moveIt()[0];
		mSlide = document.getElementById(initSlides[i][0]);
		mSlide.style.left = initSlides[i].position + "px";
		//mSlide.style.top  = -30 + 'px';
		
		if (initSlides[i].position == initSlides[i].target) {
			//alert("target clearInterval HELL= " + initSlides[i].target + " and moving = " + initSlides[i].moving);
			//Borro el Interval
			clearInterval(moveInterval);
			//Establesco que no hay movimiento del carousel
			initSlides[i].moving = false;
			
		}
		
		//Chech if coruosel has fully stopped
		if (initSlides[i].moving == false) {
			stoppingCount += 1;
			if (stoppingCount == initSlides.length) {
				//alert("carousel has stopped");
				carouselMoving = false;
			}
		}
	}

}

    
 function dammitMove (direction) {
	
	carouselMoving = true;
	
	//Si el ultimo elemento del carousel NO se mueve entonces muevo	
	if (initSlides[initSlides.length - 1].moving == false) { 
		
		//alert ("initSlides[initSlides.length - 1].moving = " + initSlides[initSlides.length - 1].moving);
			
		for (i=0; i<initSlides.length; i++) {
			
			//si NO se mueve el carousel lo muevo
			if (direction == "forth") {
				initSlides[i].target = distance + initSlides[i].position;
			}
	  		else {
				initSlides[i].target = (-distance) + initSlides[i].position;
			}
			
			initSlides[i].moving =  true;
		
			initSlides[i].startMove = new itemMovement(initSlides[i].position, initSlides[i].target, slideSpeed, direction);
			//alert(initSlides[i] + " :: moving = " + initSlides[i].moving + " :: position = " + initSlides[i].position + " :: target = " + initSlides[i].target + ":: speed = " + slideSpeed + ":: direction =" + direction);
		}
	
		moveInterval = setInterval( function() { updatePos(); }, 50 );
		
	}
	
}
 

function itemMovement(position, target, slideSpeed, direction){
	
	this.moveIt = function(){
	
		position += (target - position) / slideSpeed;
   	unRoundPosition = position;
   	if (direction == "forth") {
   		position = Math.ceil(position);
   	}
  	 	else if (direction == "back") {
  	 		position = Math.floor(position);
  	 	}
		
		//hacia ADELANTE (si la posicion es mayor que RIGHTBOUND)
		if (position >= rightBound && direction == "forth") {
			//actualizo el target
			target = (target - position) + (position - rightBound) + leftBound;
			//actualizo la posicion
			position = (position - rightBound) + leftBound;
			}
		
		//hacia atras (si la posicion es menor que LEFTBOUND )	
		if (position <= leftBound && direction == "back") {
			//actualizo el target
			target = (target - position) + (position - leftBound) + rightBound;
			//actualizo la posicion
			position = (position - leftBound) + rightBound;
			//alert ("BACKWARD position = " + position);
			}

   	//testVars(position,target,slideSpeed,unRoundPosition);
   	
   	//Check if there's any ToolTip visible
   	if(typeof(currentBook) != "undefined") {
			clearTimeout(showTimer);
			hideToolTip();
   	}
		
		return [target,position];
  }
  
	
}

//TOOLTIP
var hiddingTime = 500;

showToolTip = function(book) {
	
	
	//Check if the carousel is NOT moving
	if (carouselMoving != true) {
		if(typeof(currentBook) == "undefined") {//Si no existe el Libro
			currentBook = book.parentNode.parentNode;
			checkGlobe = findGlobe(currentBook);
			//alert("currentBook = " + parentItem.innerHTML);
			//alert("currentBook = " + currentBook.id);
			
		}
		else { //si existe y es diferente
			if(book.parentNode.parentNode != currentBook) {
				//alert("book before = " + currentBook.id + "\n book after = " + book.parentNode.parentNode);
				previousGlobe = currentGlobe;
				previousBook = currentBook;
				previousGlobe.style.display = "none";
				previousBook.style.zIndex = "0";
				currentBook = book.parentNode.parentNode;
				checkGlobe = findGlobe(currentBook);
			}
		}   
	}
	//alert("OverBook");
	//currentBook.style.background = "#000000";
	
}

findGlobe = function (currentBook) {
	
	parentDivs = currentBook.getElementsByTagName("div");
		
	//Obtengo el DIV que contiene la informacion del libro "GLOBE"
	for (i=0; i<parentDivs.length; i++) {
		//solo aņado los elementos que tienen ID
		if (parentDivs[i].className == "globe" || parentDivs[i].className == "globe globeRight") {
			parentGlobe = parentDivs[i];
		}
	}
		
	currentGlobe = parentGlobe;
	
	//defino la posicion de "Globe"
	
	//Encuentro la posicion de "currentBook"
	bookPosition = currentBook.style.left;
	bookPositionString = bookPosition.indexOf("p");
	bookPosition = bookPosition.substring(0,bookPositionString);
	//alert("bookPosition  = " + bookPosition);
	
	//si la posicion del libro es mayor a la mitad del carousel
	if(bookPosition >= (carouselWidth / 2)) {
		//alert(parentGlobe.style.display);
		parentGlobe.style.left = -140 + "px";
		parentGlobe.className = "globe globeRight";
	}
	else {
		parentGlobe.style.left = "50px";
		parentGlobe.className = "globe";
	}
		
		
	//alert("parentGlobe = " + parentGlobe.innerHTML);
	//parentGlobe.style.background = "#FF09DF";
	parentGlobe.style.display = "block";	
	currentBook.style.zIndex = "10";
		
	showingTip = true;
		
}


//Monitoreo si el Mouse esta dentro o fuera del Libro
function trackOverMouse(e){
	var trackEvent = (e)?e:event;
   var targetElement = (trackEvent.srcElement)?trackEvent.srcElement:trackEvent.target;
	//alert("tracking Mouse" + targetElement.parentNode.parentNode.id);
	//alert("targetElement.id" +  targetElement.id);
	
	if(typeof(currentBook) != "undefined") {
		
		//Compruebo el Parent
		var checkParent = findParentBook(currentBook.id,targetElement);
		//alert("matchID after Showing = " + matchID);
		//alert("overChild = " + checkParent.overChild);
		
		//doy un margen de tiempo antes de ocultar el ToolTip
		if (currentBook.id != checkParent.overParent) {
			if (typeof(showTimer) == "undefined") {
				showTimer = setTimeout( function() { hideToolTip(); }, hiddingTime );
			}
			//alert("different");
		}
		else if (typeof(showTimer) != "undefined" && currentBook.id == checkParent.overParent) {
			clearTimeout(showTimer);
			showTimer = undefined;
			//alert("equal");
		}
				
	}
	
}
	

function findParentBook(bookID, childObj) {
	var testObj = childObj;
	var count = 1;
	var matchID = false;
	var hidding = true;
	//alert(testObj.tagName + "||" + testObj.className);
	
	while(testObj.getAttribute('id') != "carousel") {
		//Defino el nivel maximo para buscar el PARENT (HTML)		
		if(testObj.tagName == "HTML") {
			//alert("BODY FOUND!!");
			break;	
		}
		//si el padre coincide
		if(testObj.getAttribute('id') == bookID) {
			matchID = true;
			hidding = false;
			break;
		}
		
		matchID = false;
		testObj = testObj.parentNode;
		count++;	
	}
	
	//Devuelvo variables
	return {bookID : bookID, matchID : matchID, overChild : childObj.id, overParent : testObj.getAttribute('id'), hidding : hidding};
	
}

hideToolTip = function() {
	//alert("hidding toolTip");
	currentGlobe.style.display = "none";
	currentBook.style.zIndex = "0";
	currentBook = undefined;
	showTimer = undefined;
}




document.onmouseover = trackOverMouse;



//Initial setUp
setUpPage = function() {
	//alert ("settingUp!!");
	
	//Texto Busqueda rapida
	setUpSimpleSearch();
	
	//Menu tipo Ficha en Explorer
	startList();

	//adjustFrameBorders
	if (navigator.appName.indexOf("Explorer") > 0 && navigator.userAgent.indexOf("MSIE 6.0") > 0) {
		adjustFrameBorders("publicidad");
	}

	//carousel
	startCarousel();
	

} 

window.onload = setUpPage;

