/*---------------------------------------------
 Libreria di base.

 Mall4Net E-Solution é un prodotto realizzato
 da Valerio Maurizio - www.icio.it
 Tutti i diritti riservati©.

----------------------------------------------*/

var OP;
var IE4;
var IE5;
var SOWIN;
var IE5WIN;
var NS;
getAgent();

function getAgent() {
SOWIN = (navigator.userAgent.toLowerCase().indexOf("win") > -1) ? 1 : 0; 
OP = (window.opera) ? 1:0; 
IE4 = (document.all && !OP) ? 1:0; 
IE5 = (IE4 && document.getElementById) ? 1:0; 
IE5WIN = ((IE5) && SOWIN);
NS = (IE4 || IE5 || OP) ? 0:1;
}

function apriWin(sName,sTop,sLeft,sWidth,sHeight,sUrl) {
	wf =  "top="+ sTop + ",left=" + sLeft + ",width=" + sWidth + ",height=" + sHeight +",resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no";
	return window.open(sUrl,sName,wf);
}

function chiudiWin() {
	self.opener = self;
	self.close();
}

function openInter(id,type){

  var ele = DocFindElement("idd"+id);
  if (ele) {
	  ele.style.display = "block";
	  if(type=='on')
		ele.style.visibility = "visible";
		  else  ele.style.visibility="hidden";
  }
  return false;
}
function getViewportWidth() {

	if(window.innerWidth) return window.innerWidth-16;
	if(typeof window.document.documentElement.clientWidth=="number") return window.document.documentElement.clientWidth;
	return window.document.body.clientWidth;
}

function CenterWindow(Base,Altezza)
{
	var Top = (screen.height) ? (screen.height-Altezza)/2 - 26: 0;
	Top = (Top<0) ? 0 : Top;
	var Left = (screen.width) ? (screen.width-Base)/2 : 0;
	Left = (Left<0) ? 0 : Left;
	window.moveTo(Left,Top);
	window.resizeTo(Base,Altezza);
}
function ResizeWin(elem) {
	var Base = window.offsetWidth;
	var Altezza = window.offsetHeight;
	if (elem) {
		Base = elem.width + 100;
		Altezza = window.document.body.scrollHeight + 100;
	} else {
		Base = window.document.body.scrollWidth + 100;
		Altezza = window.document.body.scrollHeight + 45;
	}
	Base = (Base>screen.width) ? screen.width : Base;
	Altezza = (Altezza>screen.height) ? screen.height : Altezza;
	CenterWindow(Base,Altezza)
	self.focus();
}
function openRel(sTpl,sCod,ck) {
	var wf =  "top=50,left=50,width=890,height=480,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no";		
	var sURL = "Default.aspx?Template=" + sTpl + "&F=ID&V='" + sCod + "'&ck=" + ck;
	var wrel = window.open(sURL,"rel",wf);
}
function CheckForm() { //v3.1
  var i,p,p1,q,nm,test,num,min,max,errors='',args=CheckForm.arguments,theForm=args[0];
  for (i=1; i<(args.length-2); i+=3) { test=args[i+2]; val=theForm.elements[args[i]];
    if (val) { nm=args[i+1]; if (nm=='') nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isCheck')!=-1) { if (!theForm.elements[args[i]].checked) errors+='- '+nm+' obbligatorio.\n';
      } else if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');p1=val.lastIndexOf('.');
        if (p<2 || p==(val.length-1) || p1<p || p<0) errors+='- '+nm+' deve essere un indirizzo e-mail.\n';
      } else if (test.indexOf('isNum') != -1) { val = val.replace("\.","").replace(",","");
 	for(x=0;x<val.length;x++) { if (val.substring(x,1)!="0") {val=val.substring(x); break;} }
        num = parseFloat(val);  if (val!=''+num) errors+='- '+nm+' deve essere un numero. (' + val + ')\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+' deve essere un numero compreso tra '+min+' e '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' obbligatorio.\n'; }
  } if (errors) {alert('Attenzione:\n'+errors);return false} else {return true}
}

function DocFindElement(n) {
	var elem = document.getElementById(n);
	if (!elem) elem = document.all(n,0);
	if (!elem) elem = document[n];
	return elem;
}
function getv(ele) {
	return DocFindElement(ele).value;
}
function CheckNumeric(sNum)
{
	var num;
	sNum = sNum.replace("\.","");
	sNum = sNum.replace(",",".");
	num = parseFloat(sNum);
	if (isNaN(num)) num=0;
	return num;
}
var theElem=null;
function over(element) {
if (element.className!="LinkOn")
	element.className="LinkOver";
element.style.cursor = "hand";
}
function hilight(element) {
if (theElem!=null) 
	theElem.className="LinkOut";
element.className="LinkOn";
element.style.cursor = "hand";
theElem=element;
}
function out(element) {
if (element.className!="LinkOn")
	element.className = "LinkOut";
element.style.cursor = "default";
}
//var theSel = null;
function MenuClick(Sel) {
	//if (theSel!=null && theSel!=Sel) MenuClick(theSel);
	var thisMenu = document.getElementById('cat'+Sel);
	if (thisMenu) {
		if (thisMenu.style.display == "block") {
			thisMenu.style.display = "none";
			theSel='';
		}
		else {
			thisMenu.style.display = "block";
			theSel=Sel;
		     }
		return false;
	}
	else {
		return true;
	}
}
function ShowHide(Sel) {
	var thisMenu = DocFindElement(Sel);
	if (thisMenu) {
		if (thisMenu.style.display == "block") {
			thisMenu.style.display = "none";;
		}
		else {
			thisMenu.style.display = "block";
		}
		return false;
	}
	else {
		return true;
	}
}

function DoZoom(Tpl,id,w,h,scroll) {
  pagina="Default.aspx?Template="+ Tpl + "&F=ID&V=" + id ;
  base=w;
  altezza=h;
  Sx = (screen.width) ? (screen.width-base)/2 : 0;
  Top = (screen.height) ? (screen.height-altezza)/2 - 26: 0;
  parametri ='height='+altezza+',width='+base+',top='+Top+',left='+Sx+',scrollbars='+scroll+',status=0,titlebar=0,toolbar=0'
  window.open(pagina,"zoom",parametri)
}
function DoZoomStr(Tpl,id,w,h,scroll) {
  DoZoom(Tpl,"'"+id+"'",w,h,scroll);
}

function DoDelMaillist(sck)
{
	if (CheckForm(document.forms[0],'FullName','Nome','R','Email','Indirizzo E-mail','RisEmail'))
	{
		sEmail = DocFindElement('Email').value;
		window.location = "Default.aspx?Action=del&SubTemplate=CancellatoSI.html&F=Email&V='"+ sEmail +"'&ck="+sck;
		return true;
	}
	else { return false; }
}

function Apri(pagina,base,altezza){
Sx = (screen.width) ? (screen.width-base)/2 : 0;
Top = (screen.height) ? (screen.height-altezza)/2 - 26: 0;
parametri ='height='+altezza+',width='+base+',top='+Top+',left='+Sx+',scrollbars=1,status=0,titlebar=0,toolbar=0'
window.open(pagina,"",parametri)
}

function Apri(pagina,base,altezza){
Sx = (screen.width) ? (screen.width-base)/2 : 0;
Top = (screen.height) ? (screen.height-altezza)/2 - 26: 0;
parametri ='height='+altezza+',width='+base+',top='+Top+',left='+Sx+',scrollbars=1,status=0,titlebar=0,toolbar=0'
window.open(pagina,"",parametri)
}

function DeleteItem() {
			if (confirm("Si vuole eliminare il prodotto dall'ordine?"))
				{ return true } else { return false }
		}
function DeleteAll() {
			if (confirm("Si vogliono eliminare tutti i prodotti dall'ordine?"))
				{ return true } else { return false }
		}
/**************************************
	Controllo del Codice Fiscale
	Linguaggio: JavaScript
***************************************/

function ControllaCF(cf)
{
	var validi, i, s, set1, set2, setpari, setdisp;
	if( cf == '' )  return '';
	cf = cf.toUpperCase();
	if( cf.length != 16 )
		return "Lunghezza del codice fiscale non\n"
		+"corretta: il codice fiscale dovrebbe essere lungo\n"
		+"esattamente 16 caratteri.\n";
	validi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	for( i = 0; i < 16; i++ ){
		if( validi.indexOf( cf.charAt(i) ) == -1 )
			return "Il codice fiscale contiene un carattere non valido `" +
				cf.charAt(i) +
				"'.\nI caratteri validi sono le lettere e le cifre.\n";
	}
	set1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	set2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";
	setpari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	setdisp = "BAKPLCQDREVOSFTGUHMINJWZYX";
	s = 0;
	for( i = 1; i <= 13; i += 2 )
		s += setpari.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
	for( i = 0; i <= 14; i += 2 )
		s += setdisp.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
	if( s%26 != cf.charCodeAt(15)-'A'.charCodeAt(0) )
		return "Codice fiscale non corretto:\n"+
			"il codice di controllo non corrisponde.\n";
	return "";
}
/*****************************************
	Controllo della Partita I.V.A.
	Linguaggio: JavaScript
******************************************/

function ControllaPIVA(pi)
{
	if( pi == '' )  return '';
	if( pi.length != 11 )
		return "Lunghezza della partita IVA non\n" +
			"corretta: la partita IVA dovrebbe essere lunga\n" +
			"esattamente 11 caratteri.\n";
	validi = "0123456789";
	for( i = 0; i < 11; i++ ){
		if( validi.indexOf( pi.charAt(i) ) == -1 )
			return "La partita IVA contiene un carattere non valido `" +
				pi.charAt(i) + "'.\nI caratteri validi sono le cifre.\n";
	}
	s = 0;
	for( i = 0; i <= 9; i += 2 )
		s += pi.charCodeAt(i) - '0'.charCodeAt(0);
	for( i = 1; i <= 9; i += 2 ){
		c = 2*( pi.charCodeAt(i) - '0'.charCodeAt(0) );
		if( c > 9 )  c = c - 9;
		s += c;
	}
	if( ( 10 - s%10 )%10 != pi.charCodeAt(10) - '0'.charCodeAt(0) )
		return "Partita IVA non valida:\n" +
			"il codice di controllo non corrisponde.\n";
	return '';
}


/*==============================================================================

    Routines written by John Gardner - 2003 - 2005

    See www.braemoor.co.uk/software for information about more freeware
    available.

================================================================================

Routine to write a session cookie

    Parameters:
        cookieName        Cookie name
        cookieValue       Cookie Value
    
    Return value:
        true              Session cookie written successfullly
        false             Failed - persistent cookies are not enabled

   e.g. if (writeSessionCookie("pans","drizzle") then
           alert ("Session cookie written");
        else
           alert ("Sorry - Session cookies not enabled");
*/

function writeSessionCookie (cookieName, cookieValue) {
  if (testSessionCookie()) {
    document.cookie = escape(cookieName) + "=" + escape(cookieValue) + "; path=/";
    return true;
  }
  else return false;
}

/*==============================================================================

Routine to get the current value of a cookie

    Parameters:
        cookieName        Cookie name
    
    Return value:
        false             Failed - no such cookie
        value             Value of the retrieved cookie

   e.g. if (!getCookieValue("pans") then  {
           cookieValue = getCoookieValue ("pans2);
        }
*/

function getCookieValue (cookieName) {
  var exp = new RegExp (escape(cookieName) + "=([^;]+)");
  if (exp.test (document.cookie + ";")) {
    exp.exec (document.cookie + ";");
    return unescape(RegExp.$1);
  }
  else return false;
}

/*==============================================================================

Routine to see if session cookies are enabled

    Parameters:
        None
    
    Return value:
        true              Session cookies are enabled
        false             Session cookies are not enabled

   e.g. if (testSessionCookie())
           alert ("Session coookies are enabled");
        else
           alert ("Session coookies are not enabled");
*/

function testSessionCookie () {
  document.cookie ="testSessionCookie=Enabled";
  if (getCookieValue ("testSessionCookie")=="Enabled")
    return true 
  else
    return false;
}

/*==============================================================================

Routine to see of persistent cookies are allowed:

    Parameters:
        None
    
    Return value:
        true              Session cookies are enabled
        false             Session cookies are not enabled

   e.g. if (testPersistentCookie()) then
           alert ("Persistent coookies are enabled");
        else
           alert ("Persistent coookies are not enabled");
*/

function testPersistentCookie () {
  writePersistentCookie ("testPersistentCookie", "Enabled", "minutes", 1);
  if (getCookieValue ("testPersistentCookie")=="Enabled")
    return true  
  else 
    return false;
}

/*==============================================================================

Routine to write a persistent cookie

    Parameters:
        CookieName        Cookie name
        CookieValue       Cookie Value
        periodType        "years","months","days","hours", "minutes"
        offset            Number of units specified in periodType
    
    Return value:
        true              Persistent cookie written successfullly
        false             Failed - persistent cookies are not enabled
    
    e.g. writePersistentCookie ("Session", id, "years", 1);
*/       

function writePersistentCookie (CookieName, CookieValue, periodType, offset) {

  var expireDate = new Date ();
  offset = offset / 1;
  
  var myPeriodType = periodType;
  switch (myPeriodType.toLowerCase()) {
    case "years": 
     var year = expireDate.getYear();     
     // Note some browsers give only the years since 1900, and some since 0.
     if (year < 1000) year = year + 1900;     
     expireDate.setYear(year + offset);
     break;
    case "months":
      expireDate.setMonth(expireDate.getMonth() + offset);
      break;
    case "days":
      expireDate.setDate(expireDate.getDate() + offset);
      break;
    case "hours":
      expireDate.setHours(expireDate.getHours() + offset);
      break;
    case "minutes":
      expireDate.setMinutes(expireDate.getMinutes() + offset);
      break;
    default:
      alert ("Invalid periodType parameter for writePersistentCookie()");
      break;
  } 
  
  document.cookie = escape(CookieName ) + "=" + escape(CookieValue) + "; expires=" + expireDate.toGMTString() + "; path=/";
}  

/*==============================================================================

Routine to delete a persistent cookie

    Parameters:
        CookieName        Cookie name
    
    Return value:
        true              Persistent cookie marked for deletion
    
    e.g. deleteCookie ("Session");
*/    

function deleteCookie (cookieName) {

  if (getCookieValue (cookieName)) writePersistentCookie (cookieName,"Pending delete","years", -1);  
  return true;     
}

function roundTo2(n){
	units = n * 100;
	units = Math.round(units);
	strUnits = "" + units;
	len = strUnits.length
	}

function calckw1(hp){ 
	var hpvalue1 = parseFloat(hp);
	kwvalue1 = (hpvalue1 * 0.7457) - 2;
	roundTo2(kwvalue1); 
	document.write('('+strUnits.substring(0, len - 2) +' KW)');
	}
	
// funzione per assegnare l'oggetto XMLHttpRequest
// compatibile con i browsers più recenti e diffusi
function getXMLHttpRequest() {

 var XHR = null;
 
 var browserUtente = navigator.userAgent.toUpperCase();


 // browser standard con supporto nativo
 // non importa il tipo di browser
 if(typeof(XMLHttpRequest) === "function" || typeof(XMLHttpRequest) === "object")
  XHR = new XMLHttpRequest();

 // browser Internet Explorer
 // è necessario filtrare la versione 4
 else if(window.ActiveXObject && browserUtente.indexOf("MSIE 4") < 0) {
 
  // la versione 6 di IE ha un nome differente
  // per il tipo di oggetto ActiveX
  if(browserUtente.indexOf("MSIE 5") < 0)
   XHR = new ActiveXObject("Msxml2.XMLHTTP");

  // le versioni 5 e 5.5 invece sfruttano lo stesso nome
  else
   XHR = new ActiveXObject("Microsoft.XMLHTTP");
 }

 return XHR;
} 
function ValidAjax(Tpl,fld,val,ck) {
	var ajax = getXMLHttpRequest();
	if (ajax) { // syncrona !!
		ajax.open("get","Default.aspx?ck="+ck+"&Template="+Tpl+"&VN=STRWHERE&VV="+fld+" LIKE '"+val+"%'", false);
		ajax.send(null);
		if(ajax.readyState == 4) {
			if(ajax.status == 200) {
				var resp = ajax.responseText;
				var p = resp.indexOf(" -->");
				if (p>=0) resp=resp.substring(p+4,resp.length);
				try { if (eval(resp)) return true; }
				catch (err) {alert(resp);}
			} else
				alert("Operazione fallita, errore numero " + ajax.status);
		}
	} else 
		alert ('Funzione AJAX non abilitata!');

	return false
}

function ExecAjaxCarr(act,Item,Description,Price,Price1,Quantity,tpl,ck) {
	var ajax = getXMLHttpRequest();
	if (ajax) { // syncrona !!
		ajax.open("get","Default.aspx?Action="+act+"&Item="+Item+"&Description="+Description+"&Price="+Price+"&Price1="+Price1+"&Quantity="+Quantity+"&Template="+tpl+"&ck="+ck, false);
		ajax.send(null);
		if(ajax.readyState == 4) {
			if(ajax.status == 200) {
				var resp = ajax.responseText;
				var p = resp.indexOf(" -->");
				if (p>=0) resp=resp.substring(p+4,resp.length);
				try { if (eval(resp)) return true; }
				catch (err) {alert(resp);}
			
			} else
				alert("Operazione fallita, errore numero " + ajax.status);
		}
	} else 
		alert ('Funzione AJAX non abilitata!');

	return false
}
function ExecAjaxModCarr(act,Id,Item,Description,Price,Price1,Quantity,tpl,ck) {
	var ajax = getXMLHttpRequest();
	if (ajax) { // syncrona !!
		ajax.open("get","Default.aspx?Action="+act+"&ID="+Id+"&Item="+Item+"&Description="+Description+"&Price="+Price+"&Price1="+Price1+"&Quantity="+Quantity+"&Template="+tpl+"&ck="+ck, false);
		ajax.send(null);
		if(ajax.readyState == 4) {
			if(ajax.status == 200) {
				var resp = ajax.responseText;
				var p = resp.indexOf(" -->");
				if (p>=0) resp=resp.substring(p+4,resp.length);
				try { if (eval(resp)) return true; }
				catch (err) {alert(resp);}
			
			} else
				alert("Operazione fallita, errore numero " + ajax.status);
		}
	} else 
		alert ('Funzione AJAX non abilitata!');

	return false
}



/***********************************************
* Dynamic Ajax Content- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

var bustcachevar=1 //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects=""
var rootdomain="http://"+window.location.hostname
var bustcacheparameter=""

function ajaxpage(url, containerid){
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.onreadystatechange=function(){
loadpage(page_request, containerid)
}
if (bustcachevar) //if bust caching of external page
bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
page_request.open('GET', url+bustcacheparameter, true)
page_request.send(null)
}

function loadpage(page_request, containerid){
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
document.getElementById(containerid).innerHTML=page_request.responseText
}

function loadobjs(){
if (!document.getElementById)
return
for (i=0; i<arguments.length; i++){
var file=arguments[i]
var fileref=""
if (loadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
if (file.indexOf(".js")!=-1){ //If object is a js file
fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", file);
}
else if (file.indexOf(".css")!=-1){ //If object is a css file
fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", file);
}
}
if (fileref!=""){
document.getElementsByTagName("head").item(0).appendChild(fileref)
loadedobjects+=file+" " //Remember this object as being already added to page
}
}
}

function DisableEnableLinks(xHow){
  objLinks = document.links;
  for(i=0;i<objLinks.length;i++){
    objLinks[i].disabled = xHow;
    //link with onclick
    if(objLinks[i].onclick && xHow){  
        objLinks[i].onclick = new Function("return false;" + objLinks[i].onclick.toString().getFuncBody());
    }
    //link without onclick
    else if(xHow){  
      objLinks[i].onclick = function(){return false;}
    }
    //remove return false with link without onclick
    else if(!xHow && objLinks[i].onclick.toString().indexOf("function(){return false;}") != -1){            
      objLinks[i].onclick = null;
    }
    //remove return false link with onclick
    else if(!xHow && objLinks[i].onclick.toString().indexOf("return false;") != -1){  
      strClick = objLinks[i].onclick.toString().getFuncBody().replace("return false;","")
      objLinks[i].onclick = new Function(strClick);
    }
  }
}

String.prototype.getFuncBody = function(){ 
  var str=this.toString(); 
  str=str.replace(/[^{]+{/,"");
  str=str.substring(0,str.length-1);   
  str = str.replace(/\n/gi,"");
  if(!str.match(/\(.*\)/gi))str += ")";
  return str; 
} 

