// JavaScript Document

function setOrdineDocumenti(pCampo,pSort){
    nomeForm = 'cerca_messaggi';
    document.forms[nomeForm].order.value=pCampo;
    document.forms[nomeForm].sort.value=pSort;
    document.forms[nomeForm].submit();
}

//Controllo Application Form
function checkApplicationForm(){
	nomeForm = 'iscrizione';
	document.MM_returnValue = false;
	MM_validateForm('COGNOME','','R','Family name','NOME','','R','First name','DATA_NASCITA','','RCHECKDATA','Date of birth','LUOGO_NASCITA','','R','Place of birth','INDIRIZZO','','R','Personal address','CAP','','R','ZIP/Postal code','CITTA_PAESE','','R','Country','TELEFONO','','R','Phone n°','EMAIL','','RisEmail','E-mail','CONOSCENZA_CORSO','','R','How did you learn about this course','FORMAZIONE_TITOLO_1','','R','Certificates or degrees obtained 1 ','FORMAZIONE_LUOGO_1','','R','Institution (name, place) 1','FORMAZIONE_PERIODO_1','','R','From/to month/year 1','LINGUA_INGLESE_PARLATO','','R','English SPEAK','LINGUA_INGLESE_LETTO','','R','English READ','LINGUA_INGLESE_SCRITTO','','R','English WRITE ','ENTE','','R','Name of institution','CITTA_PAESE_ENTE','','R','Country institution','TELEFONO_ENTE','','R','Phone n° institution','EMAIL_ENTE','','RisEmail','E-mail institution','ID_TIPO_ENTE','','R','Type of organisation','ESPERIENZA_PROFESSIONALE','','R','Professional background');
	if (document.MM_returnValue){
		document.forms[nomeForm].action = 'application_form_ok.php';
		document.forms[nomeForm].submit();
	}
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

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 MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  //alert(args);
  for (i=0; i<(args.length-2); i+=4) { test=args[i+2]; val=MM_findObj(args[i]);
	if (test=="RBORSADISTUDIO"){ //Modifica per Borsa di studio
		if (MM_findObj(args[i]).checked){
			if (MM_findObj('BORSA_DI_STUDIO_RESPONSABILE').value==""){errors += '- '+ 'Responsible for pay' + ' is required.\n';}
		}else{
			if (MM_findObj('PAGAMENTO_RESPONSABILE').value==""){errors += '- '+ 'Payments of course fee' + ' is required.\n';}
		}
	};
	if (test=="RRADIO"){//Modifica per Radio
		valoreCheck1 = MM_findObj(args[i]+'1');
		valoreCheck2 = MM_findObj(args[i]+'2');
		if ((valoreCheck1.checked==false)&&(valoreCheck2.checked==false)) { errors += '- '+ args[i+3] + ' is required.\n';}
	};
    if (val) { nm=args[i+3]; if ((val=val.value)!="") {
		if (test.indexOf('CHECKDATA')!=-1) {
			if (check_date(val)) errors += '- '+nm+'- The format of the date controls (ex. 31/01/2003).\n';}
	  if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
	  	charNotValid=val.indexOf('	');
        if ((charNotValid>-1)||(p<1 || p==(val.length-1))) errors+='- '+nm+' must contain an e-mail address.\n';
      } else if ((test!='R') && (test.indexOf('CHECKDATA')==-1)) { 
	  	num = parseFloat(val);
	  	if (isNaN(val) && (test!="RRADIO")) errors+='- '+nm+'  must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' must contain a number between  '+min+' e '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
  } if (errors) alert('The following error(s) occurred:\n'+errors);
  document.MM_returnValue = (errors == '');
}

function check_date(valore_campo) {
	var error = false;
	var controllo_prima_parte = 31;
	var controllo_seconda_parte = 12;
	arrayOfStrings = valore_campo.split("/");
	if (((isNaN(arrayOfStrings[0]) == true) || (arrayOfStrings[0] > controllo_prima_parte)) ||((isNaN(arrayOfStrings[1]) == true) || (arrayOfStrings[1] > controllo_seconda_parte)) || ((isNaN(arrayOfStrings[2]) == true) || (arrayOfStrings[2].length != 4)))
	{	
		error = true;
	}
	return error;
}

function format_date_sql(valore_campo) {
	arrayDate = valore_campo.split("/");
	anno = arrayDate[2];
	mese = arrayDate[1];
	giorno = arrayDate[0];
	data_formato_sql = anno + '-' + mese + '-' + giorno;
	return data_formato_sql;
}


function check_mail(valore_campo) {
	var errore = "falso";
	if (valore_campo.indexOf('@') < 1 )
		{ errore = "vero"; }
	if (valore_campo.indexOf('.') < 1 )
		{ errore = "vero"; }
	return errore;
}

function check_nome_file(valore_campo, elenco_caratteri_validi) {
	var percorso_file = valore_campo.split("\\");
	var num_elementi = percorso_file.length;
	var nome_file_completo = percorso_file[num_elementi-1].toLowerCase();
	var nome_file = nome_file_completo.split(".");
	var num_elementi_file = nome_file.length;
	var nome_file_no_ext = "";
	var errore = "falso";
	if (num_elementi_file > 2) {
		errore = "vero";
	} else {
		nome_file_no_ext = nome_file[0];
	}
	if (errore == "falso") {
		for (var i=0;i<nome_file_no_ext.length;i++) {
			if (elenco_caratteri_validi.indexOf(nome_file_no_ext.substr(i,1)) < 0) {
				errore = "vero";
				break;
			}
		}
	}
	return errore;
}


function check_estensione_file(valore_campo, elenco_estensioni_valide) {
	var percorso_file = valore_campo.split("\\");

	var num_elementi = percorso_file.length;
	var nome_file_completo = percorso_file[num_elementi-1].toLowerCase();
	var nome_file = nome_file_completo.split(".");
	var num_elementi_file = nome_file.length;
	var estensione_file = "";
	var errore = "falso";
	if (num_elementi_file > 2) {
		errore = "vero";
	} else {
		estensione_file = "." + nome_file[1];
	}
	if (errore == "falso") {
		if (elenco_estensioni_valide.indexOf(estensione_file) < 0) {
			errore = "vero";
		}
	}
	return errore;
}


function check_numeri(valore_campo) {
	var errore = "falso";
	var elenco_caratteri_validi = "0123456789";
	for (var i=0;i<valore_campo.length;i++) {
		if (elenco_caratteri_validi.indexOf(valore_campo.substr(i,1))<0) {
			errore = "vero";
			break;
		}
	}
	return errore;
}


function check_url(valore_campo) {
	var errore = "falso";
	var re
	re = new RegExp("(http|ftp|https)://[-A-Za-z0-9._/]+")
	if (re.test(valore_campo) == false)	errore = "vero";
	return errore;
}


function LTrim(valore_campo) {
   var whitespace = new String(" \t\n\r");
   if (whitespace.indexOf(valore_campo.charAt(0)) != -1) {
      var j=0, i = valore_campo.length;
      while (j < i && whitespace.indexOf(valore_campo.charAt(j)) != -1)
         j++;
      valore_campo = valore_campo.substring(j, i);
   }
   return valore_campo;
}


function RTrim(valore_campo) {
   var whitespace = new String(" \t\n\r");
   if (whitespace.indexOf(valore_campo.charAt(valore_campo.length-1)) != -1) {
      var i = valore_campo.length - 1; 
      while (i >= 0 && whitespace.indexOf(valore_campo.charAt(i)) != -1)
         i--;
      valore_campo = valore_campo.substring(0, i+1);
   }
   return valore_campo;
}


function trim(valore_campo) {
   return RTrim(LTrim(valore_campo));
}


function openNewWindow(url,windowW,windowH,windowName,visualizza_scroll) {
	var windowX = Math.ceil( (window.screen.width  - windowW) / 2 );
	var windowY = Math.ceil( (window.screen.height - windowH) / 2 );
	if (visualizza_scroll == '') {
		visualizza_scroll = 'no';
	}
	if (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion)>=4)
		{windowH = windowH + 30; windowW = windowW + 10;}
	if (navigator.appName == "Netscape" && parseInt(navigator.appVersion)>=5)
		{windowH = windowH + 29; windowW = windowW + 7;}
	var splashWin = window.open(url, windowName, 'status=yes, toolbar=no, scrollbars='+visualizza_scroll+', resizable=yes, width=' + windowW + ', height= ' + windowH);
	splashWin.resizeTo (Math.ceil(windowW), Math.ceil(windowH))
	splashWin.moveTo (Math.ceil(windowX), Math.ceil(windowY))
	splashWin.focus();
	if (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion)>=4)
		{windowH = windowH - 30; windowW = windowW - 10;}
	if (navigator.appName == "Netscape" && parseInt(navigator.appVersion)>=5)
		{windowH = windowH - 29; windowW = windowW - 7;}
}

//*********************************************
//*********************************************
//*********************************************
//**************GESTIONE UTENZA*******************************

//Funzione di set Sessione
function setSessione(idSessione){
	if (idSessione!="") {
		//Combo Utenti
		setComboTipoUtenti(idSessione);
		//Privilegi Utenza
		reset_all_policies();
		reset_all_checked()
		//Abilitazione Combo Box Moduli Sessione
		setCheckModuli(idSessione);
	}else{
		//Combo Utenti
		document.modifica_utente.elements['COMBO_UTENTI'].options.length =0;
		document.modifica_utente.elements['COMBO_UTENTI'].disabled="disabled";
		//Privilegi Utenza
		reset_all_policies();
		reset_all_checked()
		//Disabilitazione Combo Box Moduli Sessione
		strModuliTotali = strModuliTot.slice(0,(strModuliTot.length)-1);
		setenabled(strModuliTotali,"disabled");
		setchecked(strModuliTotali,false);
		//Disabilitazione Select Tutor
		strComboTutorTotali = strComboTutorTot.slice(0,(strComboTutorTot.length)-1);
		setenabled(strComboTutorTotali,"disabled");
		setValueSelect(strComboTutorTotali,0);
	}
}

//Funzione di abilitazione check dei moduli per la sessione selezionata
function setCheckModuli(idSessione){
	//Elenco Campi Moduli
	strModuli = eval("arCheckModuli"+idSessione);
	strModuli = strModuli.slice(0,(strModuli.length)-1);
	//Elenco id Moduli
	strIdModuli = eval("arCheckIdModuli"+idSessione);
	strIdModuli = strIdModuli.slice(0,(strIdModuli.length)-1);
	//Moduli Totali
	strModuliTotali = strModuliTot.slice(0,(strModuliTot.length)-1);
	setenabled(strModuliTotali,"disabled");
	setchecked(strModuliTotali,false);
	setenabled(strModuli,"");
	setchecked(strModuli,true);
	//Tutor
	comboTutorValide = eval("arComboTutor"+idSessione);
	comboTutorValide = comboTutorValide.slice(0,(comboTutorValide.length)-1);
	strComboTutorTotali = strComboTutorTot.slice(0,(strComboTutorTot.length)-1);
	setenabled(strComboTutorTotali,"disabled");
	setValueSelect(strComboTutorTotali,0);
	//Campi nascosti nel form
	document.modifica_utente.elements['ELENCO_SESSIONI_MODULI'].value =strModuli;
	document.modifica_utente.elements['ELENCO_ID_SESSIONI_MODULI'].value =strIdModuli;
	document.modifica_utente.elements['ELENCO_COMBO_TUTOR'].value =comboTutorValide;
}


//Funzione di set combo Utente in base alla sessione selezionata
function setComboTipoUtenti(idSessione){
	myArCombo = eval("comboUtenti"+idSessione);
	//Set Option a Null
	document.modifica_utente.elements['COMBO_UTENTI'].disabled="disabled";
	document.modifica_utente.elements['COMBO_UTENTI'].options.length =0;
	//Set default Option
	document.modifica_utente.elements['COMBO_UTENTI'].options[0]= new Option("Seleccione","",false,true);
	//Set Tipologie utenza
	for (i = 0; i < myArCombo.length; i++){
		document.modifica_utente.elements['COMBO_UTENTI'].options[i+1]= new Option(myArCombo[i][1],myArCombo[i][0],false,false);
	}
	document.modifica_utente.elements['COMBO_UTENTI'].disabled="";
}

//Funzione set Permessi e Privilegi per ciascun utente
function check_permissions(tipoutente,cambiovalori) {
	idTipoUtente=tipoutente;
	//COMBO BOX TUTOR
	if (idTipoUtente=="3"){
		enabled = "";}
	else {enabled = "disabled";}
	if (comboTutorValide==""){comboTutorValide = document.modifica_utente.elements['ELENCO_COMBO_TUTOR'].value; }
	setenabled(comboTutorValide,enabled);
	setValueSelect(comboTutorValide,0);
	///////////////
	if (cambiovalori) {
     	reset_all_checked(); // deseleziono tutto
		reset_all_policies();//disabilito tutti
		set_enabled_policies(idTipoUtente); //abilito in base utenza
		set_default_policies(idTipoUtente); // assegno valori di default
	}else{
     	reset_all_policies();//disabilito tutti
		set_enabled_policies(idTipoUtente);//abilito in base utenza
	}
}

//Deseziono tutti i privilegi
function reset_all_checked(){
	campi="CONSULTA_DEMO|GESTIONE_UTENTI|CONSULTA_CORSO|GESTIONE_TUTORING|SERVIZIO_LEARNING_CONTRACT|GESTIONE_SUPPORTO_TECNICO|SERVIZIO_TUTORING|GESTIONE_NEWS|GESTIONE_CENTRO_DOCUMENTAZIONE|GESTIONE_MODULI|GESTIONE_FORUM|GESTIONE_SESSIONI_CORSO|GESTIONE_BACHECA|GESTIONE_ATTIVITA|TUTORS_FORUM|GESTIONE_FORMULARI|SERVIZIO_CHAT";
	setchecked(campi,false);
}

//Disabilitazione Tutti
function reset_all_policies(){
	campi="CONSULTA_DEMO|GESTIONE_UTENTI|CONSULTA_CORSO|GESTIONE_TUTORING|SERVIZIO_LEARNING_CONTRACT|GESTIONE_SUPPORTO_TECNICO|SERVIZIO_TUTORING|GESTIONE_NEWS|GESTIONE_CENTRO_DOCUMENTAZIONE|GESTIONE_MODULI|GESTIONE_FORUM|GESTIONE_SESSIONI_CORSO|GESTIONE_BACHECA|GESTIONE_ATTIVITA|TUTORS_FORUM|GESTIONE_FORMULARI|SERVIZIO_CHAT";
	setenabled(campi,true);
}

function setchecked(campi,val){
	arcampi=campi.split("|");
	for (i=0; i<arcampi.length; i++){
		document.modifica_utente.elements[arcampi[i]].checked=val;
	}
}

function setValueSelect(campi,val){
	arcampi=campi.split("|");
	for (i=0; i<arcampi.length; i++){
		document.modifica_utente.elements[arcampi[i]].options.selectedIndex=val;
	}
}

function setvalue(campi,val){
	arcampi=campi.split("|");
	for (i=0; i<arcampi.length; i++){
		document.modifica_utente.elements[arcampi[i]].value=val;
	}
}

function setenabled(campi,val){
	arcampi=campi.split("|");
	for (i=0; i<arcampi.length; i++){
		document.modifica_utente.elements[arcampi[i]].disabled=val;
	}
}

function set_enabled_policies(idTipoUtente){
	campi="";
	if (idTipoUtente=="1"){          //VISITANTE
		campi= "CONSULTA_DEMO|CONSULTA_CORSO|SERVIZIO_LEARNING_CONTRACT|SERVIZIO_TUTORING";
	} else if (idTipoUtente=="2") {  //EXPERTO
		campi= "CONSULTA_CORSO|SERVIZIO_CHAT";
	}else if (idTipoUtente=="3"){    //PARTECIPANTE
		campi="CONSULTA_CORSO|SERVIZIO_LEARNING_CONTRACT|SERVIZIO_TUTORING|GESTIONE_SUPPORTO_TECNICO|GESTIONE_NEWS|SERVIZIO_CHAT";
	}else if (idTipoUtente=="4"){    //TUTOR
		campi="GESTIONE_UTENTI|CONSULTA_CORSO|GESTIONE_TUTORING|GESTIONE_SUPPORTO_TECNICO|GESTIONE_NEWS|GESTIONE_CENTRO_DOCUMENTAZIONE|GESTIONE_FORUM|GESTIONE_BACHECA|GESTIONE_ATTIVITA|TUTORS_FORUM|GESTIONE_FORMULARI|SERVIZIO_CHAT";
	}else if (idTipoUtente=="5"){    //AMMINISTRATORE
		campi="GESTIONE_UTENTI|CONSULTA_CORSO|GESTIONE_TUTORING|GESTIONE_SUPPORTO_TECNICO|GESTIONE_NEWS|GESTIONE_CENTRO_DOCUMENTAZIONE|GESTIONE_MODULI|GESTIONE_FORUM|GESTIONE_SESSIONI_CORSO|GESTIONE_BACHECA|GESTIONE_ATTIVITA|GESTIONE_FORMULARI|SERVIZIO_CHAT";
	}else if (idTipoUtente=="6"){   //ASSESSORE MAINTUTOR
		campi="GESTIONE_UTENTI|CONSULTA_CORSO|GESTIONE_SUPPORTO_TECNICO|GESTIONE_NEWS|GESTIONE_CENTRO_DOCUMENTAZIONE|GESTIONE_MODULI|GESTIONE_BACHECA|GESTIONE_ATTIVITA|SERVIZIO_CHAT";
	}
	if (campi!="") setenabled(campi,false); //abilitazione campi
} 

function set_default_policies(idTipoUtente){
	campi="";
	if (idTipoUtente=="1"){        //VISITANTE
		campi= "CONSULTA_DEMO";
	}else if (idTipoUtente=="2") { //EXPERTO
		campi= "CONSULTA_CORSO";
	}else if (idTipoUtente=="3"){  //PARTECIPANTE
		campi="CONSULTA_CORSO|SERVIZIO_LEARNING_CONTRACT|SERVIZIO_TUTORING";
	}else if (idTipoUtente=="4"){  //TUTOR
		campi="CONSULTA_CORSO|GESTIONE_TUTORING|GESTIONE_SUPPORTO_TECNICO|GESTIONE_FORUM|GESTIONE_BACHECA|GESTIONE_ATTIVITA";
	}else if (idTipoUtente=="5"){    //AMMINISTRATORE
		campi="GESTIONE_UTENTI|CONSULTA_CORSO|GESTIONE_TUTORING|GESTIONE_SUPPORTO_TECNICO|GESTIONE_NEWS|GESTIONE_CENTRO_DOCUMENTAZIONE|GESTIONE_MODULI|GESTIONE_FORUM|GESTIONE_SESSIONI_CORSO|GESTIONE_BACHECA|GESTIONE_ATTIVITA";
	}else if (idTipoUtente=="6"){   //ASSESSORE MAINTUTOR
		campi="CONSULTA_CORSO|GESTIONE_ATTIVITA";
	}
	if (campi!="") setchecked(campi,true); //campi checked 
} 
//*********************************************
//*********************************************
//*********************************************
//**************VALIDAZIONE FORM GESTIONE UTENZA*******************************
function MM_validateAutorizzazioni(){
	errors = "";
	if (MM_findObj('COMBO_SESSIONE')!=null){
		errors += MM_validateSessione();
		errors += MM_validateTipoUtenza();
		errors += MM_validateModuliUser();
		errors += MM_validateDate('DATA_INIZIO_ABILITAZIONE','Fecha inicio');
		errors += MM_validateDate('DATA_FINE_ABILITAZIONE','Fecha final');
	}else{
		errors += MM_validateTipoUtenza();
		errors += MM_validateModuliUser();
		errors += MM_validateDate('DATA_INIZIO_ABILITAZIONE','Fecha inicio');
		errors += MM_validateDate('DATA_FINE_ABILITAZIONE','Fecha final');
	}
	if (errors) alert('The following error(s) occurred:\n'+errors);
	document.MM_returnValue = (errors == '');
}

//Validazione Data Inizio e Data Fine
function MM_validateDate(nomeCampo,pEtichetta){
	errors = "";
	if (check_date(document.modifica_utente.elements[nomeCampo].value)) {errors = '- '+pEtichetta+' - no está en el formato correcto: (dd/mm/aaaa).\n';}
	return errors;
}

//Validazione Combo BOX SESSIONE
function MM_validateSessione(){
	errors = "";
	if (document.modifica_utente.elements['COMBO_SESSIONE'].options[document.modifica_utente.elements['COMBO_SESSIONE'].selectedIndex].value==""){ errors = "- La selección dell'edición es obligatoria.\n";}
	return errors;
}

//Validazione Combo BOX SESSIONE
function MM_validateTipoUtenza(){
	errors = "";
	if (document.modifica_utente.elements['COMBO_UTENTI'].options[document.modifica_utente.elements['COMBO_UTENTI'].selectedIndex].value==""){errors= "- La selección del tipo de usuario/a es obligatoria.\n";}
	return errors;
}

//Funzione per validazione combo box tutor
function MM_validateModuliUser(){
	errors = "";
	if (document.modifica_utente.elements['COMBO_UTENTI'].value == "3"){
		if (comboTutorValide==""){comboTutorValide = document.modifica_utente.elements['ELENCO_COMBO_TUTOR'].value; }
		arcampi=comboTutorValide.split("|");
		for (i=0; i<arcampi.length; i++){
			if ((document.modifica_utente.elements['ID_SESSIONE_MODULO_'+(i+1)].checked)&&(document.modifica_utente.elements[arcampi[i]].options.selectedIndex==0)){
				errors="- La asignación del/de la tutor/a al/a la usuario/a es obligatoria para cada Módulo.\n";
				break;
			}
		}
	}	
	return errors;
}

//Funzione per CAMBIO ELENCO UTENTI IN BACHECA E FORUM TECNICO
function change_Session(idSessione,urllink){
	document.location.href = urllink+idSessione;
}

//JAVASCRIPT FOR REPLACE
function searchAndReplace(holder, searchfor, replacement){
	var temparray;
	temparray = holder.split(searchfor);
	holder = temparray.join(replacement);
	return (holder);
}

//FUNZIONE DI CONVERSIONE TRATTINI
function checkConvertCaracterWord(form){
	for (i=0;i<=form.elements.length-1;i++){
		if ((form.elements[i].type=="text")||(form.elements[i].type=="textarea")){
			form.elements[i].value = searchAndReplace(form.elements[i].value, "—", " - ");
			form.elements[i].value = searchAndReplace(form.elements[i].value, "–", " - ");
			form.elements[i].value = searchAndReplace(form.elements[i].value, "”", "''");
		}
	}
}