var tam = 12;

//---------------------------------- Legado do tema "Classic" ---------------------------------------- //

/*
 * Utility Javascript methods for DSpace
 */

// Popup window - here so it can be referred to by several methods
var popupWindow;

// =========================================================
//  Methods for e-person popup window
// =========================================================

// Add to list of e-people on this page -- invoked by eperson popup window
function addEPerson(id, email, name)
{
    var newplace = window.document.epersongroup.eperson_id.options.length;

    if (newplace > 0 && window.document.epersongroup.eperson_id.options[0].value == "")
    {
        newplace = 0;
    }

    // First we check to see if e-person is already there
    for (var i = 0; i < window.document.epersongroup.eperson_id.options.length; i++)
    {
        if (window.document.epersongroup.eperson_id.options[i].value == id)
        {
            newplace = -1;
        }
    }

    if (newplace > -1)
    {
        window.document.epersongroup.eperson_id.options[newplace] = new Option(name + " (" + email + ")", id);
    }
}

// Add to list of groups on this page -- invoked by eperson popup window
function addGroup(id, name)
{
    var newplace = window.document.epersongroup.group_ids.options.length;

	if (newplace > 0 && window.document.epersongroup.group_ids.options[0].value == "")
    {
        newplace = 0;
    }

    // First we check to see if group is already there
    for (var i = 0; i < window.document.epersongroup.group_ids.options.length; i++)
    {
        // is it in the list already
        if (window.document.epersongroup.group_ids.options[i].value == id)
        {
            newplace = -1;
        }

        // are we trying to add the new group to the new group on an Edit Group page (recursive)
        if (window.document.epersongroup.group_id)
        {
            if (window.document.epersongroup.group_id.value == id)
            {
                newplace = -1;
            }
        }
    }

    if (newplace > -1)
    {
        window.document.epersongroup.group_ids.options[newplace] = new Option(name + " (" + id + ")", id);
    }
}

// This needs to be invoked in the 'onClick' javascript event for buttons
// on pages with a dspace:selecteperson element in them
function finishEPerson()
{
    selectAll(window.document.epersongroup.eperson_id);

	if (popupWindow != null)
	{
		popupWindow.close();
	}
}

// This needs to be invoked in the 'onClick' javascript event for buttons
// on pages with a dspace:selecteperson element in them
function finishGroups()
{
    selectAll(window.document.epersongroup.group_ids);

    if (popupWindow != null)
    {
		popupWindow.close();
    }
}

// =========================================================
//  Miscellaneous utility methods
// =========================================================

// Open a popup window (or bring to front if already open)
function popup_window(winURL, winName)
{
    var props = 'scrollBars=yes,resizable=yes,toolbar=no,menubar=no,location=no,directories=no,width=640,height=480';
    popupWindow = window.open(winURL, winName, props);
    popupWindow.focus();
}


// Select all options in a <SELECT> list
function selectAll(sourceList)
{
    for(var i = 0; i < sourceList.options.length; i++)
    {
        if ((sourceList.options[i] != null) && (sourceList.options[i].value != ""))
            sourceList.options[i].selected = true;
    }
    return true;
}

// Deletes the selected options from supplied <SELECT> list
function removeSelected(sourceList)
{
    var maxCnt = sourceList.options.length;
    for(var i = maxCnt - 1; i >= 0; i--)
    {
        if ((sourceList.options[i] != null) && (sourceList.options[i].selected == true))
        {
            sourceList.options[i] = null;
        }
    }
}






//******************************************************
// Functions used by controlled vocabulary add-on
// There might be overlaping with existing functions
//******************************************************

function expandCollapse(node, contextPath) {
	node = node.parentNode;
	var childNode  = (node.getElementsByTagName("ul"))[0];

	if(!childNode) return false;

	var image = node.getElementsByTagName("img")[0];
	
	if(childNode.style.display != "block") {
		childNode.style.display  = "block";
		image.src = contextPath + "/image/controlledvocabulary/m.gif";
		image.alt = "Collapse search term category";
	} else {
		childNode.style.display  = "none";
		image.src = contextPath + "/image/controlledvocabulary/p.gif";
		image.alt = "Expand search term category";
	}
	
	return false;
}


function getAnchorText(ahref) {
 	if(isMicrosoft()) return ahref.childNodes.item(0).nodeValue;
	else return ahref.text;
}

function getTextValue(node) {
 	if(node.nodeName == "A") {
 		return getAnchorText(node);
 	} else {
 		return "";
 	}
 	
}


function getParentTextNode(node) {
	var parentNode = node.parentNode.parentNode.parentNode;
	var children = parentNode.childNodes;
	var textNode;
	for(var i=0; i< children.length; i++) {
		var child = children.item(i);
		if(child.className == "value") {
			return child;
		}
	}
	return null;
}

function ec(node, contextPath) {
	expandCollapse(node, contextPath);
	return false;
}


function i(node) {
	return sendBackToParentWindow(node);
}


function getChildrenByTagName(rootNode, tagName) {
	var children = rootNode.childNodes;
	var result = new Array(0);
	if(children == null) return result;
	for(var i=0; i<children.length; i++) {
		if(children[i].tagName == tagName) {
			var elementArray = new Array(1);
			elementArray[0] = children[i];
			result = result.concat(elementArray);
		}
	}
	return result;
}

function popUp(URL) {
	var page;
	page = window.open(URL, 'controlledvocabulary', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=650,height=450');
}

/**
 * Comentando codigo inutilizado que esta dando em alguns browsers
 */
/*
function isNetscape(v) {
		  return isBrowser("Netscape", v);
}
	
function isMicrosoft(v) {
		  return isBrowser("Microsoft", v);
}

function isMicrosoft() {
		  return isBrowser("Microsoft", 0);
}


function isBrowser(b,v) {
		  browserOk = false;
		  versionOk = false;

		  browserOk = (navigator.appName.indexOf(b) != -1);
		  if (v == 0) versionOk = true;
		  else  versionOk = (v <= parseInt(navigator.appVersion));
		  return browserOk && versionOk;
}*/

//INICIO: 	VERIFICACAO DE PREENCHIMENTO DE CAMPOS -------------------------------
function isValidToSave(){
	
	if (verifyLanguage() && verifyResourcesTypes() && verifyNodesChecked()) {		
		return true;
	} else {
		return false;
	}
}

/**
	* Verifica existencia de algum valor nao checado 
	* nos campos de idioma
	*/
function verifyLanguage(){
	var checks = document.getElementsByName("languages");
	for(var i = 0; i < checks.length; i++){
		if(checks[i].checked){
			return true;
		}
	}
	showAlert("um", "Idiomas", "o");
	return false;
}

function verifyResourcesTypes(){
	var tableOfResources = document.getElementById("aspect_eperson_CollectionApproval_table_resources-table");
	var checks = tableOfResources.getElementsByTagName("input");
	for(var i = 0; i < checks.length; i++){
		if(checks[i].type == "checkbox" && checks[i].checked){
			return true;
		}
	}
	showAlert("um", "Tipos de recurso", "o");
	return false;
}

/**
 * Seleciona checkboxes por nome
 * @param checkName Tag "name" do select a ser marcado
 * @return
 */
function selectChecksByName(checkName) {
	
	var selects = document.getElementsByName(checkName);
	for(var i = 0; i < selects.length ; i++) {
		selects[i].checked = true;
	}	
	
}


// Verifica existencia de algum valor nao checado
// nos nodos da arvore
function verifyNodesChecked(){

	var children = document.getElementsByName("check_community_parent_0");
	var isValid = true;
	for(var i = 0; i < children.length ; i++){
		isValid = verifyFamilyChecked(children[i]);
		if (isValid) return true;
	}	
	showAlert("uma", "Modalidades de Ensino", "a");
	return false;		
}

function verifyFamilyChecked(idCheck){

	if(idCheck.checked == true){
		return true;
	}
	// O elemento corrente nao esta checado, os filhos devem ser verificados
	var idStr = idCheck.getAttribute("value");	
	var children = document.getElementsByName("check_community_parent_" + idStr);

	for(var i = 0; i < children.length; i++){
		if(verifyFamilyChecked(children[i])) return true;
	}
	return false;
}

function showAlert(umOrUma, msg, oOrA){
	window.alert("Para enviar esta solicitacao, " + umOrUma + " ou mais \"" + msg +"\" \ndevem ser selecionad" + oOrA +"s.");
}

function mudaOrder(valor, selecionado){
        var campoFiltro = pegaSelect("aspect_artifactbrowser_ConfigurableBrowse_field_sort_by");
        var campoOrderBy = pegaSelect("aspect_artifactbrowser_ConfigurableBrowse_field_order");   
        var ordem;
        if (selecionado.className.indexOf("up") > 0){
        	ordem = "DESC";
        } else {
        	ordem = "ASC";
        }
        for (var i = 0; i < campoFiltro.options.length; i++){
        	if (campoFiltro.options[i].value == valor){
        		campoFiltro.options[i].selected = "true";
        		break;
        	}
        }
        
        for (var i = 0; i < campoOrderBy.options.length; i++){
        	if (campoOrderBy.options[i].value == ordem){
        		campoOrderBy.options[i].selected = "true";
        		break;
        	}
        }
        
        document.getElementById("aspect_artifactbrowser_ConfigurableBrowse_div_browse-controls").submit();
}

function mudaOrderAdvancedSearch(valor, selecionado){
    var campoFiltro = pegaSelect("aspect_artifactbrowser_AdvancedSearch_field_sort_by");
    if (campoFiltro == null){
    	campoFiltro = pegaSelect("aspect_artifactbrowser_SimpleSearch_field_sort_by");
    }
    var campoOrderBy = pegaSelect("aspect_artifactbrowser_AdvancedSearch_field_order");   
    if (campoOrderBy == null){
    	campoOrderBy = pegaSelect("aspect_artifactbrowser_SimpleSearch_field_order");
    }
    var ordem;
    if (selecionado.className.indexOf("up") > 0){
    	ordem = "DESC";
    } else {
    	ordem = "ASC";
    }
    for (var i = 0; i < campoFiltro.options.length; i++){
    	if (campoFiltro.options[i].value == valor){
    		campoFiltro.options[i].selected = "true";
    		break;
    	}
    }
    
    for (var i = 0; i < campoOrderBy.options.length; i++){
    	if (campoOrderBy.options[i].value == ordem){
    		campoOrderBy.options[i].selected = "true";
    		break;
    	}
    }
    document.forms[1].submit();
}

function verificaOrder(){
    var campoFiltro = pegaSelect("aspect_artifactbrowser_ConfigurableBrowse_field_sort_by");
    var campoOrderBy = pegaSelect("aspect_artifactbrowser_ConfigurableBrowse_field_order");
    if(campoFiltro != null){
	    var campo;
	    var classe;
	    if (campoOrderBy.value == "ASC"){
	    	classe = " up";
	    } else {
	    	classe = " down";
	    }
	    if (document.getElementById("coluna_data") != null){
			document.getElementById("coluna_data").className = "ds-table-header-cell odd";	
			document.getElementById("coluna_tipo").className = "ds-table-header-cell even";
			document.getElementById("coluna_titulo").className = "ds-table-header-cell odd";
			document.getElementById("coluna_autores").className = "ds-table-header-cell even";
		    if (campoFiltro.value == "1"){
		    	campo = document.getElementById("coluna_titulo");
		    } else if (campoFiltro.value == "2"){
		    	campo = document.getElementById("coluna_data");
		    } else if (campoFiltro.value == "3"){
		    	campo = document.getElementById("coluna_tipo");
		    } else {
		    	campo = document.getElementById("coluna_autores");
		    }
		    campo.className = campo.className + classe;
	    }
    }
}

function verificaOrderAdvancedSearch(){
    var campoFiltro = pegaSelect("aspect_artifactbrowser_AdvancedSearch_field_sort_by");
    var campoOrderBy = pegaSelect("aspect_artifactbrowser_AdvancedSearch_field_order");
    if (campoFiltro == null){
    	campoFiltro = pegaSelect("aspect_artifactbrowser_SimpleSearch_field_sort_by");
    }
    if(campoOrderBy == null){
    	campoOrderBy = pegaSelect("aspect_artifactbrowser_SimpleSearch_field_order");
    }
    if(campoFiltro != null){
	    var campo = null;
	    var classe;
	    if (campoOrderBy.value == "ASC"){
	    	classe = " up";
	    } else {
	    	classe = " down";
	    }
	    if (document.getElementById("coluna_data") != null){
			document.getElementById("coluna_data").className = "ds-table-header-cell odd";	
			document.getElementById("coluna_tipo").className = "ds-table-header-cell even";
			document.getElementById("coluna_titulo").className = "ds-table-header-cell odd";
			document.getElementById("coluna_autores").className = "ds-table-header-cell even";
		    if (campoFiltro.value == "1"){
		    	campo = document.getElementById("coluna_titulo");
		    } else if (campoFiltro.value == "2"){
		    	campo = document.getElementById("coluna_data");
		    } else if (campoFiltro.value == "3"){
		    	campo = document.getElementById("coluna_tipo");
		    } else if (campoFiltro.value == "4") {
		    	campo = document.getElementById("coluna_autores");
		    }
		    if (campo != null){
		    	campo.className = campo.className + classe;
		    }
	    }
    }
}

function pegaSelect(nomeCampo){
	var selects = document.getElementsByTagName("select");
	for(var i = 0; i < selects.length; i++){
		if(selects[i].id == nomeCampo){
			return selects[i];
			break;
		}
	}
	
}

//FIM:		VERIFICACAO DE PREENCHIMENTO DE CAMPOS -------------------------------

/**
 * Funcao que esconde ou exibe o elemento HTML de acordo com seu id
 */
function showOrHide(id) 
{
	var elm = document.getElementById(id);
	if (elm.style.display != 'block')
	{
		elm.style.display = 'block';
	}
	else
	{
		elm.style.display = 'none';
	}
}


function hide(id) 
{
	var elm = document.getElementById(id);
	if (elm != null){
		if (elm.className == 'ds-static-div div-adv-first')
		{
			elm.style.display = 'none';
			elm.className = 'ds-static-div';
		}else if (elm.className == 'ds-static-div div-detail-first'){
			elm.style.display = 'none';
			elm.className = 'ds-static-div';
		} else {
			elm.style.display = 'none';
		}
	}
}

function escapeHTML(){
	var item = document.getElementById("aspect.administrative.highlights.ShowInitialPageHighlights.item.highlight");
	if (item == null){
		item = document.getElementById("aspect_administrative_highlights_HighlightViewer_div_highlight-viewer");
	}
	if (item != null){
		var s = item.innerHTML;
		s = replaceAll(s,"&lt;","<");
		s = replaceAll(s,"&gt;",">");
		s = replaceAll(s,"&nbsp;","<br />");
		s = replaceAll(s,"nbsp;"," ");
		item.innerHTML = s;
	}
}

function replaceAll(string, token, newtoken) {
	while (string.indexOf(token) != -1) {
 		string = string.replace(token, newtoken);
	}
	return string;
}

function getInfo(){
	var i =0;
	for (p in navigator){
		alert(' : '+navigator[p]);
		i++;
		if (i == 2){
			break;
		}
	}
	}

function identifyBrowser() {
	    alert(navigator.userAgent);
	}

/**
 * Funções responsáveis por manipular a div de Tooltip dos portais OAI
 * na busca principal do portal.
 */
$(document).ready(
		function() {
			var tooltips = $(".tooltip-container");
			for(var i = 0; i < tooltips.length; i++) {
				var currentTooltip = tooltips[i];
				$("#" + currentTooltip.id + " label.ds-form-label").tooltip(
						{effect: 'toggle', tip: '#tooltip' + currentTooltip.id, align: 'right'}
				);      
		}
});

/**
*	Método responsável por compartilhar um item
*	na rede social escolhida.
*
*	@param socialNetwork.
*		A rede social na qual será compartilhado o item.
**/

function shareItem( socialNetwork ){
	//initialize
	var	sharedURL 	=	encodeURIComponent(window.location.href);
	var	title 		= 	getMetaValue("title");
	var paramsPopUp = 	'width=640, height=480, toolbar=no, scrollbars=yes, status=yes';
	var mainURL 	=	"";
	var titlePopUp  = 	"";
	
	switch( socialNetwork ) {
		case 'twitter':
			titlePopUp 	= "Compartilhar no Twitter";
			twitterURL	= "http://twitter.com/home?status=";
			mainURL 	= twitterURL + title + " - " + sharedURL;
		break;
		
		case 'facebook':
			titlePopUp 	= "Compartilhar no Facebook";
			facebookURL = "http://www.facebook.com/sharer.php?";		
			mainURL 	= facebookURL +  "u=" + sharedURL;
		break;
			
		case 'orkut':
			var content = "";
			titlePopUp 	= "Compartilhar no Orkut";
			content = getMetaValue("description");
			/*content 	= encodeURIComponent(document.getElementById("aspect_artifactbrowser_ItemViewer_field_item-description").value);*/
			orkutURL 	= "http://promote.orkut.com/preview?nt=orkut.com&";
			mainURL 	= orkutURL + "tt=" + title + "&cn=" + content + "&du=" + sharedURL;
		break;
	}
	
	if (window.navigator.appName == "Microsoft Internet Explorer"){
		titlePopUp='';
	}
	
	window.open(mainURL, titlePopUp , paramsPopUp);
}

function getMetaValue (name){
	var metaArrays = document.getElementsByTagName("META");
	var i = 0;
	for (i=0;i<metaArrays.length;i++){
		if (metaArrays[i].name == name){
			return metaArrays[i].content;
		}
	}
	return null;
}

function setStyle(element, property, value){
	$("#"+element).css(property, value);
}

function addSelectedPortal(id){
	window.alert("id:" + id); 
}
/**
 * Adiciona ou remove input hidden dos OAI Portal
 * no html, conforme id passado por parâmetro.
 * 
 * @param id
 * @return
 */
function addOrRemoveOAIPortal(id){
	var flag = 0;
	$.each(document.getElementsByName("selected-remote-portal"), function(){
		if($(this).val() == id){
			$(this).remove();
			flag++;
		}
	});
	
	if(flag == 0){
		$("#ds-search-form").append("<input name='selected-remote-portal' type='hidden' value='" + id + "' />");
	}
}
