// JavaScript Document

var page = 0;
var currPage = 1;

var lookfor = "";
var ctype = "";

var myEffect;

var hpLstCB=null;

function oneCheckClicked(img,w,id){
	var _hpLstCB=hpLstCB;
	if((null!=_hpLstCB)&&(img!=_hpLstCB[0]))
			checkClicked(_hpLstCB[0],_hpLstCB[1],_hpLstCB[2]);
	if (!id) 
		id = "cb_Check" + w;
	
	var cbObj = $(id);
	if (!cbObj) 	return;
	
	cbObj.checked = !cbObj.checked;
	if (cbObj.checked) 
		img.src='images/BVF_Checkbox-DN.gif';
	else 
		img.src='images/BVF_Checkbox-NR.gif';
	if((null==_hpLstCB)||(img!=_hpLstCB[0]))
		hpLstCB=new Array(img,w,id);
	else
		hpLstCB=null;
}

function checkClicked(img,w,id){
	if (!id) 
		id = "cb_Check" + w;
	
	var cbObj = $(id);
	if (!cbObj) 	return;
	
	cbObj.checked = !cbObj.checked;
	if (cbObj.checked) 
		img.src='images/BVF_Checkbox-DN.gif';
	else 
		img.src='images/BVF_Checkbox-NR.gif';
}
function selectCB (w) {
	var img = $('cb_Check_Img_' + w);
	checkClicked(img, w, 'cb_Items_' + w);
	
	var selectedCount = getSelectedCount();
	if (selectedCount>0) {
		Element.update("f_DownloadMultiple_Count",selectedCount);
		new Effect.Appear($("f_DownloadMultiple_Parent"), {duration : .5 });
	} else {
		new Effect.Fade($("f_DownloadMultiple_Parent"), {duration : .5 });
	}
}
function getSelectedCount(){
	var selectedCount = 0;
	var i = 0;
	while ( $("cb_Items_" + i) ) {
		if ( $("cb_Items_" + i).checked ) {
			selectedCount++;
		}
		i++;
	}
	return selectedCount;
}
function unselectAll(){
	var i = 0;
	while ( $("cb_Items_" + i) ) {
		if ( $("cb_Items_" + i).checked ) {
			selectCB(i);
		}
		i++;
	}
}

function downloadMultipleItems ( format, toDown ) {
	var items = "";
	var i = 0;
	while ( $("cb_Items_" + i) ) {
		if ( $("cb_Items_" + i).checked ) {
			items += $("cb_Items_" + i).value + ",";
		}
		i++;
	}
	if (items == "") {
		alert("Debe seleccionar al menos una publicación.");
	} else {
		items = items.substr(0, items.length - 1);
	}
	showDownDialog(2,"format=" + format + "&id=" + items + ((!toDown) ? "&tc=1" : "" ));
}

function itemOut (obj, w) {
	if ( (!$('cb_Items_' + w)) || ( !($('cb_Items_' + w).checked) ) ) {
		Element.removeClassName(obj,'s_hover');
	}
}

function doFirstSearch ( type ) {
	$("tb_Search_2").value = $("tb_Search").value;
	if ( type ) {
		doAction('changeMe("'+type+'_small");');
//		doSearch(true,1,type);
	} else {
		doAction('doSearch(true,1);',true);
	}
	Ajax.Responders.register(myGlobalHandlers);
}

function doSearch ( resetsearch, spage, type ) {
	
	if (page == 0) {
		if ( resetsearch )
			lookfor = encodeURIComponent(formatString($("tb_Search_2").value));
		
		searchOnBlur();
	
		new Effect.Appear($("d_Loading"),{duration:1});
		new Effect.Fade($("mainForm"),{duration:1});
		new Effect.Squish($("top_image"),{duration:2,queue:"end"});
		$("tbl_HomeCenter").style.height="0px";
		
		page = 1;
		
		if (spage)
			showSearch (spage);
		else
			showSearch ();
	} else {
		var selectedCount=getSelectedCount();
		if (selectedCount > 0) {
			var url = './php/modal_msg.php?codeAction=hasSelectedItems&c='+selectedCount+'&rs='+resetsearch+'&spage='+spage;
			Modalbox.show(url,{title:'Alerta',width:500});
			return;
		}
		if ( (!aSearchFormVisible) && (( $("tb_Search_2").value == "" ) || ( $("tb_Search_2").value == defaultText ) ) && ( lookfor.charAt(0) != "|" ) ) 	return;
		if ( aSearchFormVisible) {
			if (($("tb_Title").value=="")&&($("tb_Keywords").value=="")&&($("tb_Author").value=="")&&($("cb_Period").value=="-1")&&($("tb_From").value=="")&&($("tb_To").value=="")){
				alert("Debe introducir al menos un criterio de búsqueda");
				$("tb_Title").focus();$("tb_Title").select();
				return;
			}
			if ( ($("tb_From").value!="") && (isNaN($("tb_From").value)) ){
				alert("Debe introducir un número");
				$("tb_From").focus();$("tb_From").select();
				return;
			}
			if ( ($("tb_To").value!="") && (isNaN($("tb_To").value)) ){
				alert("Debe introducir un número");
				$("tb_To").focus();$("tb_To").select();
				return;
			}
		}
		new Array("cb_Check_Titulo","cb_Check_Materia","cb_Check_Autor").each( function (aname) {
				$(aname).checked = false;
			}
		);
		new Effect.Appear($("d_Loading"), {duration : 2 });
		var e = new Effect.Fade($("d_ResultPage"), {duration : 1 });
		e.finish = function ( position ) {
				if ( resetsearch )
					lookfor = encodeURIComponent(formatString((!aSearchFormVisible ? $("tb_Search_2").value : $("tb_Title").value)));
				if (spage) 
					showSearch(spage);
				else
					showSearch();
			};
	}
}

var pageSize = 8;

function showSearch ( spage ) {
	if ( spage ) 
		currPage = spage;

	ctype = "";
	MM_swapImgRestore();

	var url = "./php/actions.php";
	var pars = "codeAction=search&q=" + lookfor + "&type=" + ctype + "&page=" + currPage + "&pageSize=" + pageSize;
	
	if ( ($("cb_Check_Titulo").checked) || ($("cb_Check_Materia").checked) || ($("cb_Check_Autor").checked) ) {
		pars += "&adv=1";
		pars += "&operand=OR";
		pars += "&period=-1";
		if ($("cb_Check_Titulo").checked)
			pars += "&title=" + encodeURIComponent(formatString($("tb_Search").value));
		if ($("cb_Check_Materia").checked)
			pars += "&keywords=" + encodeURIComponent(formatString($("tb_Search").value));
		if ($("cb_Check_Autor").checked)
			pars += "&author=" + encodeURIComponent(formatString($("tb_Search").value));
	} else if ( aSearchFormVisible ) {
		addKeyword('1');
		pars += "&adv=1";
		pars += "&operand=AND";
		pars += "&title=" + encodeURIComponent(formatString($("tb_Title").value));
		pars += "&keywords=" + encodeURIComponent(formatString($("tb_Keywords").value));
		pars += "&author=" + encodeURIComponent(formatString($("tb_Author").value));
		pars += "&period=" + $("cb_Period").value;
		pars += "&from=" + $("tb_From").value;
		pars += "&to=" + $("tb_To").value;
		if (""!=$("cb_Biblioteca").value)
			pars += "&isOnLib="+$("cb_Biblioteca").value;
		if (""!=$("cb_Digital").value)
			pars += "&isDig="+$("cb_Digital").value;
/*		pars += "&e_nombre=" + $("tb_Editorial_Nombre").value;
		pars += "&e_lugar=" + $("tb_Editorial_Lugar").value;
		pars += "&e_pais=" + $("tb_Editorial_Pais").value;*/
		showAdvancedSearch();
	}
	
	var myAjax = new Ajax.Updater ({success: "d_Result"}, url, 
																	{
																	method: "post", 
																	parameters: pars,
																	evalScripts: true,
																	onComplete: function ( rsp ) {
																			resetVars();
																			window.scrollTo(0,0);
																		}
																	}
																);
}

/*** HISTORY - START ***/
var historyList = new Array();
var historyIndex = -1;

function showHistory(){
	var msg = "";
	for (var i = 0; i < historyList.length; i++){
		msg+=((i == historyIndex) ? " *" : "") + historyList[i] + "\n";
	}
	alert(msg);
}

function goBack() {
	if (historyIndex <= 0)
		return;
	historyIndex--;
	evalHistObj(historyList[historyIndex]);
}

function goNext() {
	if (historyIndex >= (historyList.length - 1))
		return;
	historyIndex++;
	evalHistObj(historyList[historyIndex]);
}

function evalHistObj(histObj){
	var replaceResetSearch=false;
	for (var i = 0; i < histObj.length; i++){
		var hist = histObj[i];
		var evalStr="";
		if (hist.type==HIST_TYPE_ACTION){
			evalStr=hist.value;
			if (replaceResetSearch)
				evalStr=replace(evalStr,"doSearch(false","doSearch(true");
		}else if ((hist.type==HIST_TYPE_VALUESET)||(hist.type==HIST_TYPE_SEARCHVALUESET)){
			evalStr=hist.to+"='"+hist.value+"';";
		}
		if ((hist.type==HIST_TYPE_SEARCHVALUESET) && ($("tb_Search_2").value != hist.value))
			replaceResetSearch=true;
		eval(evalStr);
	}
}

var HIST_TYPE_ACTION=0;
var HIST_TYPE_VALUESET=1;
var HIST_TYPE_SEARCHVALUESET=2;

function doAction(str,storeVars) {
	if (typeof(storeVars)=="undefined")
		storeVars = false;
	var histObj = new Array();
	if (storeVars==true){
		histObj[0]={type:HIST_TYPE_SEARCHVALUESET,value:replace($("tb_Search_2").value,"'","\\'"),to:"$('tb_Search_2').value"};
	}
	histObj[histObj.length]={type:HIST_TYPE_ACTION,value:str,to:""};
/*	alert(histObj[0].type + "\n" + histObj[0].to + "\n" + histObj[0].value);
	if (histObj.length>1)
		alert(histObj[1].type + "\n" + histObj[1].to + "\n" + histObj[1].value);*/
	addToHistory(histObj);
	eval(str);
}

function addToHistory(str) {
	if ((historyList.length > 0) && ((historyList.length - 1) > historyIndex))
		historyList = historyList.slice(0, historyIndex + 1);
	historyList[++historyIndex]=str;
}
/*** HISTORY - END ***/

var defaultText = "Escriba el texto a buscar...";

function searchOnFocus (  ) {
	if ( $("tb_Search_2").value == defaultText ) {
		$("tb_Search_2").value = "";
	}
}

function searchOnBlur (  ) {
	if ( $("tb_Search_2").value == "" ) {
		$("tb_Search_2").value = defaultText;
	}
}

function showAbout () {
	new Effect.Appear($("d_Loading"), {duration : 1 });
	new Effect.Fade($("mainForm"), {duration : 1 });
	new Effect.Squish($("top_image"), {duration : 2 });
	$("tbl_HomeCenter").style.height="0px";

	var url = "./php/actions.php";
	var pars = "codeAction=about";
	
	var myAjax = new Ajax.Updater ({success: "d_Result"}, url, 
																	{
																	method: "post", 
																	parameters: pars,
																	evalScripts: true,
																	onComplete: function ( rsp ) {
																			window.scrollTo(0,0);
																		}
																	}
																);
}

function sendEMail () {
	new Effect.Appear($("d_Loading"), {duration : 1 });
	new Effect.Fade($("mainForm"), {duration : 1 });
	new Effect.Squish($("top_image"), {duration : 2 });
	$("tbl_HomeCenter").style.height="0px";

	var url = "./php/actions.php";
	var pars = "codeAction=sendEmail";
	
	var myAjax = new Ajax.Updater ({success: "d_Result"}, url, 
																	{
																	method: "post", 
																	parameters: pars,
																	evalScripts: true
																	}
																);
}

function doSendEmail() {
	new Effect.Appear($("d_Loading"), {duration : 1 });
	new Effect.Fade($("mainForm"), {duration : 1 });
	new Effect.Squish($("top_image"), {duration : 2 });
	$("tbl_HomeCenter").style.height="0px";

	var url = "./php/actions.php";
	var pars = "codeAction=doSendEmail&tb_EMail=" + $("tb_EMail").value;
	
	var myAjax = new Ajax.Updater ({success: "d_Result"}, url, 
																	{
																	method: "post", 
																	parameters: pars,
																	evalScripts: true
																	}
																);
}

function goHome () {
	document.location.reload();
	return;
	
	page = 0;
	if ( $("tb_Search_2").value != defaultText )
		$("tb_Search").value = $("tb_Search_2").value;
	else
		$("tb_Search").value = lookfor;
		
	new Effect.Appear($("d_Loading"), {duration : 1 });

	var e=new Effect.Fade($("d_ResultPage"), {duration : 1 });
	e.finish = function ( position ) {
		new Effect.Appear($("mainForm"), {duration : 1 });
		var e2 = new Effect.SlideDown($("top_image"), {duration : 2 });
		e2.finish = function ( position ) {
				new Effect.Fade($("d_Loading"), {duration : 1 });
				$("tbl_HomeCenter").style.height="0px";
		}
	}
}

function onSearchKeyPress ( evt ) {
	var key=(evt.charCode)?evt.charCode: ((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
	if (( key == Event.KEY_RETURN ) && ($$(".autosuggest").length==0)) {
		if ( Event.element(evt).id == "tb_Search" ) 
			doFirstSearch();
		else
			doAction("doSearch(true,1);",true);
	}
}

function changeMe( id ) {
	var same = false;
	ctype = "";
	MM_swapImgRestore();
	if (!same) {
		$("tb_Search_2").value="";
		$(id).className = "b_sel";
		currPage = 0;
		
		var src = $(id).src;
		$(id).src = src.replace("NR", "UP");
		
		ctype = id.substr(0,3);
		
		if (aSearchFormVisible) {
			showAdvancedSearch();
		}
		if (ctype == "col") {
			showCollections("col", -1);
			return;
		}
		if (ctype == "cat") {
			lookfor = "|cat:author;";
			showCatalog("author","A");
			//doSearch(false,1,ctype);
			return;
		}
		if (ctype == "nov") {
			lookfor = "|nov:5";
			doSearch();
			return;
		}
		
		showCollections(ctype);
		return;
	}
	
	if ( (framePage == "about") && ( ($("tb_Search_2").value == "") || ($("tb_Search_2").value == defaultText) ) ) 
		return;
	resetsearch = ( (page==0) || ( (framePage == "about") && ( ($("tb_Search_2").value != "") && ($("tb_Search_2").value != defaultText) ) ) );
	doSearch(resetsearch,1,ctype);
}

var catalogShowBy = "author";
var lastLetra = "A";

function showCatalog(showBy, letra, spage) {
	if (page == 0) {
		new Effect.Appear($("d_Loading"), {duration : 1 });
		new Effect.Fade($("mainForm"), {duration : 1 });
		new Effect.Squish($("top_image"), {duration : 2 });
		$("tbl_HomeCenter").style.height="0px";
	}
	
	if (("undefined"!=typeof(showBy)) && (showBy != ""))
		catalogShowBy = showBy;
	if("title"==catalogShowBy){
		lookfor = "|cat:author;";
		doSearch(false,1,"cat");
		return;
	}

	if ( spage ) 
		currPage = spage;
	else
		currPage = 1;

	var url = "./php/actions_cat.php";
	var pars = "codeAction=show&showBy=" + catalogShowBy + "&page=" + currPage + "&pageSize=" + pageSize;
	
	if ("undefined"!=typeof(letra))	lastLetra = ((letra!="") ? letra : "A");
	pars += "&letra=" + lastLetra;
	
	
	var myAjax = new Ajax.Updater ({success: "d_Result"}, url, 
																	{
																	method: "post", 
																	parameters: pars,
																	evalScripts: true
																	}
																);
}

function showCollections ( w, id ) {
	
	new Effect.Appear($("d_Loading"), {duration : 1 });
	new Effect.Fade($("mainForm"), {duration : 1 });
	new Effect.Squish($("top_image"), {duration : 2 });
	$("tbl_HomeCenter").style.height="0px";

	var url = "./php/actions_" + w + ".php";
	var pars = "codeAction=show";
	
	if (id) {
		pars += "&id=" + id;
	}
	var myAjax = new Ajax.Updater ({success: "d_Result"}, url, 
																	{
																	method: "post", 
																	parameters: pars,
																	evalScripts: true
																	}
																);		
}

function changeTab (w, isOver, w_img) {
/*	var file = "";
	if ( (w == 1) && (!isOver) ) {
		file = "BVF_Tab1R.gif";
	} else {
		file = "BVF_TabsDividers" + ((isOver) ? "2" : "") + ".gif";
	}
	$("i_" + w).src = "images/" + file;*/
	if (isOver) {
		var objs_id = new Array("col", "hem", "cat", "nov", "Ayuda-AcercaDe");
		var objs_files = new Array("Colecciones", "Hemeroteca", "Catalogo", "Novedades", "Acerca_de");
		
		MM_swapImage(objs_id[w-1],'','images/BVF_TabIcon-' + objs_files[w-1] + '-UP.gif',1);
	} else {
		MM_swapImgRestore();
	}
}

var aSearchFormVisible = false;

function showAdvancedSearch (  ) {
	aSearchFormVisible = !aSearchFormVisible;
	if ( aSearchFormVisible ) {
		var e = new Effect.SlideDown($("d_AdvSearch"), {duration : 1 });
		new Effect.Fade($("d_SimpleSearch"), {duration : 1 });
	} else {
		var e = new Effect.SlideUp($("d_AdvSearch"), {duration : 1 });
		new Effect.Appear($("d_SimpleSearch"), {duration : 1 });
	}
}

var framePage = "";

function setActivePage( pPage ) {
	framePage = pPage;
	
	var pNames = new Array("search", "about", "col", "hem", "cat", "nov", "tab");
	var pifnNames = new Array("BVF_Resultados_de_la_busqueda.gif", "BVF_Acerca_de.gif", "BVF_Colecciones.gif", "BVF_Hemeroteca.gif", "BVF_Catalogo.gif", "BVF_Novedades.gif", "");
	var piSize = new Array(new Array(317, 11), new Array(130, 9), new Array(147, 8), new Array(142, 8), new Array(110, 11), new Array(126, 9), new Array(0, 0));
	
	var i = pNames.indexOf(pPage);
	
	$("i_LogoText").src = "images/" + pifnNames[i];
	$("i_LogoText").width = piSize[i][0];
	$("i_LogoText").height = piSize[i][1];
}

function d_ItemsToShowMouseOver(e) {
	var obj = $("d_ItemsToShow_Popup");
	var outObj = $("d_ItemsToShow");
	var pos = Element.getPosition(outObj);
	obj.style.left = (pos.x - 2) + "px";
	obj.style.top = (pos.y + Element.getHeight(outObj) - 2) + "px";
	Element.show(obj);
}

function changeItemsToShow ( n ) {
	Element.update($("d_ItemsToShow"), "Mostrar " + n + " coincidencias");
	Element.hide($("d_ItemsToShow_Popup"));
	
	pageSize = n;
	if (ctype == "cat") 
		showCatalog('','',1);
	else
		doSearch(false);
}

var c_item = null;
var c_item_id = null;

function showItemPopup ( ref, id ) {
	c_item = ref;
	c_item_id = id;
	var obj = $("d_ItemPopup");
	var pos = Element.getPosition(ref);
	obj.style.left = (pos.x - 2) + "px";
	obj.style.top = (pos.y + Element.getHeight(ref) - 2) + "px";
	Element.show(obj);
}

function itemPopup_ShowDetails() {
	var obj = $("d_ItemPopup");
	Element.hide(obj);
}

var last_itemDetail = "";

function showItemDetails( id ) {
	if ( (!$("d_ItemDetails_" + id)) ) 	return;
	
	if ( (last_itemDetail != "") && (last_itemDetail != id) ) { 
		if (toggle_slide("d_ItemDetails_" + last_itemDetail)) 
			Element.hide($('sautor_ItemDetails' + last_itemDetail));
		else
			Element.show($('sautor_ItemDetails' + last_itemDetail));
	}

	if ( (last_itemDetail == id) ) 
		last_itemDetail = "";
	else
		last_itemDetail = id;
	
	if (toggle_slide("d_ItemDetails_" + id)) 
		Element.hide($('sautor_ItemDetails' + id));
	else
		Element.show($('sautor_ItemDetails' + id));
}

function toggleItemDetailsDownload( id, wich ) {
	if (!wich) 	wich = "Down";
	if (!toggle_slide('tbl_ItemDetails' + wich + id, true)) {
		if ($('i' + wich + '_ItemDetails' + id))
			$('i' + wich + '_ItemDetails' + id).src="./images/itemDetails/BVF_Plus.gif";
	} else {
		if ($('i' + wich + '_ItemDetails' + id))
			$('i' + wich + '_ItemDetails' + id).src="./images/itemDetails/BVF_Minus.gif";
	}
}

function resetVars() {
	last_itemDetail = "";
}

function reportError(request)
{
	alert("Su petición no ha podido ser procesada.");
}

var TABids = new Array();

function getTABPos(val){
	for(var i=0;i<TABids.length;i++)
		if (TABids[i]==val)
			return i;
	return -1;
}
function newTAB(pubId,content) {
	Element.show("d_TABS");
	getFloatLayer('f_DownloadMultiple_Parent').minY=((navigator.appVersion.match(/\bMSIE\b/))? 115 : 111 );
	alignFloatLayers();
	if (getTABPos(pubId)!=-1){
		changeTABPage(pubId);
		return;
	}
	TABids[TABids.length] = pubId;
	var h = getWindowSize().height - 145;
	new Insertion.Bottom("d_TABSContent","<div id='d_TABContent"+pubId+"' style='display:none;height:"+h+"px;'><iframe id='d_TABFrame"+pubId+"' src='"+content+"&tab="+pubId+"' frameborder='0' style='border-bottom:1px #CCC solid;height:100%;width:100%;'></iframe></div>");
	if (navigator.appVersion.match(/\bMSIE\b/)) {
		var nc=$("tbl_TABS_row").insertCell();
		nc.id="tab"+pubId;
		nc.innerHTML='<div id="d_tab'+pubId+'" class="tabDIV">Cargando...</div><img id="d_tabClose'+pubId+'" src="./images/BVF_Tab-Loading.gif" width="12" height="13" title="Cerrar pesta&ntilde;a" style="margin-top:2px;"/>';
		nc.width=175;
	} else {
		new Insertion.Bottom("tbl_TABS_row",'<td width="175" id="tab'+pubId+'"><div id="d_tab'+pubId+'" class="tabDIV">Cargando...</div><img id="d_tabClose'+pubId+'" src="./images/BVF_Tab-Loading.gif" width="12" height="13" title="Cerrar pesta&ntilde;a" style="margin-top:2px;"/></td>');
	}
	applyTabEvents("tab"+pubId);
	Element.update("d_ItemDetails_CText"+pubId, "Consultando el texto");
	$("d_ItemDetails_CImg"+pubId).src="./images/itemDetails/BVF_LinkLoading.gif";
	Element.setStyle("tbl_RTABS",{width:(TABids.length*175)+"px"});
}
function closeTAB(wich) {
	var ta = new Array();
	for(var i=0;i<TABids.length;i++){
		if (TABids[i]!=wich) {
			ta[ta.length] = TABids[i];
		}
	}
	TABids = ta;
	if ($("tab"+wich).className=="selected") 
		changeTABPage(0);
	Element.remove("tab"+wich);
	Element.remove("d_TABContent"+wich);
	Element.update("d_ItemDetails_CText"+wich, "Consultar el texto");
	$("d_ItemDetails_CImg"+wich).src="./images/itemDetails/BVF_Link.gif";
	Element.setStyle("tbl_RTABS",{width:(TABids.length*175)+"px"});
	if (TABids.length==0){
		Element.hide("d_TABS");
		getFloatLayer('f_DownloadMultiple_Parent').minY=((navigator.appVersion.match(/\bMSIE\b/))? 94 : 92 );
		alignFloatLayers();
	}
}
function setTABTitle(wich,title) {
	$("d_tab"+wich).innerHTML=title;
	$("d_tab"+wich).title=title;
	$("d_tabClose"+wich).src="./images/BVF_Tab-CloseNR.gif";
	Element.update("d_ItemDetails_CText"+wich, "Consultar el texto ahora");
	$("d_ItemDetails_CImg"+wich).src="./images/itemDetails/BVF_LinkG.gif";
}
function doTABPrint(){
	$('d_TABFrame'+currTAB).focus();
	$('d_TABFrame'+currTAB).contentWindow.print();
}
function doTABScroll(){
	$('d_TABFrame'+currTAB).contentWindow.scrollTo(0,0);
}
function updateTABToolbar(){
	var url = "./php/export.php";
	var pars = "codeAction=getPubDownOptions&id="+currTAB;
	var myAjax=new Ajax.Updater({success:"f_TopMenu_TABPage_DownPanel"},url,{method:"post",parameters:pars,evalScripts:true});
}

function showToolBar(w){
	if (w == 0) {
		setActivePage("search");
		var e = new Effect.Move($('f_TopMenu_TABPage'),{duration:.5,mode:"absolute",x:-200,moveY:false});
		e.finish = function () {
			$('f_TopMenu_TABPage').hide();
			new Effect.Move($('f_TopMenu_Search'),{duration:.5,mode:"absolute",x:0});
		}
	} else {
		setActivePage("tab");
		if (aSearchFormVisible) 
			showAdvancedSearch();
		var e = new Effect.Move($('f_TopMenu_Search'),{duration:.5,mode:"absolute",x:-800});
		e.finish = function () {
			$('f_TopMenu_TABPage').show();
			new Effect.Move($('f_TopMenu_TABPage'),{duration:.5,mode:"absolute",x:20,moveY:false});
		}
	}
}
var currTAB=0;
function changeTABPage(w) {
	if (w!=0) 	$("tab0").className="";
	var td=$("tab"+w);
	if ((td) && (td.className!="selected")) {
		for(var i=0;i<TABids.length;i++)
			$("tab"+TABids[i]).className='';
		td.className='selected';
	}
	showToolBar(w);
	
	var toShow=((w==0)? "d_Result" : "d_TABContent"+w );
	var toHide="";
	currTAB=w;
	updateTABToolbar(currTAB);
	
	if (Element.visible("d_Result"))
		toHide="d_Result";
	else
		for(var i=0;i<TABids.length;i++)
			if (Element.visible("d_TABContent"+TABids[i]))
				toHide="d_TABContent"+(TABids[i]);
	if ($(toHide)) {
		var e = new Effect.Fade(toHide,{duration:.5});
		e.finish = function(){
			if($(toShow)) 
				new Effect.Appear(toShow,{duration:.5});
		};
	} else if($(toShow)) {
		new Effect.Appear(toShow,{duration:.5});
	}
}
function applyTabEvents(id){
	Event.observe($(id), "mouseover", 
		function(el){
			var tabNumber = Event.element(el).id.substr(((Event.element(el).id.length>4)? 5 : 3));
			var td=$("tab"+tabNumber);
			if ((td) && (td.className!="selected"))
				td.className='hover';
		},
		false);
	Event.observe($(id), "mouseout", 
		function(el){
			var tabNumber = Event.element(el).id.substr(((Event.element(el).id.length>4)? 5 : 3));
			var td=$("tab"+tabNumber);
			if ((td) && (td.className!="selected"))
				td.className='';
		},
		false);
	Event.observe($(id), "click", 
		function(el){
			var tabNumber = Event.element(el).id.substr(((Event.element(el).id.length>4)? 5 : 3));
			var td=$("tab"+tabNumber);
			if ((td) && (td.className!="selected"))
				changeTABPage(tabNumber);
		},
		false);
	if ($("d_tabClose"+id.substr(3))) {
		Element.setOpacity($("d_tabClose"+id.substr(3)),.5);
		Event.observe($("d_tabClose"+id.substr(3)), "mouseover", 
			function(el){
				var tabNumber = Event.element(el).id.substr(10);
				$("d_tabClose"+tabNumber).src="./images/BVF_Tab-CloseUP.gif";
			},
			false);
		Event.observe($("d_tabClose"+id.substr(3)), "mouseout", 
			function(el){
				var tabNumber = Event.element(el).id.substr(10);
				var isLoading=($("d_tab"+tabNumber).innerHTML=="Cargando...");
				$("d_tabClose"+tabNumber).src="./images/BVF_Tab-"+((isLoading)?"Loading":"CloseNR")+".gif";
			},
			false);
		Event.observe($("d_tabClose"+id.substr(3)), "click", 
			function(el){
				var tabNumber = Event.element(el).id.substr(10);
				var td=$("tab"+tabNumber);
				if (td) 
					closeTAB(tabNumber);
			},
			false);
	}
}

function showModalBox(url,title,onAfterHide){
	if(onAfterHide)
		Modalbox.show(url,{title:title,width:500,afterHide:onAfterHide});
	else
		Modalbox.show(url,{title:title,width:500});
}
function showDownDialog(type,url){
	if ((url!="")&&(url.charAt(0)!="&"))	url="&"+url;
	showModalBox('./php/toDown.php?type='+type+url,'Descarga',function(){if(updateDownloadCounter)updateDownloadCounter=null;});
}

function requestLivePub(){
	if ($("tb_RLP_Nombre").value==""){
		alert("Debe introducir su nombre");
		$("tb_RLP_Nombre").focus();
		return false;
	}
	if ($("tb_RLP_Ocupacion").value==""){
		alert("Debe introducir su ocupación");
		$("tb_RLP_Ocupacion").focus();
		return false;
	}
	if ($("tb_RLP_CorreoE").value==""){
		alert("Debe introducir su correo electrónico");
		$("tb_RLP_CorreoE").focus();
		return false;
	}
	var d=$("tb_RLP_DYear").value+"-"+$("tb_RLP_DMonth").value+"-"+$("tb_RLP_DDay").value+" "+$("tb_RLP_HH").value+":"+$("tb_RLP_HM").value;
	var url="./php/actions.php?codeAction=requestLivePub&id="+$("tb_RLP_Id").value+"&name="+$("tb_RLP_Nombre").value+"&ocup="+$("tb_RLP_Ocupacion").value+"&email="+$("tb_RLP_CorreoE").value+"&date="+encodeURI(d);
	showModalBox(url,"Solicitar su lectura en la biblioteca del Instituto de Filosof&iacute;a, La Habana, Cuba");
}

function loadImages () {
	MM_preloadImages('images/BVF_TabIcon-Colecciones-UP.gif','images/BVF_TabIcon-Hemeroteca-UP.gif','images/BVF_TabIcon-Catalogo-UP.gif','images/BVF_TabIcon-Novedades-UP.gif','images/BVF_TabIcon-Acerca_de-UP.gif','images/BVF_Submit-UP.gif','images/BVF_Checkbox-NR.gif', 'images/BVF_Checkbox-DN.gif','images/menu_left_rounded.gif','images/minus.gif','images/plus.gif','images/nochilds.gif','images/none.gif','images/itemDetails/BVF_DOC.gif','images/itemDetails/BVF_HTM.gif','images/itemDetails/BVF_Link.gif','images/itemDetails/BVF_LinkG.gif','images/itemDetails/BVF_Minus.gif','images/itemDetails/BVF_PDF.gif','images/itemDetails/BVF_Plus.gif','images/itemDetails/BVF_PPT.gif','images/itemDetails/BVF_RAR.gif','images/itemDetails/BVF_TXT.gif','images/itemDetails/BVF_XLS.gif','images/itemDetails/BVF_ZIP.gif','images/BVF_FilterBTN.gif','images/BVF_Loading.gif','images/BVF_RibbonIcon-Atras-UP.gif','images/BVF_RibbonIcon-Siguiente-UP.gif','images/BVF_RibbonIcon-Siguiente-NR.gif','images/BVF_RibbonIcon-Atras-NR.gif','images/loadingAnimation.gif','images/BVF_DownloadBarLeft.gif','images/BVF_DownloadBarRight.gif','images/BVF_DownloadBarClose.gif','images/BVF_Tabs.gif','images/BVF_ScrollTabs_Right.gif','images/BVF_ScrollTabs_Left.gif','images/BVF_Tab-CloseNR.gif','images/BVF_Tab-CloseUP.gif','images/BVF_Tab-Loading.gif');
}

var export_formats=new Array(
	new Array("txt","Documento de texto (.TXT)"),
	new Array("htm","P&aacute;gina Web (.HTML)"),
	new Array("pdf","Documento port&aacute;til (.PDF)"),
	new Array("doc","Documento de Microsoft Word (.DOC)")
);
var htmlTemplate=''+
'<li style="cursor:default;display:none;">'+
'<span class="s_normal" onClick="selectCB(#i#);" onMouseOver="Element.addClassName(this,\'s_hover\');" onMouseOut="itemOut(this,#i#);">#LEFT_ICON#'+
'&nbsp;&nbsp;<span style="display:inline;">#TITLE_LINK#<br />'+
'<div id="d_ItemDetails_#id#" class="d_ItemDetails" style="display:none;">'+
'<table border="0">'+
'#ITEM_DETAILS_VIEW#'+
'<tr><td><a href="javascript:;" onClick="event.cancelBubble=true;showModalBox(\'./php/actions.php?codeAction=showDetails&id=#id#\',\'Ficha de la publicaci&oacute;n\');return false;"><img src="./images/itemDetails/BVF_Link.gif" border="0" width="9" height="9" />&nbsp; Ver ficha</a></td></tr>'+
'#ITEM_DETAILS_DOWN#'+
'</table><div id="tbl_ItemDetailsDown#id#" style="padding-left:20px;display:none;"><span></span>'+
'#ITEM_DETAILS_DOWN_ITEMS#'+
'</div></div>'+
'<div style="position:relative;padding-left:20px;">'+
'<span id="sautor_ItemDetails#id#" onClick="event.cancelBubble=true;">autor: #AUTHOR_LINK#'+
'</span><br /><span class="comment">( #cita# )</span>&nbsp;</div>'+
'</span></span></li>';
function getSearchItemHTML(obj,i){
	var left_icon='';
	var title_link='';
	var author_link='';
	var details_view='';
	var details_down='';
	var details_down_items='';
	if (obj["kind"] == 0){
		left_icon='<input type="checkbox" class="checkbox" id="cb_Items_#i#" name="cb_Items[]" value="#id#" onClick="event.cancelBubble=true;" style="display:none;" /><img id="cb_Check_Img_#i#" src="images/BVF_Checkbox-NR.gif" align="texttop" title="A&ntilde;adir a la lista de descarga" />';
		title_link='<a href="javascript:;" onClick="event.cancelBubble=true;showItemDetails(#id#);" title="Mostrar/Ocultar opciones">#titulo#</a><span class="comment"> - #str_tipo#</span>';
		author_link='<a href="javascript:;" onclick="Modalbox.show(\'./php/actions.php?codeAction=showAuthorDetails&id=#id#\',{title:\'Ficha del autor\',width:500});return false;" title="ver la ficha del autor">#autor#</a>';
	} else if (obj["kind"] == 1) {
		left_icon='&nbsp;&nbsp;<img src="./images/itemDetails/BVF_NewWindow.gif" border="0" width="9" height="9" align="absmiddle" />';
		title_link='<a href="#url#" target="_blank" rel="external" title="Ir al art&iacute;culo...">#titulo#</a>';
		author_link='#autor#';
	}
	if (obj["has_content"]=="1") {
		details_view+='<tr><td><a href="./php/export.php?format=htm&id=#id#&view=1" target="_blank" onClick="event.cancelBubble=true;newTAB(#id#,\'./php/export.php?format=htm&id=#id#&view=1\');return false;"><img id="d_ItemDetails_CImg#id#" src="./images/itemDetails/BVF_Link.gif" border="0" width="9" height="9"/>&nbsp; <span id="d_ItemDetails_CText#id#">Consultar el texto</span></a></td></tr>';
		export_formats.each(function(format){
			var kf=format[0];
			var f=format[1];
			details_down_items+='<a href="javascript:;" onClick="event.cancelBubble=true;showDownDialog(1,\'format='+kf+'&id=#id#\');"><img src="./images/itemDetails/BVF_'+kf.toUpperCase()+'.gif" border="0" width="10" height="13" />&nbsp; '+f+'</a><br />';
		});
	}
	if (obj["is_on_library"]=="1") {
		details_view+='<tr><td><a href="javascript:;" onClick="event.cancelBubble=true;showModalBox(\'./php/modal_msg.php?codeAction=requestLivePub&id=#id#\',\'Solicitar su lectura en la sala de la biblioteca\');"><img src="./images/itemDetails/BVF_Link.gif" border="0" width="9" height="9"/>&nbsp; Solicitar su lectura en la sala de la biblioteca</a></td></tr>';
	}
	if ((obj["has_content"]=="1")||(obj["hasFiles"]=="1")) {
		details_down+='<tr><td><a href="javascript:;" onClick="event.cancelBubble=true;toggleItemDetailsDownload(\'#id#\',\'Down\');"><img id="iDown_ItemDetails#id#" src="./images/itemDetails/BVF_Plus.gif" border="0" width="9" height="9"/>&nbsp; Descargar como</a></td></tr>';
	}
	obj.files.each(function(file){
		details_down_items+='<a href="javascript:;" onClick="event.cancelBubble=true;showDownDialog(0,\'f='+file.name+'\');"><img src="./images/itemDetails/BVF_'+file.ext+'.gif" border="0" width="10" height="13" />&nbsp; '+formatString(file.original_name)+'</a><br/>';
	});
	
	var currObjHtml=replace(htmlTemplate,"#LEFT_ICON#",left_icon);
	currObjHtml=replace(currObjHtml,"#TITLE_LINK#",title_link);
	currObjHtml=replace(currObjHtml,"#ITEM_DETAILS_VIEW#",details_view);
	currObjHtml=replace(currObjHtml,"#ITEM_DETAILS_DOWN#",details_down);
	currObjHtml=replace(currObjHtml,"#ITEM_DETAILS_DOWN_ITEMS#",details_down_items);
	currObjHtml=replace(currObjHtml,"#AUTHOR_LINK#",author_link);
	currObjHtml=replace(currObjHtml,"#i#",i);
	currObjHtml=replace(currObjHtml,"#id#",obj["id"]);
	currObjHtml=replace(currObjHtml,"#titulo#",obj["titulo"]);
	currObjHtml=replace(currObjHtml,"#autor#",obj["autor"]);
	currObjHtml=replace(currObjHtml,"#str_tipo#",obj["str_tipo"]);
	currObjHtml=replace(currObjHtml,"#url#",obj["url"]);
	currObjHtml=replace(currObjHtml,"#cita#",obj["cita"]);
	return currObjHtml;
}

function statusText(){
	window.status="Biblioteca Virtual de Filosofía y Pensamiento Cubanos - http://biblioteca.filosofia.cu/";
	setTimeout("statusText()",100);
}

/* AJAX Global Loading */
var myGlobalHandlers={
	onComplete:function(){
		new Effect.Appear($("d_ResultPage"),{duration:1});
		new Effect.Fade($("d_Loading"),{duration:2,queue:"end"});
	},
	onFailure:function(){
		alert("Ha ocurrido un error al buscar.");
		new Effect.Appear($("d_ResultPage"),{duration:1});
		new Effect.Fade($("d_Loading"),{duration:2,queue:"end"});
	}
};
//Ajax.Responders.register(myGlobalHandlers);
/* END of AJAX Global Loading */

Event.observe(window, "load", 
	function onWindowLoad() {
		$("tb_Search_2").value = defaultText;
		
		var listenKeyPressObjs = new Array("tb_Search","tb_Search_2","tb_Title","tb_Keywords","tb_Author","cb_Period","tb_From","tb_To");
		listenKeyPressObjs.each( function(objName){
			Event.observe(objName, "keypress", onSearchKeyPress, false);
		});

		var e = new Effect.SlideUp($("d_AdvSearch"), {duration : 0 });
		
		rC = new DHTMLgoodies_roundedCorners();
		rC.addTarget('d_AdvSearchOuter_Form',5,5,'#FFC39A','#FFFFFF',3,0,"bottom_left,bottom_right");
		rC.addTarget('d_AdvSearch_Form',5,5,'#FFE7D6','#FFC39A',5,0,"bottom_left,bottom_right");
		rC.init();
		
		var options_authors = {
			script: "./php/actions.php?codeAction=getAuthorsXMLList&",
			varname: "input",
			minchars: 4,
			cache: false,
			json: true,
			noresults: "No se encontraron coincidencias."
		};
		var as = new AutoSuggest("tb_Author", options_authors);
		
		var options_countries = {
			script: "./php/actions.php?codeAction=getCountriesXMLList&",
			varname: "input",
			minchars: 4,
			cache: true,
			json: true,
			noresults: "No se encontraron coincidencias."
		};
		var as = new AutoSuggest("tb_Editorial_Pais", options_countries);

		var options_keywords = {
			script: "./php/admin/action_keyw.php?codeAction=getXMLList&",
			varname: "input",
			cache: false,
			json: true,
			minchars: 4,
			timeout: 4000,
			noresults: "No se encontraron coincidencias."
		};
		var as = new AutoSuggest('tb_obj_Keywords1', options_keywords);
		
		var options_search_keywords = {
			script: "./php/admin/action_keyw.php?codeAction=getXMLList&",
			varname: "input",
			cache: true,
			json: true,
			minchars: 4,
			timeout: 4000,
			shownoresults: false
		};
		var as = new AutoSuggest('tb_Search', options_search_keywords);
		var as = new AutoSuggest('tb_Search_2', options_search_keywords);
		
		applyTabEvents("tab0");

		loadImages ();
		
		new Array("cb_Check_Titulo","cb_Check_Materia","cb_Check_Autor").each( function (aname) {
				$(aname).checked = false;
			}
		);
		statusText();
		var e=new Effect.Appear($("mainScreen"), {duration : 2 });
		e.finish=function(){
			if ($("reqQ").value != "") {
				$("tb_Search").value = $("reqQ").value;
				doFirstSearch();
				$("tb_Search_2").value = defaultText;
			} else {
				$("tb_Search").focus();
			}
		}
		new Effect.Fade($("d_Loading"), {duration : 2 });

	}, false);

//-->
