function trim(str) {
   while (str.charAt(str.length - 1)==" ")
        str = str.substring(0, str.length - 1);
  while (str.charAt(0)==" ")
        str = str.substring(1, str.length);
  return str;
        }

		//funzione per recuperare velocemente il valore (campo value) di un campo input (non so se funziona con tutti: sicuramente con text/textarea funziona)
		//prende in ingresso una stringa contenente l'ID dell'elemento
        function getElementValue(str){
        element = document.getElementById(str);
        return trim(element.value);
        }

		//funzione per settare velocemente il valore (value) di un campo input (non so se funziona con tutti: sicuramente con text/textarea funziona)
		//prende in ingresso una stringa contenente l'ID dell'elemento
        function setElementValue(element, value){
        document.getElementById(element).value = value;
        }
		
		
		//funzione per recuperare velocemente il valore di un'opzione selezionata in una select.
		//prende in ingresso la stringa contenente l'ID della select
        function getSelectedValue(str){
        element = document.getElementById(str);
        index = element.selectedIndex;
        return element.options[index].value;

        }


		
		
		//controlla che non ci siano spazi in una stringa
		//ritorna vero se ne trova, falso altrimenti
		function checkIfSpaces(str){
			if (/\s/.test(str)){
				return true;
			}
			return false;
		}

		function closeChild(){
			if (typeof dialogwindow != "undefined" ) dialogwindow.close();
		}

		function giveFocusToChild(){
			if (typeof dialogwindow != "undefined" ) dialogwindow.focus();
		}

        function displayMessage(message){
        status_bar = document.getElementById("message_bar");
        status_bar.innerHTML = '<font color=white><b>' + message + '</B></font>';
				window.scrollTo(0,0);
				window.alert(message);
        }

        function displayErrorMessage(message){
        status_bar = document.getElementById("message_bar");
        status_bar.innerHTML = '<font color=red><B>' + message + '</B></font>';
				window.scrollTo(0,0);
				window.alert(message);
        }

        function validateEmail(email){
       var email_reg_exp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$/;
       if (!email_reg_exp.test(email)){
   return false;
       } else {
        return true;
        }
        }

        function showPreview(string){
        conditions = 'height=450, width=400, location=no, scrollbars=yes, menubar=no, resizable=yes, toolbar=no, top=' + (screen.height/2-150) + ', left=' + (screen.width/2-150);
        dialogwindow=window.open('../include/show_preview.php', '_blank', conditions);
        }


        //controlla che ci sia http:// all'inizio di un url
        function checkHttp(str){
        return /^(http:\/\/)/.test(str);
        }

function MultiDimensionalArray(iRows,iCols) {
  var i;
  var j;
  var a = new Array(iRows);
  for (i=0; i < iRows; i++) {
    a[i] = new Array(iCols);
    for (j=0; j < iCols; j++) {
      a[i][j] = "";
    }
  }
  return(a);
}

        function changeNumRows(){
        sel = document.getElementById("num_rows");
        index = sel.selectedIndex;
        value = sel.options[index].value;
        str = "../include/changeNumRows.php?value=" + value;
        window.location = str;
        }


        //la funzione prende in ingresso l'id di una textarea e il numero di caratteri a cui limitarla
        //ritorna falso se non e' stato modificato il contenuto della textarea, vero se lo e' stato
        function limitText(id, limit){
        txtarea = document.getElementById(id);
        if (txtarea.type != "textarea"){
        alert("limitText function is intended for Textareas!");
        return false;
        }
        if (txtarea.value.length<limit) return false;
        txtarea.value = txtarea.value.slice(0,limit-1);
        return true;
        }


        //funzione che apre un'immagine in una nuova finestra
        function openImageWindow(URL){
        conditions = 'height=150, width=300, location=no, menubar=no, scrollbar=no, resizable=yes, toolbar=no';
        dialogwindow=window.open(URL, '_blank', conditions);
        return;
        }

        //questa funzione controlla che il nome di file passato in fileName abbia estensione
        //uguale a quella specificata in extension
        function checkExtension(fileName, extension){
        index = fileName.lastIndexOf(".");
        ext = fileName.substring(index+1).toLowerCase();
        extension = extension.toLowerCase();
        if (ext == extension){
        return true;
        } else {
        return false;
        }
        }


//la stringa in ingresso contiene la data da controllare:
//la data viene validata se nel formato YYYY-MM-DD
        function validateMySqlDate(string){

        if (string.length>10){
        //se la stringa e' piu' lunga di 10 c'e' sicuraente un errore nel formato
        return false;
        }
        //controllo con le erpessioni regolari che il formato sia giusto
        if (/\d\d\d\d-\d\d-\d\d/.test(string)){
        //il formato e' giusto: scindo la data negli elementi singoli
        year = parseInt(string.substr(0,4));
        month = parseInt(string.substr(5,2)) - 1;
        day = parseInt(string.substr(8,2));

        //per controllare che la data sia valida creo un oggetto Date Javascript e poi controllo
        //che corrispondano giorno mese e anno. N.B. I mesi vengono indicati da 0 a 11 in Javascript!!!!!!!!!
        date = new Date(year, month, day);

        if ((year == date.getFullYear()) && (month == date.getMonth()) && (day == date.getDate())){
        //la data e' corretta.
         return true;
        } else {
        return false;
        }
        } else {
        return false;
        }
        }

//le funzioni seguenti mi servono per tutti i cmapi di testo che prevedono la possibilita' di formattazione
function swap_pressed(id){
        img = document.getElementById(id);
        if (id == "corsivo"){
        img.src="../imgs/corsivo_pressed.gif";
        }
        if (id == "grassetto"){
        img.src="../imgs/grassetto_pressed.gif";
        }
        if (id == "preview"){
        img.src="../imgs/preview_pressed.gif";
        }
        if (id == "link"){
        img.src="../imgs/link_pressed.gif";
        }
        if (id == "email"){
        img.src="../imgs/email_pressed.gif";
        }
}

function swap_released(id){
        img = document.getElementById(id);
        if (id == "corsivo"){
        img.src="../imgs/corsivo.gif";
        }
        if (id == "grassetto"){
        img.src="../imgs/grassetto.gif";
        }
        if (id == "preview"){
        img.src="../imgs/preview.gif";
        }
        if (id == "link"){
        img.src="../imgs/link.gif";
        }
        if (id == "email"){
        img.src="../imgs/email.gif";
        }
}


 function insertTag(open, close) {
        var txa = document.getElementById('Testo');
        if(txa.selectionEnd) {
          var lng = txa.textLength;
          var from = txa.selectionStart;
          var to = txa.selectionEnd;
          txa.value = txa.value.substring(0, from) + open + txa.value.substr(from, to) + close + txa.value.substring(to, lng);
        } else if(browser =='explorer') {
          var str = document.selection.createRange().text;
          txa.focus();
          var sel = document.selection.createRange();
          sel.text = open + str + close;
        }
 }


function checkLength(id, length){
        if (limitText(id, length)){
        alert("Attenzione!\n Il campo di testo Abstract e' stato limitato a 255 caratteri!\nRicontrollane il contenuto.");
        }
}



 function insertLink(){
        var url = prompt('Inserisci l\'indirizzo\n ("http://" è necessario per un corretto funzionamento)', "http://")
        if (url=="") return;
        if (browser=="explorer"){
    start="<a href=\"" + url + "\" target=\"_blank\">";
    end="</a>";
    insertTag(start, end);
    return;
        }
        var testo = prompt('Inserisci il testo da visualizzare','');
        if (!testo) return;
        mod = document.getElementById('Testo');
        mod.value += ('<a href="'+url+'" target="_blank">'+testo+'</a>');
 }

 function insertEmail(){
        var email = prompt('Inserisci l\'indirizzo email');
        if (!(validateEmail(trim(email)))){
    alert("L'Email inserita ha un formato scorretto!");
    return;
        }
         if (browser=="explorer"){
    start='<a href="mailto:'+email+'">';
    end="</a>";
    insertTag(start, end);
    return;
        }
        var testo = prompt('Inserisci il testo da visualizzare','');
        if (!testo) return;
        mod = document.getElementById('Testo');
        mod.value += ('<a href="mailto:'+email+'">'+testo+'</a>');
 }
