//-------------------------------------------------------------------
//
// Codice per gestione degli Errori
//
//window.onerror = HandleError
//
//function HandleError(message, url, line) {
//  var str = "An error has occurred in this dialog." + "\n\n"
//  + "Error: " + line + "\n" + message;
//  alert(str);
//  //window.close();
//  return true;
//}


// oggetto in cui tenere i vari richiami
fin = {
   onloads:[],
   add:function(funz){this.onloads[this.onloads.length]=funz},
   init:function(){for(var x in this.onloads) eval(this.onloads[x])}
};

// setto l' onload
window.onload=function(){fin.init()}   



function winOpen(oUrl,oWinName,oWinLayout){
	window.open(oUrl,oWinName,oWinLayout);
	return false;
}



//-------------------------------------------------------------------
//
// Rileva le coordinate assolute di un oggetto nella finestra
//
function getPageCoords (element) { // thanks to 'Martin Honnen' for this function
   var coords = {x: 0, y: 0};
   while (element) {
      coords.x += element.offsetLeft;
      coords.y += element.offsetTop;
      element = element.offsetParent;
   }
   return coords;
}



//-------------------------------------------------------------------
//
// Codice per gestione delle diversitā tra i browser
//
function checkBrowser(caso){
	switch(caso){
		case 'photoGallery':
				if (navigator.userAgent.indexOf('Gecko')	>= 0){
					strAlert = 'Se usi come compressore WinZip '
						+ 'ed il file che stai scaricando viene salvato con estensione .zip\n'
						+ 'devi rinominarlo con estenzione .gz\n\n'
						+ 'In caso di problemi contatta il webmaster.';
					alert( strAlert );
				}
			break;
	}
}



//-------------------------------------------------------------------
//
// Codice per l'urlencode delle stringhe
//
function urlencode(strText) {
	// Autore: 			Charles Toepfer
	// Link articolo:	http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=3623&lngWId=2

	var isObj;
	var trimReg;
	if( typeof(strText) == "string" ) {
		if( strText != null ) {
			trimReg = /(^\s+)|(\s+$)/g;
			strText = strText.replace( trimReg, '');
			for(i=32;i<256;i++) {
				strText = strText.replace(String.fromCharCode(i),escape(String.fromCharCode(i)));
				//strText = strText.replace(strText.fromCharCode(i),escape(strText.fromCharCode(i)));
			}
		}
	}
	return strText;
}



//-------------------------------------------------------------------
//
// Codice per la stampa
//
function stampa(nomeDiv){

	if( nomeDiv == 'TestoL' && window.print())
		window.print();
	else{
		elementToPrint = document.getElementById(nomeDiv);
		winOpen('/4U/pop.php?action=print','winstampa','width=770,height=400,scrollbars=yes,resizable=yes');
	}


	return false;
}



//-------------------------------------------------------------------
//
// Codice per dare il focus alla finestra
//
function daiFocus(){
	this.focus();
}



//-------------------------------------------------------------------
//
// Codice per mostrare un blocco
//
function showBlock(id){
	document.getElementById(id).style.display='inline';
}



//-------------------------------------------------------------------
//
// Codice per nascondere un blocco
//
function hideBlock(id){
	document.getElementById(id).style.display='none';
}



//-------------------------------------------------------------------
//
// Codice per nascondere un blocco
//
function showHide(id){
	document.getElementById(id).style.display= (document.getElementById(id).style.display == 'block')? 'none' : 'block' ;

	if(document.getElementById('lbl'+id))
		document.getElementById('lbl'+id).innerText= (document.getElementById('lbl'+id).innerText == 'show')? 'hide' : 'show';

	if(document.getElementById('img'+id))
		document.getElementById('img'+id).src = (document.getElementById(id).style.display == 'block')? imgBaseDir+'/globali/bulletMenu_on.gif' :  imgBaseDir+'/globali/1pxA.gif';


	return false;
}



//-------------------------------------------------------------------
//
// Codice per il rollover delle immagini
//
function rollon(imgName) {
	if (ok_img) document[imgName].src = eval(imgName + "_on.src");
}

function rolloff(imgName) {
	if (ok_img) document[imgName].src = eval(imgName + "_off.src");
}



//-------------------------------------------------------------------
//
// Funzione per effettuare un PostBack
//
// uso questa variabile globale che viene modificata dalla funzione passata nell onsubmit
// ricorda di valorizzarla nella funziona chiamata sull onsubmit
var _doPostBack = true;
function __DoPostBack( formName, sender, argument) {
   // Devo includere nella pagina i seguenti HiddenFilds
   // Nella stessa form che richiamo con il parametro "formName"
   // <input type="hidden" name="__Sender" value="">
   // <input type="hidden" name="__Argument" value="">

   document.forms[formName].__Sender.value = sender;
   document.forms[formName].__Argument.value = argument;
   if(arguments.length>3){
      try{
        p1 = (arguments.length>4)? arguments[4]:'';
         // metto in un try perchč IE esegue correttamente la funzione, ma da un errore
         // nel settaggio dell'handler
         eval("document.forms[formName].onsubmit = "+arguments[3]+"(formName,p1)");
      }catch(e){}
   }
   if(_doPostBack) document.forms[formName].submit();
   return false;
}



//-------------------------------------------------------------------
//
// Funzione per la creazione di link esterni
//
function externalLinks() {
 if (!document.getElementsByTagName) return;
 var anchors = document.getElementsByTagName("a");
 for (var i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external")
     anchor.target = "_blank";
   else if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "nse")
      NoSpamEmail(anchor);
 }
}
fin.add("externalLinks()");



//-------------------------------------------------------------------
//
// Test per la vailditā di dati standard
//
function IsValidCAP(str) {
   var cap_re = new RegExp("^[0-9]{5}$");
   return cap_re.test(str);
}
function IsValidPhoneNumber(str) {
   var Tel_re = new RegExp("^[0-9\(\)\-/ ]+$");
   return Tel_re.test(str);
}

function checkEmail(strEmail){
   email_re = new RegExp("^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$");
   bRes = email_re.test(strEmail);
   return bRes;
}

function IsValidPWD(str){
   var un_re = new RegExp("^[a-zA-Z0-9_\-]{1,50}$");
   oResult=un_re.test(str);
   //alert(str + ' - ' + oResult);
   return oResult;
}

function checkUrl(str){
   var re = new RegExp( "^((http|https|ftp)\://)?[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*[^\.\,\)\(\s]$", "i" );
   return re.test(str);

}

function checkPartitaIVA(str){
   var re = new RegExp( "^[0-9]{11}$" );
   return re.test(str);
}



//-------------------------------------------------------------------
//
// visualizza in verticale i records di una tabella con anche la descrizione
// (intestazione delle colonne del recordset) dei valori
// La tabella deve contenere i seguneti tag <thead>[<tfoot>]<tbody>
//
function RuotaTab(tabID,divOutputID){
   function getData(cell){
      s='';
      if(cell.hasChildNodes() && cell.childNodes[0].nodeType==3)
         s = cell.childNodes.item(0).data;//innerHTML;
      else if(cell.hasChildNodes() && cell.childNodes[0].nodeType==1){
         s = cell.childNodes[0].childNodes.item(0).data;
      }

      return s;
   }

   var myTable = document.getElementById(tabID);
   var divOutput = document.getElementById(divOutputID);

   if(divOutput.style.display == 'none' || divOutput.childNodes.length>0){
      divOutput.style.display = 'block';
      return true;
   }


   var sTmp=''; var i=0; var j=0;

   if ( myTable != null && divOutput!=null) {

      p = document.createElement("p");
      p.className = "close";
      a = document.createElement("a");
      a.setAttribute( "href", "javascript:;" )
      a.onclick = function(){divOutput.style.display = 'none'; };
      a.appendChild(document.createTextNode("chiudi"));
      p.appendChild(a);
      divOutput.appendChild(p);

      tbody = myTable.getElementsByTagName("tbody").item(0);
      thead = myTable.getElementsByTagName("thead").item(0);

      for(i=0; i < tbody.rows.length; i++){

         for (j=0; j < tbody.rows[i].cells.length; j++) {
            div = document.createElement("div");
            div.className = "recVertical";

            //alert(thead.rows[0].cells[j].innerHTML);

            span = document.createElement("span");
            span.className = "label";
            span.appendChild(document.createTextNode( getData(thead.rows[0].cells[j]) ));
            div.appendChild(span);

            span = document.createElement("span");
            span.className = "val";
            span.appendChild(document.createTextNode( getData(tbody.rows[i].cells[j])) );
            div.appendChild(span);

            divOutput.appendChild(div);
         }
      }

      br = document.createElement("br");
      span.className = "clear";
      divOutput.appendChild(br);

   } else {
      alert('Non esiste la tabella da esportare');
   }

   return true;
}



//-------------------------------------------------------------------
//
// JS REMOTING
//
function doClientCallback(controlID, clientCallbackData, sendForm){
   // Oggetto XmlHttp
   var request;
   // Preparo il form da inviare
   var data = "__JsRemotingControlID=" + encodeURIComponent(controlID) +
      "&"+
      "__JsRemotingClientCallbackData=" + encodeURIComponent(clientCallbackData);

   // vengono inviati tutti i campi attivi/valorizzati del form
   if (sendForm && (theForm)){
      for (var x = 0; x < theForm.elements.length; x++)   {
         var obj = theForm.elements[x];
         if (!(obj.value) || obj.type == "submit" || ((obj.type == "checkbox" || obj.type == "radio") && !obj.checked)) continue;
         data += '&' + encodeURIComponent(obj.name) + '=' + encodeURIComponent(obj.value);
      }
   }
   //alert(data);

   // Se č IE uso gli ActiveX
   if (navigator.userAgent.indexOf('MSIE') > 0){
      request = new ActiveXObject("Microsoft.XMLHTTP");
      // Avvio operazione asincrona
      request.Open("POST", theUrl, true);
   }   else{
      try{
         request = new XMLHttpRequest();
      }
      catch (er) {}
      // Avvio operazione asincrona
      request.open('POST', theUrl, true, null, null);
   }
   // Imposto il tipo di content-type per il form
   request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
   // Creo la funzione da richiamare quando termina la chiamata
   request.onreadystatechange = function()
      {
         // Se la richiesta č andata a buon fine
         if (request.readyState == 4)
            eval(request.responseText);
      }

   // Invio la richiesta
   request.send(data);
}



//-------------------------------------------------------------------
//
// Elimina tutti i nodi figli di un nodo
//
function DeleteChilds(tree) {
   while( tree.hasChildNodes() ){
      //alert(tree.nodeType)
      for(var i=0; i<tree.childNodes.length; i++){
         DeleteChilds(tree.childNodes[i]);
         tree.removeChild(tree.childNodes[i]);
      }
   }
}



//-------------------------------------------------------------------
//
// Creazione Menu Immagini
//
var ImgMenu_ArrPreload = new Array();
function ImgMenu_Crea(elBase,datiImg) {

   divItem = document.createElement("div");
   divItem.className = "item";

   img = document.createElement("img");
   img.setAttribute( "src", ImgMenu_DirImg+datiImg.nome);
   img.setAttribute( "width", datiImg.width );
   img.setAttribute( "height", datiImg.height );
   img.setAttribute( "alt", datiImg.alt );
   if(typeof(datiImg.cssstyle)!='undefined'){
      try{
         arr = datiImg.cssstyle.split(':');
         eval("img.style."+arr[0]+" = '"+arr[1]+"';");
      }catch(e){}
   }

   if(typeof(datiImg.cssclass)!='undefined')
      img.className(datiImg.cssclass );


   if(typeof(datiImg.nolink)=='undefined'){
      a = document.createElement("a");
      a.setAttribute( "href", datiImg.url )
      if(typeof(datiImg.accesskey)!='undefined'){
         a.setAttribute( "accesskey", datiImg.accesskey );
      }
      a.onmouseover = function(){ImgMenu_SwapImg('over',this)};//ImgMenu_SwapImg_Over;//function(){alert(this.childNodes[0].src)};
      a.onmouseout = function(){ImgMenu_SwapImg('out',this)};//function(){alert('out'+this.childNodes[0].src)};
      //a.onfocus = function(){ImgMenu_SwapImg('over',this)};
      //a.onblur = function(){ImgMenu_SwapImg('out',this)};
      a.appendChild(img);

      divItem.appendChild(a);
   }else{
      divItem.appendChild(img);
   }

   elBase.appendChild(divItem);

   return false;

}

function ImgMenu_SwapImg(action,el){
   arr = el.childNodes[0].src.split('/');

   if(el.childNodes[0].src.indexOf('_on.')>-1){
      el.childNodes[0].src = el.childNodes[0].src.replace('_on.','_off.');
   }else{
      el.childNodes[0].src = el.childNodes[0].src.replace('_off.','_on.');
   }
}

function ImgMenu_Preload(arrImgMenu){
   for(i=0; i<arrImgMenu.length; i++){
      s = ImgMenu_DirImg + arrImgMenu[i].nome;
      img = new Image;
      img.src = s;
      ImgMenu_ArrPreload[ImgMenu_ArrPreload.length] = img;

      s = s.replace('_off.','_on.');
      img = new Image;
      img.src = s;
      ImgMenu_ArrPreload[ImgMenu_ArrPreload.length] = img;

      //alert(s);
   }

   return false;
}


//-------------------------------------------------------------------
//
// Funzione per aggiungere un prodotto al carrello
//
function AddToCart( formName, contentId, id) {
   document.forms[formName].content_id.value = contentId;
   document.forms[formName].productId.value = id;

   document.forms[formName].submit(); 
   return false;
}





//-------------------------------------------------------------------
//
// Decriptazione email address
//
function NoSpamEmail(link){

   if(typeof(WP_NSC) == 'undefined' || typeof(WP_NSS) == 'undefined') return;

   // This is the decoding key for all NoSpamEmailHyperlink_FieldNames objects
   var ky = WP_NSC;

   // Store the innerHTML so that it doesn't get
   // distorted when updating the href later
   var storeText = link.innerHTML;

   // Initialize variables
   var baseNum = parseInt(WP_NSS);
   var atSym = link.href.indexOf("@");
   if (atSym == -1) atSym = 0;
   var dotidx = link.href.indexOf(".", atSym);
   if (dotidx == -1) dotidx = link.href.length;
   var scramble = link.href.substring(7, dotidx); // toglie il mailto
   var unscramble = "";
   var su = 1;


   // Go through the scrambled section of the address
   for (i=0; i < scramble.length; i++){
         // Find each character in the scramble key string
         var ch = scramble.substring(i,i + 1);
         var idx = ky.indexOf(ch);

         // If it isn't there then add the character
         // directly to the unscrambled email address
         if (idx < 0){
               unscramble = unscramble + ch;
               continue;
         }

         // Decode the character
         idx -= (su ? -baseNum : baseNum);
         baseNum -= (su ? -i : i);
         while (idx < 0) idx += ky.length;
         idx %= ky.length;

         // ... and add it to the unscrambled email address
         unscramble = unscramble + ky.substring(idx,idx + 1);
         su = !su;
   }

   // Adjust the href property of the link
   var emAdd = unscramble + link.href.substring(dotidx, link.href.length + 1);
   link.href = "mailto:" + emAdd;

   // If the scrambled email address is also in the text
   // of the hyperlink, replace it
   var findEm = storeText.indexOf(scramble);
   while (findEm > -1){
         storeText = storeText.substring(0, findEm) + emAdd +
               storeText.substring(findEm + emAdd.length, storeText.length);
         findEm = storeText.indexOf(scramble);
   }

   link.innerHTML = storeText;
}
