/*
'===========================================================
'  NAME:    Redat Javascript
'  VERSION: 0.1
'  DATE:    01/10/2008
'  AUTHOR:  Luca Maroglio
'  NOTE:    Redat Ecommerce Site
'===========================================================
*/

/* ------------------------------------------------------------------------
 * Funzioni originali sito Redat
 * ------------------------------------------------------------------------ */
function former(){
   with(document.form1){
      if (campo1.value=='' || campo2.value=='' || campo3.value=='' || campo4.value=='' || campo5.value=='' ||
          campo7.value=='' || campo9.value=='' || campo10.value=='' ||email.value=='') {

         alert('Le caselle rosse sono obbligatorie.');
         return false;
      } else {
         submit();
         return true;
      }
   }
}

function CheckCV(){
   with(document.GetCV){
      if (fNome.value=='' || fCognome.value=='' || fEmail.value=='' || fDoc.value=='') {
         alert('Le caselle rosse sono obbligatorie.');
      } else {
         submit()
      }
   }
}

function CheckLength(campo,charMax) {

	if (campo.value.length>charMax) {	
		campo.value=campo.value.substring(0, charMax);
	}
}

function MM_swapImgRestore() { //v3.0
   var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

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_swapImage() { //v3.0
   var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){
      document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];
   }
}

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;
}





/* ------------------------------------------------------------------------
 * Variabili e costanti comuni a tutte le funzioni della libreria
 * ------------------------------------------------------------------------ */
var ProgressBar = false;
var ProgressBarView = false;
var ProgressValue = 0;
var oInterval = null;

/* ------------------------------------------------------------------------
 * Istanzia un oggetto XMLHttpRequest
 * ------------------------------------------------------------------------ */
function getXMLHttpRequestInstance() {
   // La funzione restituisce un'istanza di XMLHttpRequest
   // oppure il valore false in caso di errori
   var xmlhttp;
   // Provo il metodo Microsoft usando la versione pił recente
   try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
   } catch (e) {
      try {
         xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
         xmlhttp = false;
      }
   }
   // Ora provo con metodi compatibili con Mozilla/FireFox
   // e altri browser compatibile
   if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
      try {
         xmlhttp = new XMLHttpRequest();
      } catch (e) {
         xmlhttp = false;
      }
   }
   // Restituisce l'oggetto
   return xmlhttp;
}

/* ------------------------------------------------------------------------
 * Sostituisce il contenuto HTML di un nodo della pagina
 * ------------------------------------------------------------------------ */
function updateContent(nodeId, html) {
   // nodeId  ID del nodo
   // html    codice HTML da sostituire a quello del nodo
   var node = document.getElementById(nodeId);
   if(null == node) {
      alert("[ERRORE] L'elemento " + nodeId + " non esiste");
      return;
   }
   node.innerHTML = html;
   node.style.visibility = "visible";
}

/* ------------------------------------------------------------------------
 * Aggiunge contenuto HTML ad un nodo della pagina
 * ------------------------------------------------------------------------ */
function addContent(nodeId, html) {
   // nodeId  ID del nodo
   // html    codice HTML da sostituire a quello del nodo
   var node = document.getElementById(nodeId);
   if(null == node) {
      alert("[ERRORE] L'elemento " + nodeId + " non esiste");
      return;
   }
   node.innerHTML = node.innerHTML+html;
   node.style.visibility = "visible";
}

/* ------------------------------------------------------------------------
 * Visualizza il contenuto HTML di un nodo della pagina
 * ------------------------------------------------------------------------ */
function viewContent(nodeId) {
   // nodeId  ID del nodo
   var node = document.getElementById(nodeId);
   if(null == node) {
      alert("[ERRORE] L'elemento " + nodeId + " non esiste");
      return;
   }
   node.style.visibility = "visible";
}

/* ------------------------------------------------------------------------
 * Nasconde il contenuto HTML di un nodo della pagina
 * ------------------------------------------------------------------------ */
function hideContent(nodeId) {
   // nodeId  ID del nodo
   var node = document.getElementById(nodeId);
   if(null == node) {
      alert("[ERRORE] L'elemento " + nodeId + " non esiste");
      return;
   }
   node.style.visibility = "hidden";
}

/* ------------------------------------------------------------------------
 * Richiede al web server il contenuto di una pagina (url) e visualizza
 * il contenuto nell'elemento indicato
 * ------------------------------------------------------------------------ */
function getResponse(nodeId, url, addHtml) {
   // nodeId   ID dell'oggetto in cui memorizzare il risultato della richiesta
   // url      URL della pagina che eroga il servizio
   //          (deve essere sullo stesso server per motivi di sicurezza)
   var xmlhttp = getXMLHttpRequestInstance();
   if(!xmlhttp) {
      alert("Il browser non supporta l'oggetto XMLHttpRequest");
      return false;
   }
   xmlhttp.open("GET", url,true);
   xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4) {
         if (xmlhttp.status==200) {
            if (addHtml) {
               addContent(nodeId, xmlhttp.responseText);
            } else {
               updateContent(nodeId, xmlhttp.responseText);
            }
            ProgressBar=false;
         } else if (xmlhttp.status==404) {
            alert("[ERRORE] l'URL "+url+"non esiste!");
         } else {
            alert("[ERRORE] errore non gestito (" + xmlhttp.status + ")");
            //addContent(nodeId, xmlhttp.responseText)
         }
      }
   }
   xmlhttp.send(null);
}

/* ------------------------------------------------------------------------
 * Richiede al web server il contenuto di una pagina (url) e analizza il ri-
 * sultato per determinare il nome dell'oggetto ed il contenuto da visualizzare
 * ------------------------------------------------------------------------ */
function splitResponse(url) {
   // url      URL della pagina che eroga il servizio
   //          (deve essere sullo stesso server per motivi di sicurezza)
   var xmlhttp = getXMLHttpRequestInstance();
   if(!xmlhttp) {
      alert("Il browser non supporta l'oggetto XMLHttpRequest");
      return false;
   }
   xmlhttp.open("GET", url,true);
   xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4) {
         if (xmlhttp.status==200) {
            var content = xmlhttp.responseText;
            var update = new Array();
            if(content.indexOf('|' != -1)) {
               update = content.split('|');
               updateContent(update[0], update[1]);
               ProgressBar=false;
            }
         } else if (xmlhttp.status==404) {
            alert("[ERRORE] l'URL "+url+"non esiste!");
         } else {
            alert("[ERRORE] errore non gestito (" + xmlhttp.status + ")");
         }
      }
   }
   xmlhttp.send(null);
}

/* ------------------------------------------------------------------------
 * Prepara la url da invocare in base al contenuto dei campi del form indicato
 * e poi invoca la funzione getResponse
 * ------------------------------------------------------------------------ */
function formSubmit(nodeId, formName, url) {
   hideContent(nodeId);
   url+='?';
   var fields=document.forms[formName].elements;
   for (var i=0;i<fields.length;i++){
      if (fields[i].type=='checkbox' && fields[i].checked) {
         url+=fields[i].name+'=on&';
      } else if (fields[i].type=='radio' && fields[i].checked) {
         url+=fields[i].name+'='+fields[i].value+'&';
      } else if (fields[i].type!='radio' && fields[i].type!='checkbox') {
         url+=fields[i].name+'='+fields[i].value+'&';
      }
   };
   getResponse(nodeId, url, false)
}

/* ------------------------------------------------------------------------
 * ProgressBar: inizializzazione
 * ------------------------------------------------------------------------ */
function ProgBarInit() {
   ProgressValue=0;
   ProgressBar = true;
   oInterval = setInterval("ProgBarStep()", 30);
}

/* ------------------------------------------------------------------------
 * ProgressBar: avvio
 * ------------------------------------------------------------------------ */
function ProgBarStart() {
   if (!ProgressBar) {
      hideContent('ProgBar');
      hideContent('ProgBarBox');
      clearInterval(oInterval);
   } else {
      oInterval = setInterval("ProgBarStep()", 30);
   }
}

/* ------------------------------------------------------------------------
 * ProgressBar: avanzamento
 * ------------------------------------------------------------------------ */
function ProgBarStep() {
   if (!ProgressBar) {
      ProgBarStart();
   } else {
      ProgressValue+=1;
      if (ProgressValue*10>document.width) {
         ProgressValue=0;
      }

      var nBox = document.getElementById('ProgBarBox');
      var nBar = document.getElementById('ProgBar');
      if(null == nBox) {
         alert("[ERRORE] problemi durante la visualizzazione della ProgressBar");
         return;
      }
      if(null == nBar) {
         alert("[ERRORE] problemi durante la visualizzazione della ProgressBar");
         return;
      }
      nBar.innerHTML = '&nbsp;';
      nBar.style.width = ProgressValue*10;
      nBox.style.visibility = "visible";
      nBar.style.visibility = "visible";
   }
}

/* ------------------------------------------------------------------------
 * 
 * ------------------------------------------------------------------------ */
function OpenBox(str, sTitolo, wWidth, wHeight) {
   window.open(str,sTitolo,'scrollbars=yes,resizable=yes,left=200,top=50,width=' + wWidth + ',height=' + wHeight + ',status=no,location=no,toolbar=no');
}

/* ------------------------------------------------------------------------
 * Visualizzazione calendario per selezione data
 * ------------------------------------------------------------------------ */
function show_calendar(str_target, str_datetime) {
	var arr_months = ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno",
		               "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"];
	var week_days = ["Do", "Lu", "Ma", "Me", "Gi", "Ve", "Sa"];
	var n_weekstart = 1; // day week starts from (normally 0 or 1)

	var dt_datetime = (str_datetime == null || str_datetime =="" ?  new Date() : str2dt(str_datetime));
	var dt_prev_month = new Date(dt_datetime);
	dt_prev_month.setMonth(dt_datetime.getMonth()-1);
	var dt_next_month = new Date(dt_datetime);
	dt_next_month.setMonth(dt_datetime.getMonth()+1);
	var dt_firstday = new Date(dt_datetime);
	dt_firstday.setDate(1);
	dt_firstday.setDate(1-(7+dt_firstday.getDay()-n_weekstart)%7);
	var dt_lastday = new Date(dt_next_month);
	dt_lastday.setDate(0);

	// html generation (feel free to tune it for your particular application)
	// print calendar header
	var str_buffer = new String (
		"<html>\n"+
		"<head>\n"+
		"	<title>Calendar</title>\n"+
		"</head>\n"+
		"<body bgcolor=\"White\">\n"+
		"<table class=\"clsOTable\" cellspacing=\"0\" border=\"0\" width=\"100%\">\n"+
		"<tr><td bgcolor=\"#4682B4\">\n"+
		"<table cellspacing=\"1\" cellpadding=\"3\" border=\"0\" width=\"100%\">\n"+
		"<tr>\n	<td bgcolor=\"#4682B4\"><a href=\"javascript:window.opener.show_calendar('"+
		str_target+"', '"+ dt2dtstr(dt_prev_month)+"');\">"+
		"<img src=\"Immagini/prev.gif\" width=\"16\" height=\"16\" border=\"0\""+
		" alt=\"previous month\"></a></td>\n"+
		"	<td bgcolor=\"#4682B4\" colspan=\"5\">"+
		"<font color=\"white\" face=\"tahoma, verdana\" si ze=\"2\" style=\"font-size:10pt;\" >"
		+arr_months[dt_datetime.getMonth()]+" "+dt_datetime.getFullYear()+"</font></td>\n"+
		"	<td bgcolor=\"#4682B4\" align=\"right\"><a href=\"javascript:window.opener.show_calendar('"
		+str_target+"', '"+dt2dtstr(dt_next_month)+"');\">"+
		"<img src=\"Immagini/next.gif\" width=\"16\" height=\"16\" border=\"0\""+
		" alt=\"next month\"></a></td>\n</tr>\n"
	);

	var dt_current_day = new Date(dt_firstday);
	// print weekdays titles
	str_buffer += "<tr>\n";
	for (var n=0; n<7; n++)
		str_buffer += "	<td bgcolor=\"#87CEFA\">"+
		"<font color=\"white\" face=\"tahoma, verdana\" si ze=\"2\" style=\"font-size:10pt;\" >"+
		week_days[(n_weekstart+n)%7]+"</font></td>\n";
	// print calendar table
	str_buffer += "</tr>\n";
	while (dt_current_day.getMonth() == dt_datetime.getMonth() ||
		dt_current_day.getMonth() == dt_firstday.getMonth()) {
		// print row heder
		str_buffer += "<tr>\n";
		for (var n_current_wday=0; n_current_wday<7; n_current_wday++) {
				if (dt_current_day.getDate() == dt_datetime.getDate() &&
					dt_current_day.getMonth() == dt_datetime.getMonth())
					// print current date
					str_buffer += "	<td bgcolor=\"#FFB6C1\" align=\"right\">";
				else if (dt_current_day.getDay() == 0 || dt_current_day.getDay() == 6)
					// weekend days
					str_buffer += "	<td bgcolor=\"#DBEAF5\" align=\"right\">";
				else
					// print working days of current month
					str_buffer += "	<td bgcolor=\"white\" align=\"right\">";

				if (dt_current_day.getMonth() == dt_datetime.getMonth())
					// print days of current month
					str_buffer += "<a href=\"javascript:window.opener."+str_target+
					".value='"+dt2dtstr(dt_current_day)+"'; window.close();\">"+
					"<font color=\"black\" face=\"tahoma, verdana\" si ze=\"2\" style=\"font-size:10pt;\" >";
				else
					// print days of other months
					str_buffer += "<a href=\"javascript:window.opener."+str_target+
					".value='"+dt2dtstr(dt_current_day)+"'; window.close();\">"+
					"<font color=\"gray\" face=\"tahoma, verdana\" si ze=\"2\" style=\"font-size:10pt;\" >";
				str_buffer += dt_current_day.getDate()+"</font></a></td>\n";
				dt_current_day.setDate(dt_current_day.getDate()+1);
		}
		// print row footer
		str_buffer += "</tr>\n";
	}
	// print calendar footer
	//str_buffer +=
		"<form name=\"cal\">\n<tr><td colspan=\"7\" bgcolor=\"#87CEFA\">"+
		"<font color=\"White\" face=\"tahoma, verdana\" size=\"2\">"+
		"Time: <input type=\"text\" name=\"time\" value=\""+dt2tmstr(dt_datetime)+
		"\" size=\"8\" maxlength=\"8\"></font></td></tr>\n</form>\n" +
		"</table>\n" +
		"</tr>\n</td>\n</table>\n" +
		"</body>\n" +
		"</html>\n";

	var vWinCal = window.open("", "Calendar",
		"width=190,height=190,status=no,resizable=yes");
      //"width=200,height=250,status=no,resizable=yes,top=200,left=200");
	vWinCal.opener = self;
	var calc_doc = vWinCal.document;
	calc_doc.write (str_buffer);
	calc_doc.close();
}


/* ------------------------------------------------------------------------
 * datetime parsing and formatting routimes. modify them if you wish other datetime format
 * ------------------------------------------------------------------------ */
function str2dt (str_datetime) {
	//var re_date = /^(\d+)\-(\d+)\-(\d+)\s+(\d+)\:(\d+)\:(\d+)$/;
	var re_date = /^(\d+)\/(\d+)\/(\d+)$/;
	if (!re_date.exec(str_datetime))
		return alert("Invalid Datetime format: "+ str_datetime);
	return (new Date (RegExp.$3, RegExp.$2-1, RegExp.$1, RegExp.$4, RegExp.$5, RegExp.$6));
}

/* ------------------------------------------------------------------------
 * datetime parsing and formatting routimes. modify them if you wish other datetime format
 * ------------------------------------------------------------------------ */
function dt2dtstr (dt_datetime) {
	return (new String (
			strRight("0"+dt_datetime.getDate(),2)+"/"+strRight("0"+(dt_datetime.getMonth()+1),2)+"/"+dt_datetime.getFullYear()));
//			dt_datetime.getDate()+"-"+(dt_datetime.getMonth()+1)+"-"+dt_datetime.getFullYear()+" "));
}

// datetime parsing and formatting routimes. modify them if you wish other datetime format
function dt2tmstr (dt_datetime) {
	return (new String (
			dt_datetime.getHours()+":"+dt_datetime.getMinutes()+":"+dt_datetime.getSeconds()));
}

/* ------------------------------------------------------------------------
 *
 * ------------------------------------------------------------------------ */
function strLeft(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}

/* ------------------------------------------------------------------------
 *
 * ------------------------------------------------------------------------ */
function strRight(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

/* ------------------------------------------------------------------------
 *
 * ------------------------------------------------------------------------ */
function DelConfirm(Message, newUrl) {
	if (confirm(Message)) {
		location.href = newUrl;
	}
}

/* ------------------------------------------------------------------------
 *
 * ------------------------------------------------------------------------ */
function TabsClick(onTab) {
	for (cc=1;cc<=4;cc++) {
		document.getElementById("Tab"+cc).className = 'navTab';
		document.getElementById("Area"+cc).className = 'navArea';
	}
	document.getElementById("Tab"+onTab).className = 'navTabAct';
	document.getElementById("Area"+onTab).className = 'navAreaAct';
}

/* ------------------------------------------------------------------------
 *
 * ------------------------------------------------------------------------ */
function ViewNews(Elemento,Bottone,DimMinima,TestoApri,TestoChiudi,ImgApri,ImgChiudi) {
   //alert(document.getElementById(Elemento).style.height);
   if (document.getElementById(Elemento).style.height==DimMinima) {
      document.getElementById(Elemento).style.height="100%";
      document.getElementById(Bottone).alt=TestoChiudi;
      document.getElementById(Bottone).title=TestoChiudi;
      document.getElementById(Bottone).src=ImgChiudi;
   } else {  
      //alert('ok');
      document.getElementById(Elemento).style.height=DimMinima;
      document.getElementById(Bottone).alt=TestoApri;
      document.getElementById(Bottone).title=TestoApri;
      document.getElementById(Bottone).src=ImgApri;
   }
}

