function showhideLayers(obj,path, image) 
{ //v1.0
	var v,obj;	
	if ( image != ''){
		image=MM_findObj(image);
	}	
	
	if ((obj=MM_findObj(obj))!=null) 
	{
        v=obj.style.display;
        if (v == 'none' ) 
		{
                disp = 'block';
				img = path + '/retract.gif';
        }
        else 
		{
                disp = 'none';
				img = path + '/expand.gif';
        }
        obj.style.display = disp;
		if ( image != ''){
			image.src = img;
		}	
 }
}

function MM_showhideLayers()
{ 
        var i,p,v,obj,args=MM_showhideLayers.arguments;
                for (i=0; i<(args.length-2); i+=3)
                        if ((obj=MM_findObj(args[i]))!=null)
                        {
                                v=args[i+2];
                                if (obj.style)
                                {
                                        obj=obj.style;
										v=(v=='show')?'block':(v=='hide')?'none':v;
                                }
                                obj.display=v;
                        }
}

function MM_findObj(n, d)
{ //v4.01
        var p,i,x; if(!d) d=document;
        if((p=n.indexOf("?"))>0&&parent.frames.length)
        {
                d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
        }
        if(!(x=d[n])&&d.all)
                x=d.all[n];
        for (i=0;!x&&i<d.forms.length;i++)
                x=d.forms[i][n];
                for(i=0;!x&&d.layers&&i<d.layers.length;i++)
                        x=MM_findObj(n,d.layers[i].document);
                if(!x && d.getElementById)
                        x=d.getElementById(n);
        return x;
}


function validateExpression(){
	var f = document.metasearch;	
	var type = f.form.value;
	var theSearchExp = f.expression.value.toLowerCase();
	
	// tratamento inicial para expressao vazia
	if ( type == 'simple' ){
		if ( theSearchExp == '' ){	
			return false;
		}else{
			return true;
		}		
	}else{
		// obrigatorio informar a expressao quando selecionado um campo de pesquisa
		
		indexField = f.elements["INDEX_[]"]
		indexFieldSelected = f.elements["INDEX_[]"].selectedIndex;		
		
		if ( indexFieldSelected > 0 ){
			if ( theSearchExp == ''){
				alert("Informe a expressão de pesquisa");
				return false;
			}			
		}	
	
	}	
	
	var invalidStartingOperator = /^\s*(AND|OR)\s+/i;					// Impede que o AND e o OR apareçam no início da expressão
	var invalidEndingOperator = /\s+(AND|OR|NOT)\s*$/i;					// Impede que a expressão termine com um operador booleano
	var onlyOperators = /^\s*(AND|OR|NOT)(\s+(AND|OR|NOT))*\s*$/i;		// Impede que a expressão seja composta apenas por operadores booleanos
	var noOperand = /\s+(AND|OR|NOT)\s+(AND|OR)\s+/i;					// Impede as seguintes combinações AND AND, AND OR, OR AND, OR OR, NOT AND e NOT OR
	var notOperand = /\s+NOT\s+NOT\s+/i;								// Impede NOT NOT

	if (theSearchExp.search(invalidStartingOperator) >= 0 
	    || theSearchExp.search(invalidEndingOperator) >= 0
		|| theSearchExp.search(onlyOperators) >= 0
	    || theSearchExp.search(noOperand) >= 0
	    || theSearchExp.search(notOperand) >= 0
		)
	{
		alert("Invalid use of boolean operators");
		return false;
	}
	
	var replaceNot = /\s+NOT\s+/i;
	var replacement1 = " and not ";
	var replaceNotBack = /\s+(AND|OR)\s+AND\s+NOT\s+/i;
	var replacement2 = " $1 not ";
	var replaceOtherQuot = /(”|“)/g;
	var replacement3 = "\"";
	
	theSearchExp = theSearchExp.replace(replaceNot, replacement1).replace(replaceNotBack, replacement2).replace(replaceOtherQuot, replacement3);
			
	f.expression.value = theSearchExp;
	return true;
}

function insertDefaultOperator(){
	var s = document.metasearch.expression;
	var str = s.value.toLowerCase();

	var quotedExpressions = str.match(/("[^"]*")/g);

	// Substitui expressões dentro de aspas por %~~%
	if (quotedExpressions)
	{
		for (var i = 0; i < quotedExpressions.length; i++)
		{
			var qexp = quotedExpressions[i];
			var pos = str.indexOf(qexp);
			
			str = str.slice(0, pos) + "\%~~\%" + str.slice(pos + qexp.length);
		}	
	}
	
	var patterns = [ /^\s+/, /\s+$/, /\s+/g, / AND (AND|OR|NOT) AND /ig, /^NOT AND /i, / NOT AND /ig, / AND /g, / OR /g, /^NOT /, / NOT /g ];
	var replacements = [ "", "", " and ", " $1 ", "not ", " not ", " and ", " or ", "not ", " not " ];

/* sugestao do shintani 

	var patterns = [ /^\s+/, /\s+$/, /\s+/g, / (AND|OR) (AND|OR|NOT) (AND|OR) /ig, /^NOT (AND|OR) /i, / NOT (AND|OR) /ig, / AND /g, / OR /g, /^NOT /, / NOT /g ];
	var replacements = [ "", "", " " + operator + " ", " $2 ", "not ", " not ", " and ", " or ", "not ", " not " ];
*/
	
	for (var i = 0; i < patterns.length; i++)
	{
		str = str.replace(patterns[i], replacements[i]);
	}	
	
	// Insere de volta a expressão dentro de aspas
	if (quotedExpressions)
	{
		for (var i = 0; i < quotedExpressions.length; i++)
		{
			str = str.replace(/%~~%/, quotedExpressions[i]);
		}	
	}
	//alert("str: " + str);
	s.value = str;
}


function openWindow ( url ){
	var d = new Date();
	var winId = d.getDate() + d.getHours() + d.getMinutes() + d.getSeconds();
	
	//newWindow = window.open(url, winId , 'scrollbars=yes, top=20, left=230, width=565, height=520');
	newWindow = window.open(url, winId , '');
	newWindow.focus();
	return;
}


function checkUncheck( group, status  ) 
{
	 var fieldList = document.metasearch.elements;
     var fieldId;
     var pos;
	 
     for ( i = 0; i < fieldList.length; i++ )
     {
		field = fieldList[i];
	 	
		if ( field.type != 'checkbox' ){
		   continue;
		}
	    
	    if ( group == "all" ) {
       	
		    field.checked = true;
           
		} else {
		
             fieldId = field.id;
             pos = group.length;

             if ( fieldId.substring(0,pos) == group ){
			   
	                 field.checked = status;
	           
             }           
       }
 	}  
	return;
}


function historyCombineList(){

 	var fieldList = document.metasearch.elements;
	var historyList = "";
	var selected = 0;

    for ( i = fieldList.length -1; i >= 0 ;i-- )
    {	 	
		field = fieldList[i];
		if ( field.name != 'historyItem' ){
		   continue;
		}

		historyCurrent = field;		
	    if (  historyCurrent.checked == true ){
			historyList += '#' + ( parseInt(historyCurrent.value) + 1 ) + ' and ';
		}
			
 	}  
	// retira o ultimo operador and 
	historyList = historyList.substring(0,historyList.length -5)

	return historyList;

}


function historyElementsList(){

 	var fieldList = document.metasearch.elements;
	var historyList = "";
	var total = 0;
	var selected = 0;

    for ( i = 0; i < fieldList.length; i++ )
    {	 	
		field = fieldList[i];
		if ( field.name != 'historyItem' ){
		   continue;
		}

		historyCurrent = field;
		total++;
	    if (  historyCurrent.checked == true ){
			selected++
			historyList += historyCurrent.value + ';';
		}
			
 	}  
	if ( selected == total){
		historyList = 'ALL';
	}

	return historyList;

}


function combineHistory(){

	var combineList = historyCombineList();
	var expression  = document.metasearch.expression;
	
	if ( combineList != ''){

		if ( expression.value.length  > 0){
			expression.value += " and ";
		}
		expression.value += combineList;
	}
	return;
	
}


function deleteHistory(){

	deleteList = historyElementsList();
	
	if ( deleteList != ''){
		deleteUrl = "/public/scripts/php/delete_history.php?delete=" + deleteList;		
		window.open(deleteUrl, "delete", "top=5000,left=1,height=1,width=1,menubar=no,location=no,resizable=no,scrollbars=no,status=no");
	}
	return;
	
}

function saveHistory(obj){

	saveList = historyElementsList();
	if ( saveList != ''){
		saveUrl = "/public/scripts/php/save_history.php?save=" + saveList;
		obj.href = saveUrl;	
		//window.open(saveUrl, "save", "top=5000,left=0,height=1,width=1,menubar=no,location=no,resizable=no,scrollbars=no,status=no");
	}	
	return;
	
}

function openHistory(){

	lang = document.metasearch.lang.value;
	historyWindow = window.open("/public/scripts/php/open_history.php?mode=popup&lang=" + lang, "open", "left=485,top=225,height=50,width=300,menubar=no,location=no,resizable=no,scrollbars=no,status=no");
	historyWindow.focus();	
	return;
	
}


function postHref ( href, target){
		
	var hrefAction = href.substring(0,href.indexOf('?'));
	var hrefParameters = href.substring(href.indexOf('?')+1);
	var splitedHref = hrefParameters.split("&");
	var qtt = splitedHref.length;
	var splitedHidden = new Array();
	var hiddenName = "";
	var hiddenValue = "";
	var submitForm = document.formHref;

	if ( target == '' || !target ){
		target = 'postHref';
	}	
	
	submitForm.action = hrefAction;
	submitForm.target = target;
	
	for ( var i = 0; i < qtt; i++ )
	{
		splitedHidden = splitedHref[i].split("=");
		hiddenName = splitedHidden[0];
		splitedHidden[0] = "";
		hiddenValue = splitedHidden.join("=");
		hiddenValue = hiddenValue.replace(/%20/g,' ');
		hiddenValue = hiddenValue.replace(/%2F/g,'/');
		hiddenValue = hiddenValue.replace(/\+/g,' ');

		submitForm.elements[i].name = hiddenName;
		submitForm.elements[i].value = hiddenValue.substring(1);
	}
	

	submitForm.submit();
	//window.target.focus();
	// realizar testes de compatibilidade do codigo abaixo	
	resultWindow = window.open('',target);		
	resultWindow.focus();	
}


function refineSearch(){

	refineForm = document.formSearch;
	refineForm.action = "/public/scripts/php/page_show_main.php";
	refineForm.submit();
	return;

}

function openDeCS(){

	lang = document.metasearch.lang.value;
	if (lang == "pt"){ decsLang = "p"; }
	if (lang == "es"){ decsLang = "e"; }
	if (lang == "en"){ decsLang = "i"; }
	
	decsUrl = "http://decs.bvs.br/cgi-bin/wxis1660.exe/decsserver/?IsisScript=../cgi-bin/decsserver/decsserver.xis&interface_language=" + decsLang + "&previous_page=homepage&previous_task=NULL&task=start";
	decsWindow = window.open(decsUrl, "decs", "height=550,width=750,menubar=yes,toolbar=yes,location=no,resizable=yes,scrollbars=yes,status=no");
	decsWindow.focus();
	
	return;
	
}

function showDeCSTerm( id ){
	
	lang = document.formSearch.lang.value;
	if (lang == "pt"){ decsLang = "p"; }
	if (lang == "es"){ decsLang = "e"; }
	if (lang == "en"){ decsLang = "i"; }
	
	decsUrl = "http://decs.bvs.br/cgi-bin/wxis1660.exe/decsserver/?IsisScript=../cgi-bin/decsserver/decsserver.xis&interface_language=" + decsLang + "&search_language=" + decsLang + "&previous_page=homepage&task=exact_term&search_exp=mfn=" + id + "#RegisterTop";
	decsWindow = window.open(decsUrl, "decsTerm", "height=450,width=630,menubar=yes,toolbar=yes,location=no,resizable=yes,scrollbars=yes,status=no");
	decsWindow.focus();
	
	return;
	
}

function searchWithDecs( query, label){

	searchForm = document.formSearch;
	// retira do action a ancora para a area de referencias
	searchFormNewAction = searchForm.action.substring(0,searchForm.action.indexOf('#references'));

	searchForm.action = searchFormNewAction;

	// zera os valores do querySearch e queryLabel 
	searchForm.querySearch.value = "";
	searchForm.queryLabel.value  = "";	
	searchForm.preview.value = "false";
	// seta os valores para a pesquisa pelo DeCS
	searchForm.decsSearch.value  = query;
	searchForm.decsLabel.value  = label;

	searchForm.submit();
	return;
}

