// JavaScript Document

// apertura colorbox
function startLytebox(my_href, my_title, my_width, my_height) {
	$.fn.colorbox({iframe:true, href:my_href, title:my_title, width:my_width, height:my_height});
}

/// gestione select a cascata

function addOption(selectbox, value, text) {
	var optn = document.createElement("option");
	optn.text = text;
	optn.value = value;
	selectbox.options.add(optn);
}


function addAllOption(array_sottocategorie, id_padre, nome_padre, id_figlio_selezionato, nome_figlio) {
	if (array_sottocategorie) {
		for (var i=0; i < array_sottocategorie.length; ++i){
			if (array_sottocategorie[i][2] == id_padre) {
				addOption(document.getElementById(nome_figlio), array_sottocategorie[i][0], array_sottocategorie[i][1]);
				if (array_sottocategorie[i][0] == id_figlio_selezionato) {
					document.getElementById(nome_figlio).selectedIndex = i+1;		
				}
			}
		}
	}
}



//function removeOption_list() {
//	removeAllOptions(document.tabella_gloss.glossa);
//}



function removeAllOptions(nome_select) {
	var i;
	for(i=document.getElementById(nome_select).options.length-1; i>0 ;i--) {
		document.getElementById(nome_select).remove(i);
	}
}

//function removeSelectedOptions(selectbox) {
//	var i;
//	for(i=selectbox.options.length-1;i>=0;i--) {
//		if (selectbox.options[i].selected)
//		selectbox.remove(i);
//	}
//}
/// gestione select a cascata




//Selezione Multiple Selezionata
function setMultipleSelection(nameForm,nameCampo,nameCampoElenco) {
	pStrElencoId = '';
	document.forms[nameForm].elements[nameCampoElenco].value = '';
	for (i = 0; i < document.forms[nameForm].elements[nameCampo].options.length; i++){
		if (document.forms[nameForm].elements[nameCampo].options[i].selected == true) {pStrElencoId += document.forms[nameForm].elements[nameCampo].options[i].value+'|';}
	}
	if (pStrElencoId!='') {pStrElencoId = pStrElencoId.substring(0,pStrElencoId.length-1);}
	document.forms[nameForm].elements[nameCampoElenco].value = pStrElencoId;
//	alert(document.forms[nameForm].elements[nameCampoElenco].value);
}




function setMultipleCheck(nameForm,nameCampo,nameCampoElenco,numeroCheck) {
	pStrElencoId = '';
	document.forms[nameForm].elements[nameCampoElenco].value = '';
	for (i = 1; i <= numeroCheck; i++){
		if (document.forms[nameForm].elements[nameCampo+'_'+i].checked == true) {pStrElencoId += document.forms[nameForm].elements[nameCampo+'_'+i].value+'|';}
	}
	if (pStrElencoId!='') {pStrElencoId = pStrElencoId.substring(0,pStrElencoId.length-1);}
	document.forms[nameForm].elements[nameCampoElenco].value = pStrElencoId;
//	alert(document.forms[nameForm].elements[nameCampoElenco].value);
}


//Controllo Valore Selezionato da Select con scelta multipla
function checkMultipleSelection(nameForm,nameCampo) {
	pValue = true;
	for (i = 0; i < document.forms[nameForm].elements[nameCampo].options.length; i++){
		if (document.forms[nameForm].elements[nameCampo].options[i].selected == true) {pValue = false;}
	}
	return pValue;
}


//validazione nome file
function validateFileName( id, name, strValue, required ) {
	var controllo = false;

	if (((required == 'false') || (required == '')) && (strValue == '')) {
		return true; 
	}
	
	if (strValue != '') {
		controllo_nome = check_nome_file(strValue.toLowerCase(), 'abcdefghijklmnopqrstuvxywz0123456789_-.');
		controllo_estensione = check_estensione_file(strValue.toLowerCase(), '.txt,.rtf,.doc,.pdf');
		if ((controllo_nome == true) && (controllo_estensione == true)) {
			controllo = true; 
		}
	}

	return controllo;
}

//controllo nome file
function check_nome_file(valore_campo, elenco_caratteri_validi) {

	var controllo = false;
	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 = "";
	if (num_elementi_file == 2) {
		nome_file_no_ext = nome_file[0];
		for (var i=0;i<nome_file_no_ext.length;i++) {
			if (elenco_caratteri_validi.indexOf(nome_file_no_ext.substr(i,1)) < 0) {
				controllo = false;
				break;
			}
		}
	}
	return controllo;
}

//controllo estensioni file
function check_estensione_file(valore_campo, elenco_estensioni_valide) {

	var controllo = false;

	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 = "";
	if (num_elementi_file == 2) {
		estensione_file = "." + nome_file[1];
		if (elenco_estensioni_valide.indexOf(estensione_file) < 0) {
			controllo = false;
		} else {
			controllo = true;
		}
	}

	return controllo;
}




// funzione trim //
function LTrim(str_temp) {
   var whitespace = new String(" \t\n\r");
   if (whitespace.indexOf(str_temp.charAt(0)) != -1) {
      var j=0, i = str_temp.length;
      while (j < i && whitespace.indexOf(str_temp.charAt(j)) != -1)
         j++;
      str_temp = str_temp.substring(j, i);
   }
   return str_temp;
}

function RTrim(str_temp) {
   var whitespace = new String(" \t\n\r");
   if (whitespace.indexOf(str_temp.charAt(str_temp.length-1)) != -1) {
      var i = str_temp.length - 1;
      while (i >= 0 && whitespace.indexOf(str_temp.charAt(i)) != -1)
         i--;
      str_temp = str_temp.substring(0, i+1);
   }
   return str_temp;
}

function trim(str_temp) {
   return RTrim(LTrim(str_temp));
}


// validazione formato pwd
function validatePassword( id, name, strValue, required ) {
	var controllo = false;

	if (strValue != '') {
		controllo_numero = check_stringa(strValue.toLowerCase(), '0123456789');
		controllo_stringa = check_stringa(strValue.toLowerCase(), 'abcdefghilmnopqrstuvz');
		if ((controllo_numero == true) && (controllo_stringa == true)) {
			controllo = true; 
		}
	}

	return controllo;
}


function check_stringa(valore_campo, elenco_caratteri_validi) {
	var controllo = false;
	for (var i=0;i<valore_campo.length;i++) {
		if (elenco_caratteri_validi.indexOf(valore_campo.substr(i,1)) < 0) {
			controllo = false;
			break;
		} else {
			controllo = true;
		}
	}
	return controllo;
}


function check_number( id, name, strValue, required ) {
	if (((required == 'false') || (required == '')) && (strValue == '')) {
		return true; 
	}
	return check_stringa(strValue, '0123456789');
}	

//// id, name, strValue, required
//
//function getCheckedValue(id, name, value) {
//
//alert('id ' + id);
//alert('name ' + name);
//alert('strValue ' + strValue);
//alert('required ' + required);
//
////function getCheckedValue(radioObj) {
////	if(!radioObj)
////		return "";
////	var radioLength = radioObj.length;
////	if(radioLength == undefined)
////		if(radioObj.checked)
////			return radioObj.value;
////		else
////			return "";
////	for(var i = 0; i < radioLength; i++) {
////		if(radioObj[i].checked) {
////			return radioObj[i].value;
////		}
////	}
////	return "";
//}




function validateITADate( id, name, strValue, required ) {
/************************************************
DESCRIPTION: Validates that a string contains only
    valid dates with 2 digit month, 2 digit day,
    4 digit year. Date separator can be '/'.
    Uses combination of regular expressions and
    string parsing to validate date.
    Ex. dd/mm/yyyy

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

REMARKS:
   Avoids some of the limitations of the Date.parse()
   method such as the date separator character.
*************************************************/

	if (((required == 'false') || (required == '')) && (strValue == '')) {
		return true; 
	}

  var objRegExp = /^\d{1,2}(\/)\d{1,2}\1\d{4}$/


  //check to see if in correct format
  if(!objRegExp.test(strValue))
    return false; //doesn't match pattern, bad date
  else{
    var arrayDate = strValue.split(RegExp.$1); //split date into month, day, year
	var intDay = parseInt(arrayDate[0],10);
    var intMonth = parseInt(arrayDate[1],10);
	var intYear = parseInt(arrayDate[2],10);

	//check for valid month
	if(intMonth > 12 || intMonth < 1) {
		return false;
	}

    //create a lookup for months not equal to Feb.
    var arrayLookup = { '1' : 31,'3' : 31, '4' : 30,'5' : 31,'6' : 30,'7' : 31,
                        '8' : 31,'9' : 30,'10' : 31,'11' : 30,'12' : 31}

    //check if month value and day value agree
    if(arrayLookup[intMonth] != null) {
      if(intDay <= arrayLookup[intMonth] && intDay != 0)
        return true; //found in lookup table, good date
    }

    //check for February
	var booLeapYear = (intYear % 4 == 0 && (intYear % 100 != 0 || intYear % 400 == 0));
    if( ((booLeapYear && intDay <= 29) || (!booLeapYear && intDay <=28)) && intDay !=0)
      return true; //Feb. had valid number of days
  }
  return false; //any other values, bad date
}

// id, name, strValue, required




function check_url(id, name, strValue, required) {
	var controllo = true;
	if (((required == 'false') || (required == '')) && (strValue == '')) {
		return controllo; 
	}

	var errore = "falso";
	var re
	re = new RegExp("(http|ftp|https)://[-A-Za-z0-9._/]+")
	if (re.test(strValue) == false)	controllo = false;
	return controllo;
}


function showElementById (id) {
	if (document.getElementById(id)) {
		document.getElementById(id).style.display = '';
	}
}

function hideElementById (id) {
	if (document.getElementById(id)) {
		document.getElementById(id).style.display = 'none';
	}
}

function showHideElementById (id) {
	if (document.getElementById(id)) {
		if (document.getElementById(id).style.display == 'none') {
			document.getElementById(id).style.display = 'block';
		} else {
			document.getElementById(id).style.display = 'none';
		}
	}
}






/*
function changeStyleMenu (id, style, style_selected) {
	if (document.getElementById(id).className == style) {
		document.getElementById(id).className = style_selected;
	} else {
		document.getElementById(id).className = style;
	}
}
*/

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';
	}

/*
alert('url ' + url);
alert('windowW ' + windowW);
alert('windowH ' + windowH);
alert('windowName ' + windowName);
alert('visualizza_scroll ' + visualizza_scroll);
*/

//	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();
}

///////////////////////////////////////////////////////////////////////////////////////////////////



function scrivi_data_ora(lang) {
	var today = new Date();
	var year = today.getYear();
	var date = today.getDate();
	var min = today.getMinutes();
	var lingua = lang;
	var separatore = "";
	if (navigator.appName == "Netscape"){
		year = (1900+year);
	}
	if (min < 10) {
		min = "0" + min;
	}  
	if (lingua == "ita") {
		months = new Array("Gennaio","Febbraio","Marzo","Aprile","Maggio","Giugno","Luglio","Agosto","Settembre","Ottobre","Novembre","Dicembre");
		day = new Array("Domenica","Luned&igrave;","Marted&igrave;","Mercoled&igrave;","Gioved&igrave;","Venerd&igrave;","Sabato");
		separatore = " - ";
	} else if (lingua == "eng") {
		months = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
		day = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
		separatore = " - ";
	}
	document.writeln(day[today.getDay()]+ " " + date + " " + months[today.getMonth()] + " " + year + " " + separatore + today.getHours()+":"+min);
}































//Funzione di Set Check Allegati
function setStatusCheck(num,object){
	pValue = object.checked;
	arLang = new Array('EN','FR','IT','ES');
	for (i=0;i<arLang.length;i++){
		document.forms['mosForm'].elements['ALLEGATO_'+(num)+arLang[i]].checked = pValue;
	}
}

//Funzione di Autorizzazioni Utente
function setAutorizzazioniUtente(idTipoUtente,nameForm,pAction){
	//alert(idTipoUtente);
	if ((idTipoUtente==1)||(idTipoUtente==2)){
		//SuperAmministrator
		document.forms[nameForm].elements['ID_GROUP_SINGLE'].disabled = true;
		for (i = 0; i < document.forms[nameForm].elements['ID_GROUP_MULTIPLE'].options.length; i++){
			document.forms[nameForm].elements['ID_GROUP_MULTIPLE'].options[i].selected = true;
		}
		document.forms[nameForm].elements['ID_GROUP_MULTIPLE'].disabled = true;
	}else if (idTipoUtente==3){
		//Administrator Group
		document.forms[nameForm].elements['ID_GROUP_SINGLE'].disabled = true;
		for (i = 0; i < document.forms[nameForm].elements['ID_GROUP_MULTIPLE'].options.length; i++){
			if (pAction=='INSERT'){document.forms[nameForm].elements['ID_GROUP_MULTIPLE'].options[i].selected = false;}
		}
		document.forms[nameForm].elements['ID_GROUP_MULTIPLE'].disabled = false;
	}else if (idTipoUtente==4){
		//Registered
		document.forms[nameForm].elements['ID_GROUP_SINGLE'].disabled = false;
		for (i = 0; i < document.forms[nameForm].elements['ID_GROUP_MULTIPLE'].options.length; i++){
			document.forms[nameForm].elements['ID_GROUP_MULTIPLE'].options[i].selected = false;
		}
		document.forms[nameForm].elements['ID_GROUP_MULTIPLE'].disabled = true;
	}
	
}

//MESSAGGIO DI CONFERMA 
function setMessageConfirm(strMessage){
	//alert(strMessage);
	if (confirm(strMessage)){
		return true;
	}else{
		return false;
	}
}

//Selezione Allegati Controllo
/*function setMultipleSelection(nameForm,nameCampo,nameCampoElenco) {
	pStrElencoId = '';
	document.forms[nameForm].elements[nameCampoElenco].value = '';
	for (i = 0; i < document.forms[nameForm].elements[nameCampo].options.length; i++){
		if (document.forms[nameForm].elements[nameCampo].options[i].selected == true) {pStrElencoId += document.forms[nameForm].elements[nameCampo].options[i].value+'|';}
	}
	if (pStrElencoId!='') {pStrElencoId = pStrElencoId.substring(0,pStrElencoId.length-1);}
	document.forms[nameForm].elements[nameCampoElenco].value = pStrElencoId;
	//alert(document.forms[nameForm].elements[nameCampoElenco].value);
}*/

////////////////////////////////////////////////////////////////////////////////////////////////// LINGUA
function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

function MM_setCookie(selObj){
	//alert(selObj.options[selObj.selectedIndex].value);
	pLang = selObj.options[selObj.selectedIndex].value;
	SetCookie ('lingua', pLang);
	window.location.href=window.location.href;
}

function SetCookie (name, value){
   var argv = SetCookie.arguments;
   var argc = SetCookie.arguments.length;
   var expires = (2 < argc) ? argv[2] : null;
   var path = (3 < argc) ? argv[3] : null;
   var domain = (4 < argc) ? argv[4] : null;
   var secure = (5 < argc) ? argv[5] : false;
   document.cookie = name + "=" + escape (value) +
     ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
     ((path == null) ? "" : ("; path=" + path)) +
     ((domain == null) ? "" : ("; domain=" + domain)) +
     ((secure == true) ? "; secure" : "");
}
////////////////////////////////////////////////////////////////////////////////////////////////// HEADER
//Correzione Png Trasparanti
function correctPNG()
{
   for(var i=0; i<document.images.length; i++)
   {
      var img = document.images[i]
      var imgName = img.src.toUpperCase()

      if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
      {
         var imgID = (img.id) ? "id='" + img.id + "' " : ""
         var imgClass = (img.className) ? "class='" + img.className + "' " : ""
         var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
         var imgStyle = "display:inline-block;" + img.style.cssText

         if (img.align == "left") imgStyle = "float:left;" + imgStyle
         if (img.align == "right") imgStyle = "float:right;" + imgStyle
         if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle

         var strNewHTML = "<span " + imgID + imgClass + imgTitle
             + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;"
             + imgStyle + ";"      + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
             + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"

         img.outerHTML = strNewHTML
         i = i-1
      }
   }
}


////////////////////////////////////////////////////////////////////////////////////////////////// CONTROLLI CAMPI FORM
function MM_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;
}


/* FRANCESCO: Function to clear a form of all it's values */
function clearForm(frmObj) {
	for (var i = 0; i < frmObj.length; i++) {
        var element = frmObj.elements[i];
		if(element.type.indexOf("text") == 0 || 
				element.type.indexOf("password") == 0) {
					element.value="";
		} else if (element.type.indexOf("radio") == 0) {
			element.checked=false;
		} else if (element.type.indexOf("checkbox") == 0) {
			element.checked = false;
		} else if (element.type.indexOf("select") == 0) {
			for(var j = 0; j < element.length ; j++) {
				element.options[j].selected=false;
			}
            element.options[0].selected=true;
		}
	} 
}
