/*////////////////////////*/
/*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 = '';
            }
        }
    }
}

///////////////////////////////////////////////////
//FORCE RESET
///////////////////////////////////////////////////
forceReset = function (currentForm) {
	
	//alert(currentForm.length);
	
	
	//formElements = currentForm.elements[];
	
	for (var i=0; i<currentForm.length; i++) {
		output = ""
		+ "name = " + currentForm.elements[i].name + "\n"
		+ "value = " + currentForm.elements[i].value + "\n"
		+ "tagName = " + currentForm.elements[i].tagName + "\n"
		+ "type = " + currentForm.elements[i].type + "\n"
		+ "defaultValue = " + currentForm.elements[i].defaultValue + "\n"
		+ "";
		
		//alert(output);
		
		//Input Text Field
		if(currentForm.elements[i].type == "text") {
			currentForm.elements[i].value = "";
		}
		
		//File Field
		if(currentForm.elements[i].type == "file") {
			currentForm.elements[i].value = "";
		}
		
		//Password Field
		if(currentForm.elements[i].type == "password") {
			currentForm.elements[i].value = "";
		}
		
		//CheckBox Field
		if(currentForm.elements[i].type == "checkbox") {
			currentForm.elements[i].checked = false;
		}
		
		//Radio Field
		if(currentForm.elements[i].type == "radio") {
			currentForm.elements[i].checked = false;
		}
		
		//Select Field
		if(currentForm.elements[i].type == "select-one") {
			currentForm.elements[i].selectedIndex = 0;
		}
		
	}
}


///////////////////////////////////////////////////
//VENTANA PARA REDES SOCIALES
///////////////////////////////////////////////////
function socialWindow(zoomUrl) {
	
	//Init Vars
	wWidth = 626;
	wHeight = 436;
	
	properties = "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=" + wWidth + ", height=" + wHeight + ", left=10, top=10";
	mywin = window.open(zoomUrl,"win",properties);
	mywin.self.focus();
	
}

///////////////////////////////////////////////////
//CAROUSEL
///////////////////////////////////////////////////

//Init Vars
var slides = new Array();
var slidesID = new Array();
var initSlides = new Array();
var initPos =  new Number(0);
var setPos = initPos;
var incPos =  new Number(1);
var slideBottom =  new Number(8);
var slideSep =  new Number(0);
var slideSpeed =  new Number(16.5);
var distance =  new Number(0);
var carousel;
var innerOffset = new Number(75);
var carouselMoving = false;
var globeRightBound = new Number(-154);
var globeRightBoundB = new Number(-180);
var globeLefttBound = new Number(50);

		
startCarousel = function() {
	
	//First test CSS
	stylesDisabled = testCSS();
	
	if (document.getElementById("carouselContainer") != null && stylesDisabled == false) {
		
		carousel = document.getElementById("carouselContainer");
		carouselParent = carousel.parentNode;
		
		//get actual carusell width from parent
		carouselSize();
		//carouselWidth = carousel.offsetWidth;
			
		document.onmouseover = trackOverMouse;
		
		//Extrac DIV tags from carousel: ARRAY
		divTags = carousel.getElementsByTagName("li");
		divTagsLength = divTags.length;
		
		//Obtain DIV with ID and store them in ARRAY "slides"
		for (var i=0; i<divTagsLength; i++) {
			//only add elements with ID
			if (divTags[i].id != "") {
				slideToPush = document.getElementById(divTags[i].id);
				slides.push(slideToPush);
			}
		}
		slidesLength = slides.length;
		
		
		//Obtain ID from Slides and store them in an ARRAY
		for (var i=0; i<slidesLength; i++) {
			//slides[i].style.width = slides[i].firstChild.width + "px";
			slidesID.push(slides[i].id);
		}
		
		
		//define distance to travel each time the carousel moves
		//it will be less than the width from corousel minus the width from an slide minus "separator"
		for (var i=0; i<slidesLength; i++) {
			if (distance < (carouselWidth - (slides[i].offsetWidth + slideSep))) {
				distance += (slides[i].offsetWidth + slideSep);
			}
		}
		//alert("distance = " + distance);
			
		//Make a Multidimensional Array 
		for (var 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) {//if NOT the last one, order sequentially
					initSlides[i].position = setPos;
					setPos = setPos + slides[i].offsetWidth + slideSep;
				}
				else {//if IT'S the last one, then place as the first one
					initSlides[i].position = initSlides[0].position - initSlides[i][1] - slideSep;
					//alert("initSlides[1].position = " + initSlides[i].position); 
				}
		
		}
		
		//alert(slidesID);
		//alert(initSlides[1]);
		
		//define position and properties for each SLIDE
		for (var i=0; i<slides.length; i++) {
			
			//Obtain Div Tags inside each "Item"
			var itemNodes = slides[i].childNodes;
			
			//alert("itemsDivs found in " + slides[i].id + " = " + itemNodes.length);
			
			//Extract TITULO, PVP, ANCHOR, IMAGEN, DESCRIPCION from each SLIDE
			for (var j=0; j<itemNodes.length; j++) {
				
				//alert(itemNodes[j].tagName + " || " + itemNodes[j].className);
				
				//Titulo
				if(itemNodes[j].className == "titBlock") {
					slides[i].itemTitle = itemNodes[j];
					//alert("titBlock = " + itemNodes[j].innerHTML );
					//slides[i].removeChild(itemNodes[j]);
				}
				
				//pvp
				if(itemNodes[j].className == "pvp" || itemNodes[j].className == "pvp oferta" ) {

					slides[i].itemPvp = itemNodes[j];
					
					if(itemNodes[j].className == "pvp oferta") {
						slides[i].classOferta = true;
					}
					else if (itemNodes[j].className == "pvp") {
						slides[i].classOferta = false;
					}
					
					//alert("pvp = " + itemNodes[j].innerHTML);
					//slides[i].removeChild(itemNodes[j]);
				}

				//anchor
				if(itemNodes[j].className == "vermas") {
					slides[i].itemAnchor = itemNodes[j];
					slides[i].itemAnchorHref = itemNodes[j];
					//alert("anchor = " + itemNodes[j].href);
					//slides[i].removeChild(itemNodes[j]);
				}
				
				//Imagen
				if(itemNodes[j].className == "imagen") {
					slides[i].itemImage = itemNodes[j];
					//alert("imagen = " + itemNodes[j].innerHTML );
					//slides[i].removeChild(itemNodes[j]);
					
					//set behavior for image Anchor
					var itemImageNodes =  slides[i].itemImage.childNodes;
					
					for (var k=0; k<itemImageNodes.length; k++) {
						if(itemImageNodes[k].tagName == "A") {
							itemImageNodes[k].setAttribute('onmouseover','showToolTip(this);');
							//itemImageNodes[k].innerHTML = "<h5 style=\"font-size: 15px; line-height: 16px;\">Book Number: " + slides[i].id + "</h5>";
						}
					}
				}
				
				//Descripcion
				if(itemNodes[j].className == "descripcion hide") {
					slides[i].itemDescripcion = itemNodes[j];
					//alert("descripcion = " + itemNodes[j].innerHTML );
					//slides[i].removeChild(itemNodes[j]);
				}
			
			}
			
			//Remove TITULO, PVP, ANCHOR, IMAGEN, DESCRIPCION from each slide
			for (var j=0; j<itemNodes.length; j++) {
				//alert("nodeName = " + itemNodes[j].nodeName + "  || childNodes  = " +  itemNodes[j].childNodes.length);
				slides[i].removeChild(itemNodes[j]);
				j -=1;
			}
			
			
						
			//create a container "globe" TITULO, PVP, y ANCHOR in each SLIDE	
			//Insert "globe"
			var newTag = document.createElement('DIV');
			newTag.setAttribute('class','globe');
			
				//setAttribute Explorer
				if (navigator.appName.indexOf("Explorer") > 0 && (navigator.userAgent.indexOf("MSIE 6") > 0 || navigator.userAgent.indexOf("MSIE 7") > 0)) {
					newTag.setAttribute('className','globe');
				}
			
			newTag.innerHTML = ""
			+ "\n<div class=\"titBlock\">\n" + slides[i].itemTitle.innerHTML + "</div>\n";
			
			if (slides[i].classOferta == true) {
				//alert("is oferta");
				newTag.innerHTML += "\n<p class=\"pvp oferta\">\n" + slides[i].itemPvp.innerHTML + "</p>\n";
			}
			else {
				//alert("isn't oferta");
				newTag.innerHTML += "\n<p class=\"pvp\">\n" + slides[i].itemPvp.innerHTML + "</p>\n";
			}
			
			newTag.innerHTML += "\n<a href=\"" + slides[i].itemAnchorHref + "\" class=\"vermas\">\n" + slides[i].itemAnchor.innerHTML + "</a>\n";
			
			slides[i].appendChild(newTag);
			
		
			//create a container for IMAGEN			
			//Insert Imagen
			var newTag = document.createElement('P');
			newTag.setAttribute('class','imagen');
			
				//setAttribute Explorer
				if (navigator.appName.indexOf("Explorer") > 0 && (navigator.userAgent.indexOf("MSIE 6") > 0 || navigator.userAgent.indexOf("MSIE 7") > 0)) {
					newTag.setAttribute('className','imagen');
				}
			
			newTag.innerHTML = ""
			+ slides[i].itemImage.innerHTML + "\n";
			
			slides[i].appendChild(newTag);
			
			
			//create a container for DESCRIPCION			
			//Insert Descripcion
			var newTag = document.createElement('DIV');
			newTag.setAttribute('class','descripcion hide');
			
				//setAttribute Explorer
				if (navigator.appName.indexOf("Explorer") > 0 && (navigator.userAgent.indexOf("MSIE 6") > 0 || navigator.userAgent.indexOf("MSIE 7") > 0)) {
					newTag.setAttribute('className','descripcion hide');
				}
			
			newTag.innerHTML = ""
			+ slides[i].itemDescripcion.innerHTML + "\n";
			
			slides[i].appendChild(newTag);
			
			
			//Finally positioning each Slide
			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]);	
			
		//test values
		//testVars(initSlides[0].position,"--","--","--","--");
		
		//Define carousel BOUNDS
		//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);
		
		//create a containers for "CONTROLS" and insert them inside carouselParent
		var newTag = document.createElement('DIV');
		newTag.setAttribute('class','controls');
		newTag.setAttribute('id','controlPrev');
		
		//setAttribute Explorer
		if (navigator.appName.indexOf("Explorer") > 0 && (navigator.userAgent.indexOf("MSIE 6") > 0 || navigator.userAgent.indexOf("MSIE 7") > 0)) {
			newTag.setAttribute('className','controls');
		}
		
		newTag.innerHTML = ""
		+ "\n<a href=\"#\" onclick=\"move = dammitMove('forth'); return false;\"><strong class=\"hide\">&lt;&lt;</strong></a>\n";
		
		carouselParent.appendChild(newTag);
		
		var newTag = document.createElement('DIV');
		newTag.setAttribute('class','controls');
		newTag.setAttribute('id','controlNext');
		
		//setAttribute Explorer
		if (navigator.appName.indexOf("Explorer") > 0 && (navigator.userAgent.indexOf("MSIE 6") > 0 || navigator.userAgent.indexOf("MSIE 7") > 0)) {
			newTag.setAttribute('className','controls');
		}
		
		newTag.innerHTML = ""
		+ "\n<a href=\"#\" onclick=\"move = dammitMove('back'); return false;\"><strong class=\"hide\">&gt;&gt;</strong></a>\n";
		
		carouselParent.appendChild(newTag);
		
		//carousel finished, carousel visible (hidden before via CSS)
		carousel.style.visibility = "visible";
	}
}


function updatePos(){
	 
	var stoppingCount = 0;
		
	for (var 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);
			//Clear Interval
			clearInterval(moveInterval);
			//Set NO MOVEMENT from the 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;
	
	//If the last element from carousel is NOT moving then is allowed to move again
	if (initSlides[initSlides.length - 1].moving == false) { 
		
		//alert ("initSlides[initSlides.length - 1].moving = " + initSlides[initSlides.length - 1].moving);
			
		for (var i=0; i<initSlides.length; i++) {
			
			//If carousel is NOT moving them move it
			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);
  	 	}
		
		//FORWARD movement (if position is bigger than RIGHTBOUND)
		if (position >= rightBound && direction == "forth") {
			//update target
			target = (target - position) + (position - rightBound) + leftBound;
			//update position
			position = (position - rightBound) + leftBound;
			}
		
		//BACKWARD movement (if position is lesser than LEFTBOUND )	
		if (position <= leftBound && direction == "back") {
			//update target
			target = (target - position) + (position - leftBound) + rightBound;
			//update position
			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") {//If the item doesn't exist
			currentBook = book.parentNode.parentNode;
			currentBookWidth = currentBook.offsetWidth;
			checkGlobe = findGlobe(currentBook, currentBookWidth);
			//alert("currentBook = " + parentItem.innerHTML);
			//alert("currentBook = " + currentBook.id);
			
		}
		else { //it exist and is different
			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;
				currentBookWidth = currentBook.offsetWidth;
				checkGlobe = findGlobe(currentBook, currentBookWidth);
			}
		}  
	}
	//alert("OverBook");
	//currentBook.style.background = "#000000";
	
}

findGlobe = function (currentBook, currentBookWidth) {
	
	parentDivs = currentBook.getElementsByTagName("div");
		
	//Obtain DIV tag that contains information abotu the item "GLOBE"
	for (var i=0; i<parentDivs.length; i++) {
		//Only add elements tah have ID attribute
		if (parentDivs[i].className == "globe" || parentDivs[i].className == "globe globeRight") {
			parentGlobe = parentDivs[i];
		}
	}
		
	currentGlobe = parentGlobe;
	
	//Define "Globe" position
	
	//Find position of "currentBook"
	bookPosition = parseFloat(currentBook.style.left);
	//alert("bookPosition  = " + bookPosition);
	
	//If item position is bigger than half width of the carousel
	if(bookPosition >= (carouselWidth / 2)) {
		
		var testFitting = (bookPosition + currentBookWidth + slideSep);
		parentGlobe.className = "globe globeRight";
		//alert("bookPosition = " + bookPosition + "\n testFitting = " + testFitting + "\n carouselWidth = " + carouselWidth);
		
		
		if (testFitting < carouselWidth) {	
			//alert("bookPosition = " + bookPosition + "\n testFitting = " + testFitting + "\n carouselWidth = " + carouselWidth);
			parentGlobe.style.left = globeRightBound + "px";
		}
		else {
			parentGlobe.style.left = globeRightBoundB + "px";	
		}

	}
	else {
		parentGlobe.style.left = globeLefttBound + "px";
		parentGlobe.className = "globe";
	}
		
		
	//alert("parentGlobe = " + parentGlobe.innerHTML);
	//parentGlobe.style.background = "#FF09DF";
	parentGlobe.style.display = "block";	
	currentBook.style.zIndex = "10";
		
	showingTip = true;
		
}

var trackCounter = new Number(0);

//Check if Mouse pointer is inside the item
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") {
		
		//Check the parent Parent
		var checkParent = findParentBook(currentBook.id,targetElement);
		//alert("matchID after Showing = " + matchID);
		//alert("overChild = " + checkParent.overChild);
		
		//give a little time before hidding the 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");
		}
				
	}
	
	
	trackCounter += 1;
	//testVars ("tracking: " + trackCounter);
	
}
	

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") {
		//Define the max level to find the PARENT (HTML)		
		if(testObj.tagName == "HTML") {
			//alert("BODY FOUND!!");
			break;	
		}
		//if parent match
		if(testObj.getAttribute('id') == bookID) {
			matchID = true;
			hidding = false;
			break;
		}
		
		matchID = false;
		testObj = testObj.parentNode;
		count++;	
	}
	
	//return 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;
}


//Check carousel size
carouselSize = function () {
	
	stylesDisabled = testCSS();
	
	if (document.getElementById("carouselContainer") != null && stylesDisabled == false) {
		var itemWidth = new Number(127);
		var itemNumber = Math.floor((carouselParent.offsetWidth - innerOffset)/127)
		var sepNumber = itemNumber - 1;
		carouselWidth = (itemNumber*itemWidth) + (sepNumber*slideSep);
		//carouselWidth = (carouselParent.offsetWidth) - innerOffset;
		carousel.style.width = carouselWidth + "px";
		//alert(carouselParent.offsetWidth + "||" + carouselWidth);
		carousel.style.left = (Math.ceil((carouselParent.offsetWidth - carouselWidth)/2)) + "px";
		//testVars(carouselWidth, carousel.id ,carousel.style.width);
	}
}


//verify CSS is active (Generic function)
function testCSS() {
	var cssdisabled = false; // must be proven otherwise
	var testcss = document.createElement('div');
	
	testcss.innerHTML = "testing...";
	
	
	testcss.style.position = "absolute";
	document.getElementsByTagName("body")[0].appendChild(testcss);
	if (testcss.currentStyle) {
		var currstyle = testcss.currentStyle["position"];
		//alert(currstyle);
	}
	else if (window.getComputedStyle) {
		//alert(currstyle);
		var currstyle = document.defaultView.getComputedStyle(testcss, null).getPropertyValue("position");
		
	}
	var cssdisabled = (currstyle == "static") ? true : false;
	document.getElementsByTagName("body")[0].removeChild(testcss);
	//alert(cssdisabled);
	
	return cssdisabled;
}


//Test vars
//testVars = function (tracking) {




testVars = function (carouselParentWidth, carouselID, carouselWidth) {

	var outPutVars = ""
	
	+ '<strong>CAROUSEL WIDTH</strong><br />'
	+ '<strong>'
	+ 'carouselParentWidth=' + carouselParentWidth + '<br />'
	+ 'carouselID =' + carouselID + '<br />'
	+ 'carouselWidth =' + carouselWidth + '<br />'
	+ '<br /></strong>';
	
	if (document.getElementById("testVars") == null) {
		var newTag = document.createElement('DIV');
		newTag.setAttribute('id','testVars');
		var tContainer = document.getElementById("colDestacados");
		var TCNodes = tContainer.children;
		var TCNodesLength = TCNodes.length - 1;
		tContainer.insertBefore(newTag, tContainer.firstChild);
		newTag.innerHTML = outPutVars;
	}
	else {
		var newTag = document.getElementById("testVars");
		newTag.innerHTML = outPutVars;
	}

	

}


//Initial setUp
setUpPage = function() {

	//carousel
	startCarousel();
	
} 

window.onload = setUpPage;
window.onresize = carouselSize;
