var win_wf = null;
function OpenWebFiction(url)
{
	var width = window.screen.width
  var height = window.screen.height  

	if (win_wf != null && !win_wf.closed) { win_wf.close(); }
	win_wf = window.open(url,"popup_webfiction","top=0,left=0,status=yes,location=no,titlebar=yes,toolbar=no,menubar=no,width=" + (width-10) + ",height=" + (height-75));
  return;
}
//-- gestione visualizzazione approfondisci in homepage-------------------------------------------------------------
function ShowApprofondisci(){
	if (GetProp("tabApprofondisci",true,"display") == "none") {
		SetProp("tabApprofondisci",true,"display","");
		SetProp("app_button",false,"src","../../../../images/html/ok_button.jpg");
	} else {
		SetProp("tabApprofondisci",true,"display","none");
		SetProp("app_button",false,"src","../../../../images/html/cont_button.jpg");
	}
}
//-- gestione visualizzazione aree catalogo-------------------------------------------------------------
function ShowAree(pkt){
	// in attesa che decidano se i corsi verranno pubblicati anche all'interno delle tipologie (primo livello del catalogo)
	// e non solo nelle aree di contenuto, gestisco l'apertura della sezione scelta chiudendo le altre
	// in caso decidessero di attivare anche le tipologie decommentare il codice sottostante
	document.forms[0].elements["tipo"].value = "1";
	document.forms[0].elements["pkt"].value = pkt;
	document.forms[0].elements["pka"].value = "";
	document.forms[0].action = "/Default.aspx";
	document.forms[0].submit();
	return;
}
function isTabVis(pkt) {
	// verifico se il tab indicato è visibile o meno
	return (GetProp("tabAree"+pkt,true,"display") != "none");
}
function setClassName(pkt,sel,out){
	if (out && isTabVis(pkt)) return;
	SetProp("tdAreeCn"+pkt,false,"className","sezioniaree"+sel);
}
function lanciaListaCorsi(pkt,pka) {
	document.forms[0].elements["tipo"].value = "4"; //1
	document.forms[0].elements["pkt"].value = pkt;
	document.forms[0].elements["pka"].value = pka;
	document.forms[0].action = "/Default.aspx";
	document.forms[0].submit();
}
function apriDettaglioNotizia(area,desc_area) {
	document.forms[0].elements["tipo"].value = "9";
	document.forms[0].elements["area"].value = area;
	document.forms[0].elements["desc_area"].value = desc_area;
	document.forms[0].action = "/Default.aspx";
	document.forms[0].submit();
}
//-- gestione calendario -----------------------------------------
var linkGiorno = new Array();
var linkGiornoOK = false;
var et = null;
var win_cal = null;

function showDayLinkNew(serverName,data,obj) {
	//per motivi di spazio visualizzo la lista dei corsi in un popup
	if (win_cal != null && !win_cal.closed) { win_cal.close(); }
	win_cal = window.open("popup_calendar.asp?serverName="+serverName+"&data="+data,"popup_calendar","statusbar,menubar=no,height=300,width=300,top="+(screen.height/2));
}
function showDayLink(index,row,col,top,left) {
  //procedo solo se il caricamento dei link nell'apposito array è stata completata
  if (linkGiornoOK) {
  	//inserisco la lista di link del div di popup corsi e lo visualizzo
  	document.getElementById("oLink").innerHTML = linkGiorno[index];
  	document.getElementById("oLink").style.display = "";
  //alert(document.getElementById("oLink").offsetLeft+"-"+left+"-"+document.getElementById("oLink").clientWidth);
    var extra_left = ((document.getElementById("oLink").clientWidth>200)?(parseInt(document.getElementById("oLink").offsetLeft/10)):30);
  	if (navigator.appName.toLowerCase().indexOf("explorer")!=-1) {
  	    document.getElementById("oLink").style.top = (85 + (15*row)).toString()+"px";//(top+15).toString()+"px";
  	    document.getElementById("oLink").style.left = (35 + (25*col)).toString()+"px";//(left-extra_left).toString()+"px"; // ((document.getElementById("oLink").clientWidth>0)?document.getElementById("oLink").clientWidth/2+extra_left:extra_left)
  	} else {
  	    document.getElementById("oLink").style.top = (top+15).toString()+"px";
  	    document.getElementById("oLink").style.left = (left-extra_left).toString()+"px"; // ((document.getElementById("oLink").clientWidth>0)?document.getElementById("oLink").clientWidth/2+extra_left:extra_left)
    }  	
  }
}
function stopHideDayLink() {
	window.clearTimeout(et);
}
function hideDayLink() {
	et = window.setTimeout(hideDayLink2, 1000);
}
function hideDayLink2() {
	document.getElementById("oLink").style.display = "none";
}
function findPosX(obj)
{
	var curleft = 0;
	if(obj.offsetParent)
		while(1) 
		{
		  curleft += obj.offsetLeft;
		  if(!obj.offsetParent)
			break;
		  obj = obj.offsetParent;
		}
	else if(obj.x)
		curleft += obj.x;
	
	//alert(obj.offsetParent + "-" + curleft + "-" + obj.clientLeft);
	return curleft;
}
function findPosY(obj)
{
	var curtop = 0;
	if(obj.offsetParent)
		while(1)
		{
		  curtop += obj.offsetTop;
		  if(!obj.offsetParent)
			break;
		  obj = obj.offsetParent;
		}
	else if(obj.y)
		curtop += obj.y;
	
	//alert(obj.offsetParent + "-" + curtop + "-" + obj.style.top + "--" + document.getElementById("tabCalendario").style.top);
	return curtop;
}
function setParentParam(anno,mese) {
	document.forms[0].elements["anno"].value = anno;
	document.forms[0].elements["mese"].value = mese;
	document.forms[0].submit();
}
function setCalClassName(pk,up){
	var objName = "td"+pk;
	SetProp(objName,false,"className","giorno"+up);
}
//-- gestione scheda corso -----------------------------------------
var sk = null;
var win_popup = null;

function RefreshSchedaCorso() {
	sk = window.setTimeout(RefreshSchedaCorso2, 300000);
}
function RefreshSchedaCorso2() {
	document.forms[0].submit(); // aggiorno la scheda ogni 5 minuti
}
function backSchedaCorso(tipo,menu_back) {
	document.forms[0].elements["tipo"].value = tipo;
	document.forms[0].action = "/"+((menu_back=="")?"Home/tabid/36/Default.aspx":menu_back);
	document.forms[0].submit();
}
function lanciaSchedaCorso(crs,ed,clear_pka,pkt) {
	document.forms[0].elements["tipo"].value = "2";
	document.forms[0].elements["crs"].value = crs;
	document.forms[0].elements["ed"].value = "0"; // rimuovo l'edizione perché per labelVLC l'iscrizione è solo un invio di una mail a formazione
	if (clear_pka){ document.forms[0].elements["pka"].value = ""; }
	document.forms[0].elements["pkt"].value = ((pkt != "0") ? pkt : "");
	document.forms[0].action = "/Default.aspx";
	document.forms[0].submit();
}
function lanciaElencoCarrelli() {
    document.forms[0].elements["tipo"].value = "10";
    document.forms[0].elements["num_richiesta"].value = "";
    document.forms[0].action = "/Default.aspx";
    document.forms[0].submit();
}
function lanciaVediCarrello(num_richiesta) {
    document.forms[0].elements["num_richiesta"].value = num_richiesta;
    document.forms[0].action = "/carrello/tabid/127/Default.aspx";
    document.forms[0].submit();
}
function lanciaSegnalazione(crs) {
	document.forms[0].elements["tipo"].value = "5";
	document.forms[0].elements["crs"].value = crs;
	document.forms[0].action = "/Default.aspx";
	document.forms[0].submit();
}
function lanciaContattaResp(crs) {
	document.forms[0].elements["tipo"].value = "6";
	document.forms[0].elements["crs"].value = crs;
	document.forms[0].action = "/Default.aspx";
	document.forms[0].submit();
}
function lanciaIscriviti(pku,profilo,modalita) {
	// per labelVLC l'iscrizione da portale consiste solo nell'invio di una mail
  // a formazione x evidenziare l'interesse dell'utente al corso 
  // poi provvederà formazione via back-office ad iscriverlo ad una delle edizioni del corso
  document.forms[0].elements["tipo"].value = "7";
	document.forms[0].elements["pku"].value = pku;
	document.forms[0].action = "/Default.aspx";
	document.forms[0].submit();
}
function lanciaIscrizione() {
	// verifico che sia stato fornito l'indirizzo e-mail del responsabile
	if (document.forms[0].elements["email_resp"].value == "")	{
		alert("Indicare l'indirizzo e-mail del proprio responsabile.");
		document.forms[0].elements["email_resp"].focus();
		return false;
	}
	// verifico che l'indirizzo e-mail del responsabile sia corretto
	if (!checkMailAddress(document.forms[0].elements["email_resp"].value)){
		alert("Indicare un indirizzo e-mail valido.");
		document.forms[0].elements["email_resp"].focus();
		return false;
	}
	// verifico che l'indirizzo e-mail fornito termini con @labelformazione.it (uniche due estensioni al momento consentite)
	/*var email = document.forms[0].elements["email_resp"].value.trim().toLowerCase();
	if (email.indexOf("@labelformazione.it") == -1) {
		alert("Estensione dell'indirizzo e-mail non valida.\n\nSono ammessi solo indirizzi di @labelformazione.it.");
		document.forms[0].elements["email_resp"].focus();
		return false;
  }*/
	document.forms[0].elements["tipo"].value = "7";
	document.forms[0].action = "/Default.aspx";
	document.forms[0].submit();
}
function lanciaListaPartecipanti(pke) {
	//visualizza la lista dei partecipanti all'edizione in un popup
	if (win_popup != null && !win_popup.closed) { win_popup.close(); }
	win_popup = window.open("ListaPartecipanti.aspx?pk_edizione="+pke,"popup_scheda","statusbar,menubar=no,height=600,width=500,top=0");
}
function lanciaPrerequisiti(pkc) {
	//visualizza i requisiti per partecipare al corso in un popup
	if (win_popup != null && !win_popup.closed) { win_popup.close(); }
	win_popup = window.open("Prerequisiti.aspx?pk_corso="+pkc,"popup_scheda","statusbar,menubar=no,height=300,width=500,top=0");
}
function lanciaStampaScheda(pkc) {
	//visualizza la scheda corso in un popup per la stampa
	if (win_popup != null && !win_popup.closed) { win_popup.close(); }
	win_popup = window.open("StampaScheda.aspx?sk_print=1&crs="+pkc+"&ed=0","popup_scheda","statusbar,menubar=no,height=800,width=650,top=0,resizable=yes,scrollbars=yes");
}
function checkContattaResp(argID,testoID){

    var selArgomento = document.getElementById(argID);
    var testo = document.getElementById(testoID);
    
    if(selArgomento.value == 0)
    {
        alert("Selezionare l'argomento.");
        selArgomento.focus();
        return false;
    }
    
    if(testo.value.replace(/\s/g, '') == '')
    {
        alert("Indicare i termini della richiesta.");
        testo.focus();
        return false;
    }

}
function showNoEdizioni(top,left) {
	document.getElementById("oMsgEdizioni").style.display = "";
	document.getElementById("oMsgEdizioni").style.top = (top-35).toString()+"px";
	document.getElementById("oMsgEdizioni").style.left = (left-138).toString()+"px";
}
function hideNoEdizioni() {
  document.getElementById("oMsgEdizioni").style.display = "none";
}

function checkRegistrati(cognomeID,nomeID,telID,emailID,cfID,viaID,nrID,cittaID,prID,capID,check_mail){

    var cognome = document.getElementById(cognomeID);
    var nome = document.getElementById(nomeID);
    var tel = document.getElementById(telID);
    var email = document.getElementById(emailID);
    var cf = document.getElementById(cfID);
    var via = document.getElementById(viaID);
    var nr = document.getElementById(nrID);
    var citta = document.getElementById(cittaID);
    var pr = document.getElementById(prID);
    var cap = document.getElementById(capID);
        
    if(nome.value.replace(/\s/g, '') == '')
    {
        alert("Indicare il nome.");
        nome.focus();
        return false;
    }
    if(cognome.value.replace(/\s/g, '') == '')
    {
        alert("Indicare il cognome.");
        cognome.focus();
        return false;
    }
    if(via.value.replace(/\s/g, '') == '')
    {
        alert("Indicare la via.");
        via.focus();
        return false;
    }
    if(cap.value.replace(/\s/g, '') == '')
    {
        alert("Indicare il Cap.");
        cap.focus();
        return false;
    }
    if(citta.value.replace(/\s/g, '') == '')
    {
        alert("Indicare la citta'.");
        citta.focus();
        return false;
    }
    if(pr.value.replace(/\s/g, '') == '')
    {
        alert("Indicare la provincia.");
        pr.focus();
        return false;
    }
	if (!checkMailAddress(email.value) && check_mail){
		alert("Indicare un indirizzo e-mail valido.");
		email.focus();
		return false;
	}
    if(tel.value.replace(/\s/g, '') == '')
    {
        alert("Indicare il telefono.");
        tel.focus();
        return false;
    }
    if(cf.value.replace(/\s/g, '') == '')
    {
        alert("Indicare il Codice Fiscale o la Partita Iva.");
        cf.focus();
        return false;
    }

}
function checkDatiCarrello()
{
    //controllo che i dati di fatturazione siano stati indicati
    //controllo che ci sia almeno un corso
    return confirm('Confermi l\'acquisto dei corsi in carrello?')
    /*alert("Funzione ancora non disponibile");
    return false;*/
}
function EnableNrLicenze(nrLicenze, abilita)
{
    var licenze = document.getElementById(nrLicenze);
    licenze.disabled = !abilita;
    if (!abilita) { licenze.value = "1"; }
}
//-- funzioni globali ---------------------------------------------
function GetProp(objName,IsStyle,theProp) {
	var x = MM_findObj(objName);
	var s = "x."+(IsStyle?"style.":"")+theProp;
	return eval(s);
}
function SetProp(objName,IsStyle,theProp,theValue) {
	var x = MM_findObj(objName);
	var s = "if(x) { x."+(IsStyle?"style.":"")+theProp+"='"+theValue+"'; }";
	eval(s);
}
function MM_findObj(n, d) { //v4.0
  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 && document.getElementById) x=document.getElementById(n); return x;
}
function dummy() {
  return;
}
/******************************************************************************
* Functions To Check an EMail Address syntax validity
******************************************************************************/

function checkMailAddress(emailStr)
{
	emailStr = emailStr.trim();
    var emailPat=/^(.+)@(.+)$/;
    var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
    var validChars="\[^\\s" + specialChars + "\]";
    var quotedUser="(\"[^\"]*\")";
    var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
    var atom=validChars + '+';
    var word="(" + atom + "|" + quotedUser + ")";
    var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
    var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
    var matchArray=emailStr.match(emailPat);
    if (matchArray==null)
    {
        //alert("L'indirizzo email non sembra corretto. Controlla.")
        return false;
    }
    var user=matchArray[1];
    var domain=matchArray[2];
    
    if (user.match(userPat)==null)
    {
        //alert("Il nome utente non sembra corretto.")
        return false;
    }
    
    var IPArray=domain.match(ipDomainPat);
    if (IPArray!=null)
    {
        for (var i=1;i<=4;i++)
        {
            if (IPArray[i]>255)
            {
                //alert("L'IP di destinazione non è corretto.")
                return false;
            }
        }
        return true;
    }
    
    var domainArray=domain.match(domainPat);
    if (domainArray==null)
    {
        //alert("Il nome del dominio non sembra valido.")
        return false;
    }
    
    var atomPat=new RegExp(atom,"g");
    var domArr=domain.match(atomPat);
    var len=domArr.length;
    if (domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>3)
    {
        /*alert("L'indirizzo email deve terminare con un 
        dominio di tre lettere (.com, .net, etc...) o con due lettere 
        per i domini nazionali (.it, .fr, etc..).")*/
        return false;
    }
    
    if (len<2)
    {
        //var errStr="Questo indirizzo non presenta il nome dell'host!"
        //alert(errStr)
        return false;
    }

	var Filtro = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$/;
	return Filtro.test(emailStr);

}

// dovrebbe controllare solo che ci siano il carattere @ e . e poi che nel caso l'estensione del dominio sia di 3 char questa sia esattamente tra quelle ammesse altrimenti se è di 2 tutto va bene...
function checkMailAddress2(mail) 
{
  return mail.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$)\b/gi);
}

String.prototype.trim = function() {
  var x=this;
  x=x.replace(/^\s*(.*)/, "$1");
  x=x.replace(/(.*?)\s*$/, "$1");
  return x;
}

function LeggiTutto(flg_apri) {

  for (var key in document.body.getElementsByTagName("DIV"))
  {
      if (key.substring(0,8) == 'risposta') {
        document.getElementById(key).style.display = ((flg_apri) ? '' : 'none');
      }
  }
  document.getElementById("btnOpenAll1").value = ((flg_apri) ? 'Solo domande' : 'Leggi tutto');
  document.getElementById("btnOpenAll1").onclick = function() { 
    if (flg_apri) { 
      LeggiTutto(false); 
    } else {
      LeggiTutto(true);
    }
  }
  document.getElementById("btnOpenAll2").value = ((flg_apri) ? 'Solo domande' : 'Leggi tutto');
  document.getElementById("btnOpenAll2").onclick = function() { 
    if (flg_apri) { 
      LeggiTutto(false); 
    } else {
      LeggiTutto(true);
    }
  }
}

function Leggi(item, flg_apri) {

  var key = 'risposta' + item;
  document.getElementById(key).style.display = ((flg_apri) ? '' : 'none');

}

/****** funzioni per calendario personalizzato *******/

var oldLink = null;
function setActiveStyleSheet(link, title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  }
  if (oldLink) oldLink.style.fontWeight = 'normal';
  oldLink = link;
  link.style.fontWeight = 'bold';
  return false;
}

// This function gets called when the end-user clicks on some date.
function selected(cal, date) {
  cal.sel.value = date; // just update the date in the input field.
  if (cal.dateClicked && (cal.sel.id == "sel1" || cal.sel.id == "sel3"))
    cal.callCloseHandler();
}

function closeHandler(cal) {
  cal.hide();                        // hide the calendar
//  cal.destroy();
  _dynarch_popupCalendar = null;
}

function showCalendar(id, format, showsTime, showsOtherMonths) {
  var el = document.getElementById(id);
  if (_dynarch_popupCalendar != null) {
    // we already have some calendar created
    _dynarch_popupCalendar.hide();                 // so we hide it first.
  } else {
    // first-time call, create the calendar.
    var cal = new Calendar(1, null, selected, closeHandler);
    // uncomment the following line to hide the week numbers
    // cal.weekNumbers = false;
    if (typeof showsTime == "string") {
      cal.showsTime = true;
      cal.time24 = (showsTime == "24");
    }
    if (showsOtherMonths) {
      cal.showsOtherMonths = true;
    }
    _dynarch_popupCalendar = cal;                  // remember it in the global var
    cal.setRange(1900, 2070);        // min/max year allowed.
    cal.create();
  }
  _dynarch_popupCalendar.setDateFormat(format);    // set the specified date format
  _dynarch_popupCalendar.parseDate(el.value);      // try to parse the text in field
  _dynarch_popupCalendar.sel = el;                 // inform it what input field we use

  _dynarch_popupCalendar.showAtElement(el.nextSibling, "Br");        // show the calendar

  return false;
}

var MINUTE = 60 * 1000;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;
var WEEK = 7 * DAY;

function isDisabled(date) {
  var today = new Date();
  return (Math.abs(date.getTime() - today.getTime()) / DAY) > 10;
}

function flatSelected(cal, date) {
  var el = document.getElementById("preview");
  el.innerHTML = date;
}

function showFlatCalendar() {
  var parent = document.getElementById("display");

  var cal = new Calendar(0, null, flatSelected);

  cal.weekNumbers = false;

  cal.setDisabledHandler(isDisabled);
  cal.setDateFormat("%A, %B %e");

  cal.create(parent);

  cal.show();
}
/*********************************************************/

