/* $Id: functions.js,v 1.7 2001/11/24 16:59:54 loic1 Exp $ */


/**
 * Displays an confirmation box beforme to submit a "DROP/DELETE/ALTER" query.
 * This function is called while clicking links
 *
 * @param   object   the link
 * @param   object   the sql query to submit
 *
 * @return  boolean  whether to run the query or not
 */
function controllas(formIndex, azione){
// Ricordarsi che se si vuole applicare il controllo di chiocciola e punto sugli indirizzi di casella e-mail
// il campo si deve chiamare o Mail o Newsletter

  testo="Sono stati riscontrati degli errori nei seguenti campi\n\n";
  controllo="No";
  for (iElement = 0; iElement < document.forms[formIndex].elements.length; iElement++){
    switch (document.forms[formIndex].elements[iElement].type){
    case 'text':
      if (document.forms[formIndex].elements[iElement].type != 'undefined' && document.forms[formIndex].elements[iElement].type == 'text' && document.forms[formIndex].elements[iElement].value.length < 2 || document.forms[formIndex].elements[iElement].value=='<Inserisci i tuoi dati>') {
	    controllo="Si";
        testo+=document.forms[formIndex].elements[iElement].name+"\n"
      } else {
	    if (document.forms[formIndex].elements[iElement].name=="Mail" || document.forms[formIndex].elements[iElement].name=="Newsletter"){
	      miaStringa = document.forms[formIndex].elements[iElement].value;
          if (miaStringa.indexOf("@")==(-1)  || miaStringa.indexOf(".")==(-1)) {
		    controllo="Si";
            testo+=document.forms[formIndex].elements[iElement].name+" - L'indirizzo e-mail non sembra valido\n"
          }
	    }
	  }
	  break;

    case 'textarea':
	  if (document.forms[formIndex].elements[iElement].value==''){
	    controllo="Si";
        testo+=document.forms[formIndex].elements[iElement].name+"\n"
	  }
	  break;

    case 'hidden':
	  if (document.forms[formIndex].elements[iElement].value==''){
	    controllo="Si";
        testo+=document.forms[formIndex].elements[iElement].name+"\n"
	  }
	  break;

    case 'select-one':
	  // RICORDARSI CHE QUANDO SI VUOLE BLOCCARE L UTENTE SULLE LIST BOX GLI ELEMENTI DELLA LISTA 
	  // NEI QUALI SI DEVE BLOCCARE L UTENTE NON IMPOSTARE IL VALORE VALUE
	  if (document.forms[formIndex].elements[iElement].value==''){
	    controllo="Si";
        testo+=document.forms[formIndex].elements[iElement].name+"\n"
	  }
	  break;
    }
  }
  if (controllo=="Si"){
    testo+="\nSi ricorda infine che per essere validi\nI campi devono contenere almeno due caratteri.";
    alert(testo);
	return false;
  } else {
   document.forms[formIndex].action=azione;
   document.forms[formIndex].submit();
  }
}

function controlla(formIndex, azione){
   document.forms[formIndex].action=azione;
   document.forms[formIndex].submit();
}


function valuta_colore(riga, controllo){
   if (controllo.checked==true){
     setPointer(riga, '#e3e3e3')
   } else {
     setPointers(riga, '')
   }
 }
 
function seleziona_uno() {
  selezione_trovata="no"
  quante=0
  if (frm.rec.value>1){
	for (q = 0 ; q<=frm.rec.value; q++){
      if (frm.id[q].checked==true){
	    quante++;
	  }
    }
    if (quante>1){
      quante=0
	  for (q = 0 ; q<=frm.rec.value; q++){
        if (frm.id[q].checked==true){
	      quante++;
		  if (quante>1){
		    frm.id[q].checked=false
		  }
		}
      }
      alert("E' stata rilevata una selezione multipla fra i record\nSi ricorda che per effettuare la modifica deve essere selezionato un solo record\nPertanto il sistema correggerà automaticamente la selezione lasciando selezionato solo il primo dei record selezionati!");
    }
  }
}
 
function fai_tutto() {
  frm = document.form1;
  if (frm.totale.checked==true){
  	 if (frm.rec.value>1){
	    for (i = 0 ; i<=frm.rec.value; i++){
          frm.id[i].checked=true
        }
	 } else {
        frm.id.checked=true
	 }
  } else {
  	 if (frm.rec.value>1){
	    for (i = 0 ; i<=frm.rec.value; i++){
          frm.id[i].checked=false
        }
	 } else {
        frm.id.checked=false
	 } 
  }	
}
 
function enviar(decisione, tabella, tipo) {
	frm = document.form1;
	//alert("Rec è: " + frm.rec.value);
	if (decisione==2){
	  controllo="no";
	  if (frm.rec.value>1){
	    for (i = 0 ; i<=frm.rec.value; i++){
          if (frm.id[i].checked==true){
            controllo="si"
          }
        }
	  } else {
          if (frm.id.checked==true){
            controllo="si"
          }
	  }
	  if (controllo=="no" || frm.rec.value==0){
		alert("Selezionare un prodotto prima!");
	    return false;
	  } else {
        if (confirm("ATTENZIONE!\rL'operazione cancellerà DEFINITIVAMENTE tutti i record (le righe) selezionati\rSei sicuro di voler proseguire?")){
	      frm.action="default.asp?tabella=" + tabella + "&type=" + tipo + "&azione=kill_record";
		  frm.submit();
		} else{
		  return false;
		}
	  } 
	}
	if (decisione==3){
	  seleziona_uno();
	  controllo="no";
 	  if (frm.rec.value>1){
	    for (i = 0 ; i<=frm.rec.value; i++){
          if (frm.id[i].checked==true){
            controllo="si"
          }
        }
	  } else {
          if (frm.id.checked==true){
            controllo="si"
          }
	  }
	  if (controllo=="no" || frm.rec.value==0){
		alert("Selezionare un prodotto prima!");
	    return false;
	  } else {
	    frm.action="default.asp?tabella=" + tabella + "&type=" + tipo + "&azione=modify_record";
		frm.submit();
	  }
	}
	if (decisione==4){
	  frm.action="default.asp?tabella=" + tabella + "&type=" + tipo + "&azione=new_record";
	  frm.submit();
	}

}

function confirmLink(theLink, theSqlQuery)
{
    // Confirmation is not required in the configuration file
    if (confirmMsg == '') {
        return true;
    }

    var is_confirmed = confirm(confirmMsg + ' :\n' + theSqlQuery);
    if (is_confirmed) {
        theLink.href += '&is_js_confirmed=1';
    }

    return is_confirmed;
} // end of the 'confirmLink()' function


/**
 * Displays an error message if a "DROP DATABASE" statement is submitted
 * while it isn't allowed, else confirms a "DROP/DELETE/ALTER" query before
 * sumitting it if required.
 * This function is called by the 'checkSqlQuery()' js function.
 *
 * @param   object   the form
 * @param   object   the sql query textarea
 *
 * @return  boolean  whether to run the query or not
 *
 * @see     checkSqlQuery()
 */
function confirmQuery(theForm1, sqlQuery1)
{
    // Confirmation is not required in the configuration file
    if (confirmMsg == '') {
        return true;
    }

    // The replace function (js1.2) isn't supported
    else if (typeof(sqlQuery1.value.replace) == 'undefined') {
        return true;
    }

    // js1.2+ -> validation with regular expressions 
    else {
        // "DROP DATABASE" statement isn't allowed
        if (noDropDbMsg) {
            var drop_re = new RegExp('DROP\\s+(IF EXISTS\\s+)?DATABASE', 'i');
            if (drop_re.test(sqlQuery1.value)) {
                alert(noDropDbMsg);
                theForm1.reset();
                sqlQuery1.focus();
                return false;
            } // end if
        } // end if

        // Confirms a "DROP/DELETE/ALTER" statement
        var do_confirm_re_0 = new RegExp('DROP\\s+(IF EXISTS\\s+)?(TABLE|DATABASE)', 'i');
        var do_confirm_re_1 = new RegExp('ALTER TABLE\\s+((`[^`]+`)|([A-Za-z0-9_$]+))\\s+DROP', 'i');
        var do_confirm_re_2 = new RegExp('DELETE FROM', 'i');
        if (do_confirm_re_0.test(sqlQuery1.value)
            || do_confirm_re_1.test(sqlQuery1.value)
            || do_confirm_re_2.test(sqlQuery1.value)) {
            var message      = (sqlQuery1.value.length > 100)
                             ? sqlQuery1.value.substr(0, 100) + '\n    ...'
                             : sqlQuery1.value;
            var is_confirmed = confirm(confirmMsg + ' :\n' + message);
            // drop/delete/alter statement is confirmed -> update the
            // "is_js_confirmed" form field so the confirm test won't be
            // run on the server side and allows to submit the form
            if (is_confirmed) {
                theForm1.elements['is_js_confirmed'].value = 1;
                return true;
            }
            // "DROP/DELETE/ALTER" statement is rejected -> do not submit
            // the form
            else {
                window.focus();
                sqlQuery1.focus();
                return false;
            } // end if (handle confirm box result)
        } // end if (display confirm box)
    } // end confirmation stuff

    return true;
} // end of the 'confirmQuery()' function


/**
 * Displays an error message if the user submitted the sql query form with no
 * sql query, else checks for "DROP/DELETE/ALTER" statements
 *
 * @param   object   the form
 *
 * @return  boolean  always false
 *
 * @see     confirmQuery()
 */
function checkSqlQuery(theForm)
{
    var sqlQuery = theForm.elements['sql_query'];

    // The replace function (js1.2) isn't supported -> basic tests
    if (typeof(sqlQuery.value.replace) == 'undefined') {
        var isEmpty  = (sqlQuery.value == '') ? 1 : 0;
        if (isEmpty && typeof(theForm.elements['sql_file']) != 'undefined') {
            isEmpty  = (theForm.elements['sql_file'].value == '') ? 1 : 0;
        }
        if (isEmpty && typeof(theForm.elements['id_bookmark']) != 'undefined') {
            isEmpty  = (theForm.elements['id_bookmark'].value == null || theForm.elements['id_bookmark'].value == '');
        }
    }
    // js1.2+ -> validation with regular expressions 
    else {
        var space_re = new RegExp('\\s+');
        var isEmpty  = (sqlQuery.value.replace(space_re, '') == '') ? 1 : 0;
        // Checks for "DROP/DELETE/ALTER" statements
        if (!isEmpty && !confirmQuery(theForm, sqlQuery)) {
            return false;
        }
        if (isEmpty && typeof(theForm.elements['sql_file']) != 'undefined') {
            isEmpty  = (theForm.elements['sql_file'].value.replace(space_re, '') == '') ? 1 : 0;
        }
        if (isEmpty && typeof(theForm.elements['id_bookmark']) != 'undefined') {
            isEmpty  = (theForm.elements['id_bookmark'].value == null || theForm.elements['id_bookmark'].value == '');
            isEmpty  = (theForm.elements['id_bookmark'].selectedIndex == 0);
        }
        if (isEmpty) {
            theForm.reset();
        }
    }

    if (isEmpty) {
        sqlQuery.select();
        alert(errorMsg0);
        sqlQuery.focus();
        return false;
    }

    return true;
} // end of the 'checkSqlQuery()' function


/**
 * Displays an error message if an element of a form hasn't been completed and
 * should be
 *
 * @param   object   the form
 * @param   string   the name of the form field to put the focus on
 *
 * @return  boolean  whether the form field is empty or not
 */
function emptyFormElements(theForm, theFieldName)
{
    var theField = theForm.elements[theFieldName];
    // Whether the replace function (js1.2) is supported or not
    var isRegExp = (typeof(theField.value.replace) != 'undefined');

    if (!isRegExp) {
        var isEmpty  = (theField.value == '') ? 1 : 0;
    } else {
        var space_re = new RegExp('\\s+');
        var isEmpty  = (theField.value.replace(space_re, '') == '') ? 1 : 0;
    }
    if (isEmpty) {
        theForm.reset();
        theField.select();
        alert(errorMsg0);
        theField.focus();
        return false;
    }

    return true;
} // end of the 'emptyFormElements()' function


/**
 * Ensures a value submitted in a form is numeric and is in a range
 *
 * @param   object   the form
 * @param   string   the name of the form field to check
 * @param   integer  the minimum authorized value
 * @param   integer  the maximum authorized value
 *
 * @return  boolean  whether a valid number has been submitted or not
 */
function checkFormElementInRange(theForm, theFieldName, min, max)
{
    var theField         = theForm.elements[theFieldName];
    var val              = parseInt(theField.value);

    if (typeof(min) == 'undefined') {
        min = 0;
    }
    if (typeof(max) == 'undefined') {
        max = Number.MAX_VALUE;
    }

    // It's not a number
    if (isNaN(val)) {
        theField.select();
        alert(errorMsg1);
        theField.focus();
        return false;
    }
    // It's a number but it is not between min and max
    else if (val < min || val > max) {
        theField.select();
        alert(val + errorMsg2);
        theField.focus();
        return false;
    }
    // It's a valid number
    else {
        theField.value = val;
    }

    return true;
} // end of the 'checkFormElementInRange()' function


/**
 * Ensures the choice between 'transmit', 'zipped', 'gzipped' and 'bzipped'
 * checkboxes is consistant
 *
 * @param   object   the form
 * @param   string   a code for the action that causes this function to be run
 *
 * @return  boolean  always true
 */
function checkTransmitDump(theForm, theAction)
{
    var formElts = theForm.elements;

    // 'zipped' option has been checked
    if (theAction == 'zip' && formElts['zip'].checked) {
        if (!formElts['asfile'].checked) {
            theForm.elements['asfile'].checked = true;
        }
        if (typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked) {
            theForm.elements['gzip'].checked = false;
        }
        if (typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked) {
            theForm.elements['bzip'].checked = false;
        }
    }
    // 'gzipped' option has been checked
    else if (theAction == 'gzip' && formElts['gzip'].checked) {
        if (!formElts['asfile'].checked) {
            theForm.elements['asfile'].checked = true;
        }
        if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
            theForm.elements['zip'].checked = false;
        }
        if (typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked) {
            theForm.elements['bzip'].checked = false;
        }
    }
    // 'bzipped' option has been checked
    else if (theAction == 'bzip' && formElts['bzip'].checked) {
        if (!formElts['asfile'].checked) {
            theForm.elements['asfile'].checked = true;
        }
        if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
            theForm.elements['zip'].checked = false;
        }
        if (typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked) {
            theForm.elements['gzip'].checked = false;
        }
    }
    // 'transmit' option has been unchecked
    else if (theAction == 'transmit' && !formElts['asfile'].checked) {
        if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
            theForm.elements['zip'].checked = false;
        }
        if ((typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked)) {
            theForm.elements['gzip'].checked = false;
        }
        if ((typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked)) {
            theForm.elements['bzip'].checked = false;
        }
    }

    return true;
} // end of the 'checkTransmitDump()' function


/**
 * Sets/unsets the pointer in browse mode
 *
 * @param   object   the table row
 * @param   object   the color to use for this row
 *
 * @return  boolean  whether pointer is set or not
 */
function setPointer(theRow, thePointerColor)
{
    if (typeof(theRow.style) == 'undefined' || typeof(theRow.cells) == 'undefined') {
        return false;
    }

    var row_cells_cnt           = theRow.cells.length;
    for (var c = 0; c < row_cells_cnt; c++) {
	  if (theRow.cells[c].bgColor != '#e3e3e3') {
        theRow.cells[c].bgColor = thePointerColor;
	  }
    }

    return true;
} // end of the 'setPointer()' function

function setPointers(theRow, thePointerColor)
{
    if (typeof(theRow.style) == 'undefined' || typeof(theRow.cells) == 'undefined') {
        return false;
    }

    var row_cells_cnt           = theRow.cells.length;
    for (var c = 0; c < row_cells_cnt; c++) {
        theRow.cells[c].bgColor = thePointerColor;
    }

    return true;
} // end of the 'setPointer()' function


function NewWindow1(larghezza, altezza){
	larghezza +=50;
	altezza +=120;
	barre="no";
	if (altezza>750){
	  altezza=550;
	  barre="yes";
	}
	var w = larghezza; 
	var h = altezza; 
	var pw = Math.floor(((screen.width-w)/2)); 
	var ph = Math.floor((screen.height-h)/2); 
	win1=window.open ("", "click_super", "history=no,top=" + ph +",left="+pw+",resizable=no,status=no,scrollbars="+barre+",menubar=no,width="+ larghezza +",height="+altezza);
}
