/*////////////////////////*/
/*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();
	
}





///////////////////////////////////////////////////
//BUSQUEDA RAPIDA
///////////////////////////////////////////////////

startQuickSearch = function (quickSearch) {
	
	if (document.getElementById(quickSearch) != null) {
		//Init Vars
		var defaultText = "Buscar...";
			
		var searchContainer = document.getElementById("buscar");
		var containerTags = searchContainer.getElementsByTagName("input");
		var inputTextFields = new Array;
		
		searchForm = searchContainer;
		
		//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;
		}
	}
	
}


///////////////////////////////////////////////////
//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(18);
var slideSep =  new Number(3);
var slideSpeed =  new Number(16.5);
var distance =  new Number(0);
var carousel;
var carouselMoving = false;
var globeRightBound = new Number(-154);
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;
		carouselWidth = carousel.offsetWidth;
		
		document.onmouseover = trackOverMouse;
		
		carouselVisibleArea = carousel.offsetWidth;
		//alert("carouselVisibleArea = " + carouselVisibleArea);
		
		//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);');
						}
					}
				}
				
				//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)
		//alert(carousel.id);
		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)) {
		//alert(parentGlobe.style.display);
		parentGlobe.style.left = globeRightBound + "px";
		parentGlobe.className = "globe globeRight";
	}
	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;
}



//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;
}


///////////////////////////////////////////////////
//EXPANDABLE MENU
///////////////////////////////////////////////////

//Init Vars
var activeSmenus = new Array();
var expandSpeed = 3.1;
var removeActiveSmenu = new Boolean(false);
var animating = new Boolean (false);
var bkgImage = "";

//Encuentro los menus Secundarios y obtengo su altura inicial
startIzqMenus =  function (izqMenu) {
	

	
	if (document.getElementById(izqMenu) != null) {
		
		var izqMenu = document.getElementById(izqMenu);
		var divTags = izqMenu.getElementsByTagName("UL");
		var labelTags = izqMenu.getElementsByTagName("A");
		
		//alert(divTags.length);
		
		//Doy propiedades a los objetos UL
		for (var i = 0; i<divTags.length; i++) {

			divTags[i].id = "subM" + i;
			divTags[i].expanded = false;
			divTags[i].currentSize = 0;
			divTags[i].targetSize = divTags[i].offsetHeight; //estan contyraidos siempre al principio
			divTags[i].contractedSize = divTags[i].targetSize;
			divTags[i].expandedSize = divTags[i].currentSize;
			divTags[i].moving = false;
			divTags[i].parentNode.hasSM = true;
			
			//encuentro dentro de los submenus si hay un current
			var subM_items = divTags[i].getElementsByTagName("LI");
			//alert("subM_items = " + subM_items.length);
			
			for (var j = 0; j<subM_items.length; j++) {
				if(subM_items[j].className.indexOf("current") > -1) {
					divTags[i].parentNode.firstChild.className = "current";
				}
			}
			
			
			if(divTags[i].parentNode.firstChild.className == "current") {
				
				divTags[i].expanded = true;
				divTags[i].currentSize = divTags[i].offsetHeight; //estan expandidos siempre al principio			
				divTags[i].targetSize = 0;	
				divTags[i].style.height = divTags[i].currentSize + "px";
				
				setBackgroundPos(divTags[i],"-736px 0px","#417ACB","#FFFFFF",false);
				
				sMenu = divTags[i];
				activeSmenus.push(sMenu);
				
				//alert(divTags[i].parentNode.firstChild.innerHTML);
				divTags[i].parentNode.firstChild.className = "kind current";
				
			}
			else {
				//oculto todos los submenus
				divTags[i].style.height = divTags[i].currentSize + "px";
				divTags[i].parentNode.firstChild.className = "kind";
			}
			
			/*posiciono y hago visibles a todos los submenus (ocultados via CSS)*/
			divTags[i].style.visibility = "visible";
			divTags[i].style.position = "relative";
			
			//Busco los STRONG con clase "kind" que tengan subMenu y les aņado Eventos
			if(divTags[i].parentNode.firstChild.className.indexOf("kind") > -1) {
				//alert("LABEL found!!");
				setUpIzqmenuEvents(divTags[i].parentNode.firstChild);
			}
			
		}
		
	}
	
}


//Animacion del subMenu
animateSubmenus = function(selectedAnchor) {
	
	if(animating == false) {//Si no se esta animando(Espero a que termine para animar de nuevo)
		
		//alert(animating);
		
		//Encuentro el submenu "div class = subM" correpondiente al anchor seleccionado
		var liParentChilds = selectedAnchor.parentNode.childNodes;
		
		for (var i = 0; i<liParentChilds.length; i++) {
			if(liParentChilds[i].tagName == "UL") {
				animating = true;
			}
		}
		
		
		
		//Si existia un sMenu que se ha contraido lo borro del array activeSmenus
		if(removeActiveSmenu == true) {
			activeSmenus.shift();
			//alert("removing ActiveSmenu");
		}
		
		stoppingCount = 0;
		
		
		
		//alert(liParentChilds.length);
		
		for (var i = 0; i<liParentChilds.length; i++) {
			if(liParentChilds[i].tagName == "UL") {
				sMenu = liParentChilds[i];
				sMenuId = liParentChilds[i].id;
				
				//alert("sMenu = " + sMenuId + ":: sMenu currentSize = " + sMenu.currentSize);
				
				//Aņado sMenus al array activeSmenus solo si se va a expandir
				if(sMenu.targetSize != 0) {
					activeSmenus.push(sMenu);
				}
  
				if(activeSmenus.length > 1){//Si la longitud del activeSmenus es mayor a 1 se debe remover un valor del mismo
					removeActiveSmenu = true;
					//alert("Dos items");
				}
				else if (activeSmenus.length == 1 && sMenu.targetSize == 0) {//Si hay solo 1 valor pero es el mismo SMenu contrayendose se remueve tambien 
					removeActiveSmenu = true;
					//alert("1 items y se va a cerrar");
				}
				else {//Ni es el mismo contrayendose
					//alert("1 items y se va a abrir");
					removeActiveSmenu = false;
				}
   	
				//alert("activeSmenus.length = " + activeSmenus.length + " ::: removing = " + removeActiveSmenu);
				
				for (var j=0; j<activeSmenus.length; j++) {
					//alert("activeSmenus = " + activeSmenus[j].id + " || targetSize = " + activeSmenus[j].targetSize);
					activeSmenus[j].moving = true;
					activeSmenus[j].resizing = new sizeIncrement(activeSmenus[j].currentSize, activeSmenus[j].targetSize);
				}
   	
				
			}
		}
		
		sizeInterval = setInterval( function() { updateSize(); }, 50 );
	}
		
}


//Aņado eventos a los Anchors de los izqMenu
setUpIzqmenuEvents = function (izqMenuItem) {
	
	izqMenuItem.onclick = function () {
		 
		//Encuentro el submenu "div class = subM" correpondiente al anchor seleccionado
		var liParentChilds = izqMenuItem.parentNode.childNodes;
		//alert(izqMenuItem.className);
    	
    	if(animating != true) {
    	
			for (var i = 0; i<liParentChilds.length; i++) {
				//alert(liParentChilds.length + "||" + liParentChilds[i].tagName);
				if(liParentChilds[i].tagName == "UL") {
					
					if(liParentChilds[i].currentSize == liParentChilds[i].expandedSize && liParentChilds[i].expanded == true){
						if(liParentChilds[i].parentNode.firstChild.className.indexOf("current") > -1) {
							setBackgroundPos(liParentChilds[i],"-552px 0px","#417ACB","#FFFFFF",false);
						}
						else {
							setBackgroundPos(liParentChilds[i],"-184px 0px","#B82929","#FFFFFF",false);
						}
					}
					else {
						if(liParentChilds[i].parentNode.firstChild.className.indexOf("current") > -1) {
							setBackgroundPos(liParentChilds[i],"-552px 0px","#417ACB","#FFFFFF",false);
						}
						else {
							setBackgroundPos(liParentChilds[i],"-184px 0px","#B82929","#FFFFFF",false);
						}
					}
					
					
					//Quito el color del menu anteriormente seleccionado
					for (var j = 0; j<activeSmenus.length; j++) {
						//alert(activeSmenus[j].id);
						if(activeSmenus[j].id != liParentChilds[i].id) {
							if(activeSmenus[j].parentNode.firstChild.className.indexOf("current") > -1) {
								setBackgroundPos(activeSmenus[j],"-552px 0px","#417ACB","#FFFFFF",false);
							}
							else {
								setBackgroundPos(activeSmenus[j],"0px 0px","#FFFFFF","#417ACB",true);
							}
						}
					}
        	
				}
			}
		
			animateSubmenus(izqMenuItem);
			
		}
		
		return false;
		
		/*
		if("undefined" != typeof(event) ) {
			event.returnValue = false;
		}
		
		*/
	}
}


//recolocacion del fondo
setBackgroundPos = function (activeSmenu,pos,color,textColor,removeStyles) {
	
	//Encuentro los hijos del Nodo padre
	//para el link y para el submenu es el LI contenedor
	var liParentChilds = activeSmenu.parentNode.childNodes;
	//alert(liParentChilds.length);
	
	//si uno de los hijos es "STRONG" busco el hijo "SPAN"
	for (var i = 0; i<liParentChilds.length; i++) {
		
		if(liParentChilds[i].tagName == "A") {
			var parentSmenu = liParentChilds[i];
		}
		
	}
	
	//alert(removeStyles);
	
	//pongo el fondo
	if(removeStyles != true){
		parentSmenu.style.color = textColor;
		parentSmenu.style.backgroundPosition = pos;
		parentSmenu.style.backgroundColor = color;
	}
	else {
		parentSmenu.removeAttribute("style");
	}
	//parentSmenu.firstChild.style.backgroundPosition = pos2;
}




//Incremento de Movimiento
function sizeIncrement (currentSize,targetSize) {
	
	this.resizeIt = function(){
		
		if(currentSize < targetSize) {//Expando
			currentSize += (targetSize - currentSize) / expandSpeed;
			currentSize = Math.ceil(currentSize);
		}
		else if (targetSize < currentSize) {//Contraigo
			currentSize += (targetSize - currentSize) / expandSpeed;
			currentSize = Math.floor(currentSize);
		}
		
		return [currentSize,targetSize];   
		
	}
}


//Actualizacion de tamaņo del subMenu
function updateSize(){
	
	for (var i=0; i<activeSmenus.length; i++) {
		activeSmenus[i].currentSize = activeSmenus[i].resizing.resizeIt()[0];
		activeSmenus[i].style.height = activeSmenus[i].currentSize + "px";
		
		//Si completo la expansion o la contraccion del subMenu
		if (activeSmenus[i].currentSize == activeSmenus[i].targetSize && activeSmenus[i].moving == true) {
			//alert(sMenu.id + " -> finished!!");
			stoppingCount += 1;
			
			//alert("stoppingCount = " + stoppingCount);
			//alert("activeSmenus.length = " + activeSmenus.length);
			
			if(activeSmenus[i].targetSize == activeSmenus[i].expandedSize) {//Se estaba expandiendo
				activeSmenus[i].targetSize = activeSmenus[i].contractedSize;
				activeSmenus[i].moving = false;
				
				if(activeSmenus[i].parentNode.firstChild.className.indexOf("current") == -1) {
					setBackgroundPos(activeSmenus[i],"0px 0px","#417ACB","#B82929",true);
				}
				
				activeSmenus[i].expanded = true;
				
				//alert(activeSmenus[i].id + " targetSize = " +  activeSmenus[i].targetSize + "\n item = " + activeSmenus[i].parentNode.firstChild.className);
			}
			else {//Se estaba contrayendo
				activeSmenus[i].targetSize = activeSmenus[i].expandedSize;
				activeSmenus[i].moving = false; 
				
				if(activeSmenus[i].parentNode.firstChild.className.indexOf("current") > -1) {
					setBackgroundPos(activeSmenus[i],"-736px 0px","#417ACB","#FFFFFF",false);
					//alert("jiji");
				}
				else {
					setBackgroundPos(activeSmenus[i],"-368px 0px","#B82929","#FFFFFF",false);
				}
				
				activeSmenus[i].expanded = false;
				
				
				//alert(activeSmenus[i].parentNode.className);
				//alert(activeSmenus[i].id + " targetSize = " +  activeSmenus[i].targetSize);
				//alert("contracting:" + activeSmenus[i].id);
			}
			
			if (stoppingCount == activeSmenus.length) {
				//alert("full STOP!!");
				animating = false;
				clearInterval(sizeInterval);
			}
			
		}
		
		//testVars
		//testVars(activeSmenus.length,activeSmenus[0].id,activeSmenus[0].currentSize,activeSmenus[0].targetSize);
		
		
	}

}

//Obtengo valor de los estilos (FUNCION GENERICA)
function getStyle(tag,stylePropA,stylePropB) {
	var testTag = tag;
	
	if (testTag.currentStyle) {
		var styleValue = testTag.currentStyle[stylePropA];
	}
	
	else if (window.getComputedStyle) {
		var styleValue = document.defaultView.getComputedStyle(testTag,null).getPropertyValue(stylePropB);
	}
	
	//alert(parseFloat(styleValue));
	return parseFloat(styleValue);
}


///////////////////////////////////////////////////
//LISTADO DOS COLUMNAS(Materias)
///////////////////////////////////////////////////
twoColsList = function (container,listClass,columnWidth) {
	
	if (document.getElementById(container) != null) {
		var container = document.getElementById(container);
		var ulTags = container.getElementsByTagName("UL");
		//alert(ulTags.length);
		
		//find 3col list
		for (var i=0; i<ulTags.length; i++) {
			
			if(ulTags[i].className == listClass) {
				//alert("list found!!");
				sortList(container,ulTags[i],listClass,columnWidth);
			}
		}
	
	}
	
}

//sorting 2Col list
sortList = function (container,list,listClass,columnWidth) {
	
	//alert(listClass);
	
	//Init Vars
	var totalHeight = new Number();
	var heightCounter = new Number(0);
	var columnsNames = new Array("colA","colB");
	var columns = new Array([],[]);
	var columnsCounter = new Number(0);
	var startColumnHeight = new Number(0);
	var listNodes = list.childNodes;
	
	
	var listItems = new Array();
	
	for (var i=0; i<listNodes.length; i++) {
		if(listNodes[i].tagName == "LI") {
			listItems.push(listNodes[i]);
		}
	}
	
	
	//alert(listItems.length);
	
	//apply width to list before taking LI measurements
	list.style.width = columnWidth + "px"
	
	for (var i=0; i<listItems.length; i++) {
		var itemHeight = listItems[i].offsetHeight;
		listItems[i].itemHeight = itemHeight;
		//alert("itemHeight = " + itemHeight);
		totalHeight += itemHeight;
	}
	
	//alert("totalHeight = " + totalHeight);
	//Define column height
	var columnHeight = Math.ceil(totalHeight/2);
	
	//alert("columnHeight = " + columnHeight);
	
	//fill columns
	for (var i=0; i<listItems.length; i++) {
		
		//alert(columnsCounter);
		//alert(listItems[i].innerHTML);
		

		columns[columnsCounter].push(listItems[i]);
		heightCounter += listItems[i].itemHeight;
		
		//alert("heightCounter = " + heightCounter);
		
		if((heightCounter) >= (columnHeight - 200) && columnsCounter < (columns.length - 1)) {
			//alert("heightCounter greater than columnheight = " + heightCounter);
			heightCounter = startColumnHeight;
			columnsCounter += 1;
		}
		
		
		
		//alert("heightCounter = " + heightCounter);
	}
	
	//create and set up new columns source
	//alert("columns length = " + columns.length);
	//alert("-->" + columns[0][0].innerHTML);
	
	//create container for 2 columns
	var newContainerTag = document.createElement('DIV');
	newContainerTag.setAttribute('class',listClass);
	
	//setAttribute Explorer
	if (navigator.appName.indexOf("Explorer") > 0 && (navigator.userAgent.indexOf("MSIE 6") > 0 || navigator.userAgent.indexOf("MSIE 7") > 0)) {
		newContainerTag.setAttribute('className','itemRow lista2col');
	}
		
	container.insertBefore(newContainerTag, list);

	for (var i=0; i<columns.length; i++) {

		var newTag = document.createElement('UL');
		newTag.setAttribute('class',columnsNames[i]);
		//newTag.setAttribute('style','height:' + columnHeight + 'px');
		
		//setAttribute Explorer
		if (navigator.appName.indexOf("Explorer") > 0 && (navigator.userAgent.indexOf("MSIE 6") > 0 || navigator.userAgent.indexOf("MSIE 7") > 0)) {
			newTag.setAttribute('className',columnsNames[i]);
		}
		
		newTag.innerHTML = "";
		
		for (var j=0; j<columns[i].length; j++) {
			newTag.innerHTML += "\n<li>\n" + columns[i][j].innerHTML + "</div>\n";
		}
		
		newContainerTag.appendChild(newTag);
		
	}
	
	container.removeChild(list);
	
			
			/*
			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" + "jiji" + "</div>\n";		
			
			container.insertBefore(newTag, list);
			*/
	
	//remove original list
	//container.removeChild(list);
	
	
}


//Test vars
//testVars = function (selectedItem) {
testVars = function (activeMenus,activeSmenuID, currentSize, targetSize) {

	var outPutVars = ""

	+ '<strong>EXPENDABLE MENU</strong><br />'
	+ '<strong>'
	+ 'activeSmenus=' + activeMenus + '<br/>'
	+ 'activeSmenuID=' + activeSmenuID + '<br/>'
	+ 'currentSize=' + currentSize + '<br/>'
	+ 'targetSize=' + targetSize
	/*
	+ 'selectedItem=' + selectedItem
	*/
	+ '<br /></strong>';
	
	document.getElementById("testVars").innerHTML = outPutVars;

}


//Initial setUp
setUpPage = function() {

	//carousel
	startCarousel();
	
	//Busqueda rapida
	startQuickSearch("buscar");
	
	//Menus Expandibles
	startIzqMenus("izqMenu");
	
	//Listado en dos columnas
	twoColsList("centro","itemRow lista2col materias",283);
	
} 

window.onload = setUpPage;
