
var numb = '0123456789';
var lwr = 'abcdefghijklmnopqrstuvwxyz';
var upr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var dd = '0123456789/-';
var rootdomain='http://'+window.location.hostname;

function ajaxinclude(url) {
	var page_request = false;
	if (window.XMLHttpRequest) // if Mozilla, Safari etc
		page_request = new XMLHttpRequest();
	else if (window.ActiveXObject){ // if IE
		try {
		page_request = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e){
		try{
		page_request = new ActiveXObject("Microsoft.XMLHTTP");
		}
	catch (e){}
	}
}
else return false;
page_request.open('GET', url, false); //get page synchronously 
page_request.send(null);
writecontent(page_request);
}

function writecontent(page_request){
 if (window.location.href.indexOf("http")==-1 || page_request.status==200) document.write(page_request.responseText);
}




function isValid(parm,val) {
		if (parm == "") return true;
		for (i=0; i<parm.length; i++) {
			if (val.indexOf(parm.charAt(i),0) == -1) return false;
		}
	return true;
}


function epuraCampo(parm,val) {
	var temp='';
	if (parm == "") return temp;
		for (i=0; i<parm.length; i++) {
			if (!(val.indexOf(parm.charAt(i),0) == -1)) {temp=temp+parm.charAt(i);}
		}
	return temp;
}



function epuraisNumber(parm) {return epuraCampo(parm,numb);}
function epuraisLower(parm) {return epuraCampo(parm,lwr);}
function epuraisUpper(parm) {return epuraCampo(parm,upr);}
function epuraisAlpha(parm) {return epuraCampo(parm,lwr+upr);}
function epuraisDate(parm) {return epuraCampo(parm,dd);}
function epuraisAlphanum(parm) {return epuraCampo(parm,lwr+upr+numb);} 


function isNumber(parm) {return isValid(parm,numb);}
function isLower(parm) {return isValid(parm,lwr);}
function isUpper(parm) {return isValid(parm,upr);}
function isAlpha(parm) {return isValid(parm,lwr+upr);}
function isDate(parm) {return isValid(parm,dd);}
function isAlphanum(parm) {return isValid(parm,lwr+upr+numb);} 



// ora controllo tutti i campi con caratteri particolari (apostrofi, ecc.) 
function codificaCaratteri(stringa) {
                             var str;
                             str=stringa.replace('\'','\'');
                             return str;
}
                            
// questo invece mi codifica un campo di tipo Data "aggiustando" i caratteri strani        
function codificaData(stringa) {
                             var str;
                             str=stringa.replace('-','/');
                             str=str.replace('\\','/');
                             if (!(isDate(stringa))) {str=epuraisDate(str);alert('Attenzione, Carattere non ammesso');}
                             return str;
}


function controlloobbligatorio(elemento,changebck) {
	if(elemento.value=='') {
              elemento.focus();
	      if (changebck == true) {elemento.style.background='#f08080';}
              alert('Attenzione! questo campo non può essere vuoto.');
              return false;
          } else {
	      if (changebck == true) {elemento.style.background='#ffffff';}
	      return true;
	   }
}



function isDateLessToday(str) {
	if (str=='') {return true;}
	spz = str.split('/'); 
	dat = new Date(spz[2], spz[1]-1, spz[0]);
	var oggi = new Date();
	if ((dat) <= (oggi))  {return true;} else {return false;}
}




/* questa è da usare nei form ed e' la versione semplificata */
function controlladatasemplice(elemento){
	return controlladata(elemento.value,elemento,false);
}


/* questa è da usare nei form */
function controlladata(stringa,elemento,changebck) {
	if (controllo_data(stringa)||(stringa=='')){
		if (changebck == true) {elemento.style.background='#ffffff';}
		return true;	
	} else {
	  alert('La data non è nel formato corretto');
	  if (changebck == true) {elemento.style.background='#f08080';}
	  elemento.focus();
          return false;
	}
}

/* questa genera solo true o false, da non usare nei form */
function controllo_data(stringa){	
	var espressione = /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/;	
	if (!espressione.test(stringa))	{return false;}
		else{				anno = parseInt(stringa.substr(6),10);
		mese = parseInt(stringa.substr(3, 2),10);
		giorno = parseInt(stringa.substr(0, 2),10);
						var data=new Date(anno, mese-1, giorno);
		if(data.getFullYear()==anno && data.getMonth()+1==mese && data.getDate()==giorno)
			{return true;}else{return false;}	
	}

}


function urlencode (str) {
	str = escape(str);
	var a = str.replace(/[*+\/@]|%20/g,
		function (s) {
		switch (s) {
			case "*": s = "%2A"; break;
			case "+": s = "%2B"; break;
			case "/": s = "%2F"; break;
			case "@": s = "%40"; break;
			case "%20": s = "+"; break;
			}			
		return s;
		}
		);
	return a;
}



function filesize(file, id) {

    var xmlHttpObj = null;
    var size = null;
    var risposta = null;
   
    if (typeof XMLHttpRequest != "undefined") {
        xmlHttpObj = new XMLHttpRequest();
    }
    else {
        try {
            xmlHttpObj = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP");
            } 
            catch (e) {
                xmlHttpObj = null;
            }
        }
    }

   
    xmlHttpObj.open("HEAD", file, true);
         
    xmlHttpObj.onreadystatechange = function() {
        if (xmlHttpObj.readyState == 4) {
            switch(xmlHttpObj.status) {
            
                case 200: // Page found
                case 304: // Status Code on Opera when page reload
                     size = xmlHttpObj.getResponseHeader("Content-Length");
		     if (size<1001){
		     	risposta="&#160; ("+size+" byte)";
		     	document.getElementById(id).innerHTML = risposta;
			} 
			else
			{
			risposta="&#160; ("+Math.round(size / 1000)+" Kb)";
			document.getElementById(id).innerHTML = risposta;
			}
                     return;
                     break;
                     
                case 0: // Worong protocol
                    //alert("Can't load file using 'file://' protocol")
                    return;
                    break;
                    
                case 404: // Page not found
                    //alert("File not found: "+file);
                    return;
                    break;
                    
                default:
                    //alert("Unrecognized status code: ["+xmlHttpObj.status+"]")
                    return;
                    break;
            }
        }            
    }          
    xmlHttpObj.send(null); 
    delete xmlHttpObj;
    

}



			function eseguiRichiesta(url,idelement) {
				eseguiRichiestaLowLevel(url,idelement,false);
			}


                        function eseguiRichiestaLowLevel(url,idelement,messaggio) {
                        
                                var http_request = false;
				
                        
                                if (window.XMLHttpRequest) { // Mozilla, Safari,...
                                    http_request = new XMLHttpRequest();
                                    if (http_request.overrideMimeType) {
                                        http_request.overrideMimeType('text/xml');
                                        // Vedi note sotto
                                    }
                                } else if (window.ActiveXObject) { // IE
                                    try {
                                        http_request = new ActiveXObject("Msxml2.XMLHTTP");
                                    } catch (e) {
                                        try {
                                            http_request = new ActiveXObject("Microsoft.XMLHTTP");
                                        } catch (e) {}
                                    }
                                }
                        
                                if (!http_request) {
                                    alert('Giving up :( Non riesco a creare una istanza XMLHTTP');
                                    return false;
                                }
                                http_request.onreadystatechange = function() { alertContents(http_request,idelement); };
                                http_request.open('GET', url, true);
				http_request.setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" );
                                http_request.send(null);
                                return true;
                            }
                        

                            function alertContents(http_request,elemento) {
                        	//alert('tt:'+http_request.responseText);
                                if (http_request.readyState == 4) {
                                    if (http_request.status == 200) {
                                        
                                        document.getElementById(elemento).innerHTML = http_request.responseText;
                                        
                                    } else {
                                        if (messaggio) alert('Si è verificato un problema con la richiesta');
                                    }
                                }
                        
                            }


function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	var i = '';
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found ) 
	{
		return null;
	}
}

/*
only the first 2 parameters are required, the cookie name, the cookie
value. Cookie time is in milliseconds, so the below expires will make the 
number you pass in the Set_Cookie function call the number of days the cookie
lasts, if you want it to be hours or minutes, just get rid of 24 and 60.

Generally you don't need to worry about domain, path or secure for most applications
so unless you need that, leave those parameters blank in the function call.
*/
function Set_Cookie( name, value, expires, path, domain, secure ) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	// if the expires variable is set, make the correct expires time, the
	// current script below will set it for x number of days, to make it
	// for hours, delete * 24, for minutes, delete * 60 * 24
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60;
	}
	//alert( 'today ' + today.toGMTString() );// this is for testing purpose only
	var expires_date = new Date( today.getTime() + (expires) );
	//alert('expires ' + expires_date.toGMTString());// this is for testing purposes only

	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
			( ( path ) ? ";path=" + path : "") +
			( ( domain ) ? ";domain=" + domain : "" ) +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
