  
//funzione per il blink del testo
(function($) {
  //
  // plugin definition
  //
	$.fn.cyclicFade = function(options)
	{
		var opts = $.extend({}, $.fn.cyclicFade.defaults, options);
		return this.each(function() {
			$.fn.cyclicFade.doCycle(this,1,opts.repeat,opts.params,0);
		});
	};
	
	$.fn.cyclicFade.defaults = {
		repeat: 0,
		params: [{fadeout:100, stayout:300, opout:0, fadein:100, stayin:300, opin:1.0}]
	};
	
	// this function is used internally
	$.fn.cyclicFade.doCycle = function(obj,start,finish,paramsList,paramsPos) {
		if (paramsPos >= paramsList.length) {
			paramsPos = 0;
		}
		// important: params must be a local variable (var) otherwise it gets overwritten by other
		// calls to doCycle
		var params = paramsList[paramsPos];
		$(obj).fadeTo(params.fadeout, params.opout, function() {
			setTimeout(function() {
				$(obj).fadeTo(params.fadein, params.opin, function() {
					setTimeout(function(){
						if(start!=finish) {
							// increment start only if it is bounded
							if (start<finish) {
								start++;
							}
							$.fn.cyclicFade.doCycle(obj,start,finish,paramsList,paramsPos+1);
						}
					}, params.stayin)
				})
			}, params.stayout)
		});	
	};
	
})(jQuery); 


//funzione per il preload delle immagini
(function($) {
  var cache = [];
  $.caricaImmagini = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery);
/////////////////funzione jquery per menu al right click
(function($){var menu,shadow,trigger,content,hash,currentTarget;var defaults={menuStyle:{listStyle:'none',padding:'1px',margin:'0px',backgroundColor:'#fff',border:'1px solid #999',width:'100px'},itemStyle:{margin:'0px',color:'#000',display:'block',cursor:'default',padding:'3px',border:'1px solid #fff',backgroundColor:'transparent'},itemHoverStyle:{border:'1px solid #0a246a',backgroundColor:'#b6bdd2'},eventPosX:'pageX',eventPosY:'pageY',shadow:true,onContextMenu:null,onShowMenu:null};$.fn.contextMenu=function(id,options){if(!menu){menu=$('<div id="jqContextMenu"></div>').hide().css({position:'absolute',zIndex:'500'}).appendTo('body').bind('click',function(e){e.stopPropagation()})}if(!shadow){shadow=$('<div></div>').css({backgroundColor:'#000',position:'absolute',opacity:0.2,zIndex:499}).appendTo('body').hide()}hash=hash||[];hash.push({id:id,menuStyle:$.extend({},defaults.menuStyle,options.menuStyle||{}),itemStyle:$.extend({},defaults.itemStyle,options.itemStyle||{}),itemHoverStyle:$.extend({},defaults.itemHoverStyle,options.itemHoverStyle||{}),bindings:options.bindings||{},shadow:options.shadow||options.shadow===false?options.shadow:defaults.shadow,onContextMenu:options.onContextMenu||defaults.onContextMenu,onShowMenu:options.onShowMenu||defaults.onShowMenu,eventPosX:options.eventPosX||defaults.eventPosX,eventPosY:options.eventPosY||defaults.eventPosY});var index=hash.length-1;$(this).bind('contextmenu',function(e){var bShowContext=(!!hash[index].onContextMenu)?hash[index].onContextMenu(e):true;if(bShowContext)display(index,this,e,options);return false});return this};function display(index,trigger,e,options){var cur=hash[index];content=$('#'+cur.id).find('ul:first').clone(true);content.css(cur.menuStyle).find('li').css(cur.itemStyle).hover(function(){$(this).css(cur.itemHoverStyle)},function(){$(this).css(cur.itemStyle)}).find('img').css({verticalAlign:'middle',paddingRight:'2px'});menu.html(content);if(!!cur.onShowMenu)menu=cur.onShowMenu(e,menu);$.each(cur.bindings,function(id,func){$('#'+id,menu).bind('click',function(e){hide();func(trigger,currentTarget)})});menu.css({'left':e[cur.eventPosX],'top':e[cur.eventPosY]}).show();if(cur.shadow)shadow.css({width:menu.width(),height:menu.height(),left:e.pageX+2,top:e.pageY+2}).show();$(document).one('click',hide)}function hide(){menu.hide();shadow.hide()}$.contextMenu={defaults:function(userDefaults){$.each(userDefaults,function(i,val){if(typeof val=='object'&&defaults[i]){$.extend(defaults[i],val)}else defaults[i]=val})}}})(jQuery);$(function(){$('div.contextMenu').hide()});



///////////////funzione per aggiornamento spedizione via ajax
 function fct_aggiorna_spedizione(id_pagamento)
				{
				var http7 = new XMLHttpRequest();
var url = "satelliti/operazioni_ajax.php";
var params = "note_finali="+encodeURIComponent(document.getElementById('note_finali').value)+
"&carrello="+$('#carrello').val()+
"&utente="+$('#utente').val()+
"&aggiorna_spedizione="+$('#aggiorna_spedizione').val();
http7.open("POST", url, true);
http7.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http7.setRequestHeader("Content-length", params.length);
http7.setRequestHeader("Connection", "close");
http7.onreadystatechange = function() {//chiama funzione quando lo stato cambia
	if(http7.readyState == 4 && http7.status == 200) {
		risult = http7.responseText;
		valori = risult.split("[METODI]");
		document.getElementById("descrizione_spedizione").innerHTML = valori[2];
        $('#div_maggiorazione_spedizione').html(valori[3]);
		metodi = valori[1].split("[]");

		 var options = "";
      for (var i = 0; i < metodi.length-1; i++) {
		  met = metodi[i].split("|");
       if (met[2] != "")  options += '<option value="' + met[2] + '">' + met[0] + '</option>';
      }
	  $("#aggiorna_pagamento").children().remove();
     $("#aggiorna_pagamento").html(options);
     if (id_pagamento != "") $('#aggiorna_pagamento').val(id_pagamento);
     fct_aggiorna_tutto("no");
     

}
}
http7.send(params);	
				}
                
                ///////////////////funzione ajax per aggiornare il pagamento
                function fct_aggiorna_pagamento()
				{
				var http7 = new XMLHttpRequest();
var url = "satelliti/operazioni_ajax.php";
var params = "note_finali="+encodeURIComponent(document.getElementById('note_finali').value)+
"&carrello="+$('#carrello').val()+
"&utente="+$('#utente').val()+
"&aggiorna_pagamento="+$('#aggiorna_pagamento').val();
http7.open("POST", url, true);
http7.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http7.setRequestHeader("Content-length", params.length);
http7.setRequestHeader("Connection", "close");
http7.onreadystatechange = function() {//chiama funzione quando lo stato cambia
	if(http7.readyState == 4 && http7.status == 200) {
		risult = http7.responseText;
		valori = risult.split("[METODI]");
		document.getElementById("descrizione_pagamento").innerHTML = valori[2];
		 $('#div_maggiorazione_pagamento').html(valori[1]);
         metodi = valori[1].split("[]");
       
        //////////aggiorniamo i totali
        ////alla maggiorazione di spedizione o pagamento, non applichiamo sconti
        fct_aggiorna_tutto("no");

}
}
http7.send(params);	
				}
                
                
                 ///////////////////funzione ajax per aggiornare le quantita
                function fct_aggiorna_quantita(id)
				{
				var http7 = new XMLHttpRequest();
var url = "satelliti/operazioni_ajax.php";
var params = "note_finali="+encodeURIComponent(document.getElementById('note_finali').value)+
"&carrello="+$('#carrello').val()+
"&utente="+$('#utente').val()+
"&aggiorna_quantita="+id+
"&quantita="+$('#quantita_'+id).val();
http7.open("POST", url, true);
http7.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http7.setRequestHeader("Content-length", params.length);
http7.setRequestHeader("Connection", "close");
http7.onreadystatechange = function() {//chiama funzione quando lo stato cambia
	if(http7.readyState == 4 && http7.status == 200) {
		risult = http7.responseText;
//eseguiamo l'aggiornamento di tutti i prezzi e dati dinamici
fct_aggiorna_tutto(id);

}
}
http7.send(params);	
				}
                
                /////funzione per rimuovere prodotti dal carrello
                function fct_rimuovi(id)
                {
                var http7 = new XMLHttpRequest();
var url = "satelliti/operazioni_ajax.php";
var params = "cancella=si&carrello="+$('#carrello').val()+
"&utente="+$('#utente').val()+
"&articolo="+id;
http7.open("POST", url, true);
http7.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http7.setRequestHeader("Content-length", params.length);
http7.setRequestHeader("Connection", "close");
http7.onreadystatechange = function() {//chiama funzione quando lo stato cambia
	if(http7.readyState == 4 && http7.status == 200) {
		risult = http7.responseText;
//rimuoviamo il tr dell'articolo
$('#tr_articolo_'+id).remove();
fct_aggiorna_tutto("");
}
}
http7.send(params);	
                }
                
                
                 /////funzione per lo sconto aggiuntivo
                function fct_sconto()
                {
                var http7 = new XMLHttpRequest();
var url = "satelliti/operazioni_ajax.php";
var params = "carrello="+$('#carrello').val()+
"&utente="+$('#utente').val()+
"&sconto_aggiuntivo="+$('#sconto_aggiuntivo').val();
http7.open("POST", url, true);
http7.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http7.setRequestHeader("Content-length", params.length);
http7.setRequestHeader("Connection", "close");
http7.onreadystatechange = function() {//chiama funzione quando lo stato cambia
	if(http7.readyState == 4 && http7.status == 200) {
		risult = http7.responseText;
         $('#id_sconto_aggiuntivo').html($('#sconto_aggiuntivo').val());
fct_aggiorna_tutto("");
}
}
http7.send(params);	
                }
                
                        /////funzione per inserire il buono
                function fct_inserisci_buono()
                {
                var http7 = new XMLHttpRequest();
var url = "satelliti/operazioni_ajax.php";
var params = "carrello="+$('#carrello').val()+
"&utente="+$('#utente').val()+
"&codice_buono="+$('#codice_buono').val();
http7.open("POST", url, true);
http7.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http7.setRequestHeader("Content-length", params.length);
http7.setRequestHeader("Connection", "close");
http7.onreadystatechange = function() {//chiama funzione quando lo stato cambia
	if(http7.readyState == 4 && http7.status == 200) {
		risult = http7.responseText;
        valori = risult.split("[METODI]");
          //creiamo pure l'input
          if ((valori[1] != undefined)&&(valori[1] != ""))
          {
       linput =  ' <input class="bottone_admin ui-state-default ui-corner-all"  type="submit" name="canc" id="canc" value="Rimuovi" onclick="fct_rimuovi_buono();">';
         $('#id_nome_buono').html(valori[1]+linput);
          $('#id_valore_buono_2').html('Sconto '+valori[2]+' %');
          $('#contenitore_buonissimo').hide();
          }
          fct_aggiorna_tutto("");
          
}
}
http7.send(params);	
                }
                
                
                            /////funzione per rimuovere il buono
                function fct_rimuovi_buono()
                {
                var http7 = new XMLHttpRequest();
var url = "satelliti/operazioni_ajax.php";
var params = "carrello="+$('#carrello').val()+
"&utente="+$('#utente').val()+
"&rimuovi_buono=si";
http7.open("POST", url, true);
http7.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http7.setRequestHeader("Content-length", params.length);
http7.setRequestHeader("Connection", "close");
http7.onreadystatechange = function() {//chiama funzione quando lo stato cambia
	if(http7.readyState == 4 && http7.status == 200) {
		risult = http7.responseText;
         $('#id_sconto_aggiuntivo').html($('#sconto_aggiuntivo').val());
         $('#id_nome_buono').html("");
         $('#rimuovi_buono').remove();
         $('#id_valore_buono').html("");
         $('#id_valore_buono_2').html("");
         $('#contenitore_buonissimo').show();
         fct_aggiorna_tutto("");
}
}
http7.send(params);	
                }
                
                                         /////funzione per aggiornare tutto
                function fct_aggiorna_tutto(id)
                {
                var http7 = new XMLHttpRequest();
var url = "satelliti/operazioni_ajax.php";
var params = "carrello="+$('#carrello').val()+
"&utente="+$('#utente').val()+
"&id_articolo="+id+
"&calcola_tutto=si";
http7.open("POST", url, true);
http7.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http7.setRequestHeader("Content-length", params.length);
http7.setRequestHeader("Connection", "close");
http7.onreadystatechange = function() {//chiama funzione quando lo stato cambia
	if(http7.readyState == 4 && http7.status == 200) {
		risult = http7.responseText;
        valori = risult.split("[RISULTATO]");
        if (id != "") articolo = id;
         $('#div_prezzo_singolo_'+id).html(valori[0]);
          $('#div_prezzo_totale_'+id).html(valori[1]);
           $('#div_quantita_tot').html(valori[2]);
            $('#div_prezzo_singolo_tot').html(valori[3]);
             $('#div_prezzo_totale_tot').html(valori[4]);
              $('#div_prezzo_singolo_tot_iva').html(valori[5]);
             $('#prezzo_totale_tot_iva').html(valori[6]);
             $('#div_peso').html(valori[7]);
             
             //togliamo opzioni dove il peso è minore, e richiamiamo fct_aggiorna_spedizione
             metodi = valori[8].split("[]");
       var options = "";
      for (var i = 0; i < metodi.length-1; i++) {
		  met = metodi[i].split("|");
      selezione_spedizione = $("#aggiorna_spedizione").val();
          if (met[2] == selezione_spedizione)
          {
          descrizione = met[1];
          prezzo = met[3];
          }
       if (met[2] != "")  options += '<option value="' + met[2] + '">' + met[0] + '</option>';
      }
      //prendiamo in carico cio che era selezionato prima e lo riselezioniamo
	  $("#aggiorna_spedizione").children().remove();
     $("#aggiorna_spedizione").html(options);
      $('#aggiorna_spedizione').val(selezione_spedizione);
      document.getElementById("descrizione_spedizione").innerHTML = descrizione;
       document.getElementById("div_costo_spedizione").innerHTML = prezzo;
        $('#div_maggiorazione_spedizione').html(valori[3]);
    if (id != "no")
    {
    selezione_pagamento = $("#aggiorna_pagamento").val();
    fct_aggiorna_spedizione(selezione_pagamento);
    }
   $('#attendi').hide();
             
}
}
http7.send(params);	
                }
                
                
                

function testo_d(nome)
{
	document.getElementById("descric").innerHTML = '<i>'+nome+'</i>';
}

function colli(id)
{
	colli = 'colli'+id;
	collino = document.getElementById(colli).value;
var http7 = new XMLHttpRequest();
var url = "gestione_ordini.php";
var params = "colli="+encodeURIComponent(collino)+"&id="+id+"";
http7.open("POST", url, true);
http7.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http7.setRequestHeader("Content-length", params.length);
http7.setRequestHeader("Connection", "close");
http7.onreadystatechange = function() {//chiama funzione quando lo stato cambia
	if(http7.readyState == 4 && http7.status == 200) {
			$.jGrowl("Il salvataggio Ã¨ avvenuto con successo.", { life: 3000 });
	}
}
http7.send(params);		
}
////////////////fine colli
function n_fattura(id)
{
	colli = 'n_fattura'+id;
	collino = document.getElementById(colli).value;
var http7 = new XMLHttpRequest();
var url = "gestione_ordini.php";
var params = "n_fattura="+encodeURIComponent(collino)+"&id="+id+"";
http7.open("POST", url, true);
http7.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http7.setRequestHeader("Content-length", params.length);
http7.setRequestHeader("Connection", "close");
http7.onreadystatechange = function() {//chiama funzione quando lo stato cambia
	if(http7.readyState == 4 && http7.status == 200) {
			$.jGrowl("Il salvataggio Ã¨ avvenuto con successo.", { life: 3000 });
			
	}
}
http7.send(params);		
}
////////////////fine fattura_n
function cambia_cliente(id)
{
	n_ordine = id;
	cliente = document.getElementById('cliente_ordine'+id).value;
var http7 = new XMLHttpRequest();
var url = "gestione_ordini.php";
var params = "n_ordine="+n_ordine+"&cliente="+cliente+"";
http7.open("POST", url, true);
http7.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http7.setRequestHeader("Content-length", params.length);
http7.setRequestHeader("Connection", "close");
http7.onreadystatechange = function() {//chiama funzione quando lo stato cambia
	if(http7.readyState == 4 && http7.status == 200) {
    $('#suggestioni'+id).hide();
    $('#cambia_utente'+id).hide();
    $('#nome_cliente'+id).text(cliente);
			$.jGrowl("Il salvataggio Ã¨ avvenuto con successo.", { life: 3000 });
			
	}
}
http7.send(params);		
}
////////////////fine fattura_n

function data_fattura(id)
{
	colli = 'datafattura'+id;
	collino = document.getElementById(colli).value;
var http7 = new XMLHttpRequest();
var url = "gestione_ordini.php";
var params = "data_fattura="+encodeURIComponent(collino)+"&id="+id+"";
http7.open("POST", url, true);
http7.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http7.setRequestHeader("Content-length", params.length);
http7.setRequestHeader("Connection", "close");
http7.onreadystatechange = function() {//chiama funzione quando lo stato cambia
	if(http7.readyState == 4 && http7.status == 200) {
			$.jGrowl("Il salvataggio Ã¨ avvenuto con successo.", { life: 3000 });
	}
}
http7.send(params);		
}
////////////////fine fattura_n
function aspetto(id)
{
	aspetto = 'aspetto'+id;
	aspettino = document.getElementById(aspetto).value;
var http7 = new XMLHttpRequest();
var url = "gestione_ordini.php";
var params = "aspetto="+encodeURIComponent(aspettino)+"&id="+id+"";
http7.open("POST", url, true);
http7.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http7.setRequestHeader("Content-length", params.length);
http7.setRequestHeader("Connection", "close");
http7.onreadystatechange = function() {//chiama funzione quando lo stato cambia
	if(http7.readyState == 4 && http7.status == 200) {
			$.jGrowl("Il salvataggio Ã¨ avvenuto con successo.", { life: 3000 });
	}
}
http7.send(params);		
}

function trackingy(id)
{
	tracking = 'codice_tracking'+id;
	trakino = document.getElementById(tracking).value;
var http7 = new XMLHttpRequest();
var url = "gestione_ordini.php";
var params = "tracking="+encodeURIComponent(trakino)+"&id="+id+"&trackingo=si";
http7.open("POST", url, true);
http7.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http7.setRequestHeader("Content-length", params.length);
http7.setRequestHeader("Connection", "close");
http7.onreadystatechange = function() {//chiama funzione quando lo stato cambia
	if(http7.readyState == 4 && http7.status == 200) {
			$.jGrowl("Il salvataggio Ã¨ avvenuto con successo.", { life: 3000 });
	}
}
http7.send(params);		
}
////////////////fine colli






function paga(id)
{
	paghi = 'pagato'+id;
	if (document.getElementById(paghi).checked == true)//se il click su pagato è true allora aggiorniamo il db con valore positivo
	{
		pago = "1";
	}
	else //altrimenti negativo
	{
		pago = "0";
	}
	
	var http7 = new XMLHttpRequest();
var url = "gestione_ordini.php";
var params = "pagato="+encodeURIComponent(pago)+"&id="+id+"";
http7.open("POST", url, true);
http7.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http7.setRequestHeader("Content-length", params.length);
http7.setRequestHeader("Connection", "close");
http7.onreadystatechange = function() {//chiama funzione quando lo stato cambia
	if(http7.readyState == 4 && http7.status == 200) {
			$.jGrowl("Il salvataggio Ã¨ avvenuto con successo.", { life: 3000 });
	}
}
http7.send(params);
	
	
}
////////////////fine pagato

function bookmarksite(title,url){
if (window.sidebar) // firefox
	window.sidebar.addPanel(title, url, "");
else if(window.opera && window.print){ // opera
	var elem = document.createElement('a');
	elem.setAttribute('href',url);
	elem.setAttribute('title',title);
	elem.setAttribute('rel','sidebar');
	elem.click();
} 
else if(document.all)// ie
	window.external.AddFavorite(url, title);
}




function GetXmlHttpObject(handler)
{
var objXMLHttp=null
if (window.XMLHttpRequest)
{
objXMLHttp=new XMLHttpRequest()
}
else if (window.ActiveXObject)
{
objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
return objXMLHttp
}

function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("txtResult").innerHTML= 'ciao';
}
else {
//alert(xmlHttp.status);
}
}

// Will populate data based on input
function htmlData(url, qStr)
{
	
var http2 = new XMLHttpRequest();
var url = "satelliti/popola.php";
var params = qStr;
http2.open("GET", url+"?"+params, true);

http2.onreadystatechange = function() {//Call a function when the state changes.
	if(http2.readyState == 4 && http2.status == 200) {
	
risult = http2.responseText;

   document.getElementById('txtResult').innerHTML = risult;
  // alert(nomiamo);

	}
}
http2.send(null);
	
}

function CalcolaCodiceFiscale()
	{
	document.subform.codice_fiscale.value = "Codice Fiscale non Presente";
	with (document.subform)
		 {
		 Cognome=cognome.value;
		 Nome=nome.value
		 GiornoNascita=giorno.value;
		 MeseNascita=mese.value;
		 AnnoNascita=anno.value;
 		 Sesso=sesso.options[sesso.selectedIndex].value;
		Comune=comune.value;
		 }
	
   if (Cognome != "" && Nome != "" && Comune != "")
   {
      ComuneCalcolato=Comune;
      rc = CalcolaCognome(Cognome);
	  rn = CalcolaNome(Nome)
	  rN = CalcolaNascita(GiornoNascita, MeseNascita, AnnoNascita, Sesso);

      var cf = rc+" "+rn+" "+rN+" "+ComuneCalcolato+" ";

      cf += CalcolaK(rc+rn+rN+ComuneCalcolato);
      if (ComuneCalcolato != -1)
		  document.subform.codice_fiscale.value = cf;
		else
		  document.subform.codice_fiscale.value = "";
   }
}

function CalcolaCognome(Cognome)
{
   var code = "";
   code = GetConsonanti(Cognome);
   if (code.length >= 3)
      code = code.substring(0, 3);
   else
   {
      code += GetVocali(Cognome).substring(0, 3 - code.length)
      if (code.length < 3)
         for (i = code.length; i < 3; i++)
            code += "X";
   }
   return code;
}

function CalcolaNome(Nome)
{
   var code = "";
   cons = GetConsonanti(Nome);
   if (cons.length > 3)
      code = cons.substring(0, 1) + cons.substring(2, 3) + cons.substring(3, 4);
   else if (cons.length == 3)
      code = cons;
   else
   {
      code = cons + GetVocali(Nome).substring(0, 3 - cons.length);
      if (code.length < 3)
         for (i = code.length; i < 3; i++)
            code += "X";
   }
   return code;
}

function GetConsonanti(Stringa)
{
   var cns = "";
   for (i = 0; i < Stringa.length; i++)
      if (consonanti.indexOf(Stringa.substring(i, i + 1)) != -1)
         cns += Stringa.substring(i, i + 1);
   return cns.toUpperCase();
}

function GetVocali(Stringa)
{
   var voc = "";
   for (i = 0; i < Stringa.length; i++)
      if (consonanti.indexOf(Stringa.substring(i, i + 1)) == -1 && Stringa.substring(i, i + 1) != " ")
         voc += Stringa.substring(i, i + 1);
   return voc.toUpperCase();
}

function CalcolaNascita(Giorno, Mese, Anno, Sesso)
{
   var code = "";
   code += Anno.substring(2, 4) + Mese;
   if (Sesso == "M")
      code += Giorno;
   else
      code += parseInt(40, 10) + parseInt(Giorno, 10);
   return code;
}

function CalcolaComune(Comune)
{
flag = document.subform.comune.value 
}

function CalcolaK(Stringa)
{
   var somma = 0, k;
   var arrPari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
   var arrDispari = new Array(
      Array(0,1),
      Array(1,0),
      Array(2,5),
      Array(3,7),
      Array(4,9),
      Array(5,13),
      Array(6,15),
      Array(7,17),
      Array(8,19),
      Array(9,21),
      Array("A",1),
      Array("B",0),
      Array("C",5),
      Array("D",7),
      Array("E",9),
      Array("F",13),
      Array("G",15),
      Array("H",17),
      Array("I",19),
      Array("J",21),
      Array("K",2),
      Array("L",4),
      Array("M",18),
      Array("N",20),
      Array("O",11),
      Array("P",3),
      Array("Q",6),
      Array("R",8),
      Array("S",12),
      Array("T",14),
      Array("U",16),
      Array("V",10),
      Array("W",22),
      Array("X",25),
      Array("Y",24),
      Array("Z",23)
   );
   for (i = 0; i < Stringa.length; i += 2)
   {
      for (j = 0; j < arrDispari.length; j++)
      {
         if (Stringa.substring(i, i + 1).toUpperCase() == arrDispari[j][0])
         {
            somma += parseInt(arrDispari[j][1], 10);
            break;
         }
      }
   }
   for (i = 1; i < Stringa.length; i += 2)
   {
      if (isNaN(Stringa.substring(i, i + 1)))
         somma += parseInt(arrPari.indexOf(Stringa.substring(i, i + 1)), 10);
      else
         somma += parseInt(Stringa.substring(i, i + 1), 10);
   }
   k = somma % 26;
   k = arrPari.charAt(k);
   return k;
}



function aggiornaattendere (n)
{
attendere.style.visibility="hidden"
}


function validazione_spedizione(){
	if (document.pagamento.aggiorna_pagamento.value == "")
	{
		document.getElementById("spedizionediv").innerHTML = "<span class='rosso_strong_undici'>Devi selezionare un metodo di pagamento e spedizione!</span>";
	//alert("Devi selezionare un metodo di pagamento e spedizione!");
	return false;
	}
	if (document.getElementById('username').value == "")
	{
		document.getElementById("usdiv").innerHTML = "<span class='rosso_strong_undici'>Devi inserire lâ€™Username!</div>";
//alert("Devi inserire l'Username!");
	return false;
	}
	if (document.getElementById("password").value == "")
	{
		document.getElementById("padiv").innerHTML = "<span class='rosso_strong_undici'>Devi inserire una Password!</span>";

//alert("Devi inserire una password!");
	return false;
	}
}


function addText(instext,id) {
    var mess = document.getElementById(id);
        //IE support
        if (document.selection) {
            document.getElementById(id).focus();
            sel = document.selection.createRange();
            sel.text = instext;
            document.getElementById(id).focus();
        }
        //MOZILLA/NETSCAPE support
        else if (document.getElementById(id).selectionStart || document.getElementById(id).selectionStart == "0") {
            var startPos = document.getElementById(id).selectionStart;
            var endPos = document.getElementById(id).selectionEnd;
            var chaine = document.getElementById(id).value;

            document.getElementById(id).value = chaine.substring(0, startPos) + instext + chaine.substring(endPos, chaine.length);

            document.getElementById(id).selectionStart = startPos + instext.length;
            document.getElementById(id).selectionEnd = endPos + instext.length;
           document.getElementById(id).focus();
        } else {
           document.getElementById(id).value += instext;
            document.getElementById(id).focus();
        }
    }




function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}



	function NascondiTitolo(ID){
			document.getElementById(ID).style.display='none';
		}
		
		
	
		function ShowNascondiTitolo(ID){
			if(document.getElementById(ID).style.display==''){
				NascondiTitolo(ID);
			}else{
			for (i=1;i<=6;i++){
	
				NascondiTitolo("titolo"+i);
			}
		
				MostraTitolo(ID);
			}
		}
		
		function MostraTitolo(ID){
		
			document.getElementById(ID).style.display='';
		}
		
	
	

		
var horizontal_offset="9px" //horizontal offset of hint box from anchor link

/////No further editting needed

var vertical_offset="0" //horizontal offset of hint box from anchor link. No need to change.
var ie=document.all
var ns6=document.getElementById&&!document.all

function getposOffset(what, offsettype){
var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
var parentEl=what.offsetParent;
while (parentEl!=null){
totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
parentEl=parentEl.offsetParent;
}
return totaloffset;
}

function iecompattest(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function clearbrowseredge(obj, whichedge){
var edgeoffset=(whichedge=="rightedge")? parseInt(horizontal_offset)*-1 : parseInt(vertical_offset)*-1
if (whichedge=="rightedge"){
var windowedge=ie && !window.opera? iecompattest().scrollLeft+iecompattest().clientWidth-30 : window.pageXOffset+window.innerWidth-40
dropmenuobj.contentmeasure=dropmenuobj.offsetWidth
if (windowedge-dropmenuobj.x < dropmenuobj.contentmeasure)
edgeoffset=dropmenuobj.contentmeasure+obj.offsetWidth+parseInt(horizontal_offset)
}
else{
var windowedge=ie && !window.opera? iecompattest().scrollTop+iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
dropmenuobj.contentmeasure=dropmenuobj.offsetHeight
if (windowedge-dropmenuobj.y < dropmenuobj.contentmeasure)
edgeoffset=dropmenuobj.contentmeasure-obj.offsetHeight
}
return edgeoffset
}

function showhint(menucontents, obj, e, tipwidth){
if ((ie||ns6) && document.getElementById("hintbox")){
dropmenuobj=document.getElementById("hintbox")
dropmenuobj.innerHTML=menucontents
dropmenuobj.style.left=dropmenuobj.style.top=-500
if (tipwidth!=""){
dropmenuobj.widthobj=dropmenuobj.style
dropmenuobj.widthobj.width=tipwidth
}
dropmenuobj.x=getposOffset(obj, "left")
dropmenuobj.y=getposOffset(obj, "top")
dropmenuobj.style.left=dropmenuobj.x-clearbrowseredge(obj, "rightedge")+obj.offsetWidth+"px"
dropmenuobj.style.top=dropmenuobj.y-clearbrowseredge(obj, "bottomedge")+"px"
dropmenuobj.style.visibility="visible"
obj.onmouseout=hidetip
}
}

function hidetip(e){
dropmenuobj.style.visibility="hidden"
dropmenuobj.style.left="-500px"
}

function createhintbox(){
var divblock=document.createElement("div")
divblock.setAttribute("id", "hintbox")
document.body.appendChild(divblock)
}

if (window.addEventListener)
window.addEventListener("load", createhintbox, false)
else if (window.attachEvent)
window.attachEvent("onload", createhintbox)
else if (document.getElementById)
window.onload=createhintbox


	function HideDiv(ID){
			document.getElementById(ID).style.display='none';
		}
		
		function ShowDiv(ID){
			document.getElementById(ID).style.display='';
		}
		
		function ShowHideDiv(ID,naz){
			
			
			if(document.getElementById(ID).style.display==''){
				HideDiv(ID);
			}else{
				HideAll("cat",6);
				ShowDiv(ID);
			}
			
			naza = "contenuto_documenti_"+naz;
			xinha_editors = null;
xinha_init    = null;
xinha_config  = null;
xinha_plugins = null;
xinha_init = xinha_init ? xinha_init : function()
{
xinha_editors = xinha_editors ? xinha_editors :
  [
  naza
  ];
  xinha_plugins = xinha_plugins ? xinha_plugins :
  [
   'CharacterMap',
   'ContextMenu',
   'ListType',
   'Stylist',
   'Linker',
   'SuperClean',
   'TableOperations',
   'ExtendedFileManager',
	   'ImageManager'
  ];
  // THIS BIT OF JAVASCRIPT LOADS THE PLUGINS, NO TOUCHING  :)
         if(!Xinha.loadPlugins(xinha_plugins, xinha_init)) return;
xinha_config = xinha_config ? xinha_config() : new Xinha.Config();
xinha_config.pageStyle = "body {font-family: Georgia,'Nimbus Roman No9 L',serif; font-size: 8pt;}";
    xinha_config.pageStyleSheets = [ _editor_url + "examples/full_example.css" ];
xinha_editors   = Xinha.makeEditors(xinha_editors, xinha_config, xinha_plugins);
Xinha.startEditors(xinha_editors);
}
	

		if ((naza == "contenuto_documenti_ita")&&(document.getElementById("premutoita").value != "vero"))
			{
             xinha_init();
			 document.getElementById("premutoita").value = "vero";
		    }//fine premuto
			
			if ((naza == "contenuto_documenti_eng")&&(document.getElementById("premutoeng").value != "vero"))
			{
             xinha_init();
			 document.getElementById("premutoeng").value = "vero";
		    }//fine premuto
			if ((naza == "contenuto_documenti_fra")&&(document.getElementById("premutofra").value != "vero"))
			{
             xinha_init();
			 document.getElementById("premutofra").value = "vero";
		    }//fine premuto
			if ((naza == "contenuto_documenti_spa")&&(document.getElementById("premutospa").value != "vero"))
			{
             xinha_init();
			 document.getElementById("premutospa").value = "vero";
		    }//fine premuto
			if ((naza == "contenuto_documenti_ted")&&(document.getElementById("premutoted").value != "vero"))
			{
             xinha_init();
			 document.getElementById("premutoted").value = "vero";
		    }//fine premuto
			if ((naza == "contenuto_documenti_extra")&&(document.getElementById("premutoextra").value != "vero"))
			{
             xinha_init();
			 document.getElementById("premutoextra").value = "vero";
		    }//fine premuto
			
			
			
		}
		
		function HideAll(prefix,iterations){
			for (i=1;i<=iterations;i++){
				HideDiv(prefix+i);
			}
		}
	



//Browsercheck
n=document.layers
ie=document.all

//Hides the layer onload
function hideIt(){
	if(ie || n){
		document.body.style.overflow='hidden';
		document.body.scrollTop=0;
		if(n) document.attendi.visibility="visible"
		else attendi.style.visibility="visible"
		
	}
}
function showIt(){
		//windowX = (document.documentElement && document.documentElement.clientWidth) || window.innerWidth || self.innerWidth || document.body.clientWidth; 
		//windowY = (document.documentElement && document.documentElement.clientHeight) || window.innerHeight || self.innerHeight || document.body.clientHeight; 
		//scrollX = (document.documentElement && document.documentElement.scrollLeft) || window.pageXOffset || self.pageXOffset || document.body.scrollLeft; 
		//scrollY = (document.documentElement && document.documentElement.scrollTop) || window.pageYOffset || self.pageYOffset || document.body.scrollTop; 
	//if(ie || n){
		//if(n) 
		document.getElementById('attendi').style.display="none";
		//else attendi.style.visibility="hidden"
	//}
}

//per ordinare un'array numerica in modo descrescente
function ordina_decrescente(a, b){ return (b-a); } 




  var stile = "top=10, left=10, width=250, height=200, status=no, menubar=no, toolbar=no scrollbar=no";
     function Popup(apri) {
        window.open(apri, "", stile);
     }

 
 function mostra(id)
 {
	 if (document.getElementById("storico_modifiche"+id).style.display != 'block')
	 {
 document.getElementById("storico_modifiche"+id).style.display='block';

  }
  else
  	 {
 document.getElementById("storico_modifiche"+id).style.display='none';
  }
 
  }
  
  function mostra_stat(id)
 {
	 if (document.getElementById("statistiche"+id).style.display != 'block')
	 {
 document.getElementById("statistiche"+id).style.display='block';

  }
  else
  	 {
 document.getElementById("statistiche"+id).style.display='none';
  }
 
  }
  /////////////////////////
  function mostra_cats(id,idue)
 {
	 if (document.getElementById(id).style.display != 'block')
	 {
 document.getElementById(id).style.display='block';
  document.getElementById(idue).style.display='none';
  }
  }
  
  function svuota_cats()
{
document.getElementById("ins_cat").reset();
}

function mostra_nascondi(id,plus)
 {
	 if (document.getElementById(id).style.display == 'none')
	 {
		if (plus != '') document.getElementById(plus).value = 'si';
 document.getElementById(id).style.display='';

  }
  else
   {
 document.getElementById(id).style.display='none';
  if (plus !='') document.getElementById(plus).value = 'no';
  }
 //alert( document.getElementById(plus).value);
  }

function vedi_nascondi(id)
 {
	 if (document.getElementById(id).style.display == 'none')
	 {
 document.getElementById(id).style.display='';
 }
  else
   {
 document.getElementById(id).style.display='none';
   }
   
  }






 
	
	$(function() {
   $('a.lightbox').lightBox({
	overlayBgColor: '#a70000',
	overlayOpacity: 0.6
   });
});



var opts =
  // horizontal Dock with images expanding downwards in the vertical axis...
{ align: 'top'
  // set the maximum minor axis (vertical) image dimension to 48px
, size: 70
  // add labels..
 ,labels:  'tc' //default
  // swap the GIF extension for PNG extension for the larger image...
, source: function(i){ return this.src.replace(/gif$/,'png'); }
};
$('#menu').jqDock(opts);
jQuery(document).ready(function(){
  jQuery('#menu').jqDock(opts);
});

function togli()///funzione per cancellare vignette al movimento dello scroll
{
                     document.getElementById("zero").style.display='none'; 
					 document.getElementById("uno").style.display='none'; 
					 document.getElementById("due").style.display='none'; 
					 document.getElementById("tre").style.display='none'; 
					 document.getElementById("quattro").style.display='none'; 
					 document.getElementById("cinque").style.display='none';
					 document.getElementById("sei").style.display='none'; 	
					 }
	
		function minimizza()
		{
			
			//callback function to bring a hidden box back
		function callback(){
			setTimeout(function(){
				$("#pannello:hidden").removeAttr('style').hide().fadeIn();
			}, 1000);
		};
		$("#pannello").hide("slide","",500,callback);
		document.getElementById('massimizza').style.display='';
		createCookie('menu_admin','minimizzato',7);
		$("#due").hide();
		$("#tre").hide();
		$("#quattro").hide();
		$("#cinque").hide();
		$("#sei").hide();

		}
			function massimizza()
		{
			//callback function to bring a hidden box back
		function callback(){
			setTimeout(function(){
				$("#pannello:visible").removeAttr('style').hide().fadeOut();
			}, 1000);
		};

			$("#pannello").show('slide','',500,callback);
		//document.getElementById('pannello').style.display='';
		document.getElementById('massimizza').style.display='none';
		createCookie('menu_admin','massimizzato',7);
		}
		function menu_visibile()
		{
		
			var visibile = readCookie('menu_admin');
			
			var visibile = "minimizzato";		if (visibile == "minimizzato")
		{
			document.getElementById('pannello').style.display='none';
		document.getElementById('massimizza').style.display='block';
		}
		else
		{
			document.getElementById('pannello').style.display='';
		document.getElementById('massimizza').style.display='none';
		}
		//alert(visibile);
        		function getObj(objID)
{
    if (document.getElementById) {return document.getElementById(objID);}
    else if (document.all) {return document.all[objID];}
    else if (document.layers) {return document.layers[objID];}
}
			////questo codice mi serve all'avvio per non far visualizzare la tabella del calendario causa BUG
			/*
			e?evt=e:evt=event;
	CSE=evt.target?evt.target:evt.srcElement;
			if (getObj('fuckyou'))getObj('fuckyou').style.display='none';
			*/
			////////////////fine tabella calendario da non visualizzare
		
		}
		
					 function promemoria (id) ////funzione per salvare il promemoria senza refresh della pagina
 {
 var http = new XMLHttpRequest();
var url = id;
var params = "vai=promemoria&id="+eval(id)+"";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
	if(http.readyState == 4 && http.status == 200) {
		document.getElementById("promemory").innerHTML = "Documento aggiunto al Promemoria!";
		}
		}
http.send(params);
}
 function suggerisci (id) ////funzione per salvare il promemoria senza refresh della pagina
 {
document.getElementById("live_help").innerHTML = id;

}

function vignetta(testo,livello)
{
	   document.getElementById("vignetta").style.display = "";
// If it is not IE, we assume that the browser is NS.
var IE = document.all?true:false

// If NS -- that is, !IE -- then set up for mouse capture
if (!IE) document.captureEvents(Event.MOUSEOVER)

// Set-up to use getMouseXY function onMouseMove
document.onmouseover = getMouseXY;
//document.onmouseout = addio;

// Temporary variables to hold mouse x-y pos.s
var tempX = 0
var tempY = 0

// Main function to retrieve mouse x-y pos.s

function getMouseXY(e) {
  if (IE) { // grab the x-y pos.s if browser is IE
    tempX = event.clientX + document.body.scrollLeft
    tempY = event.clientY + document.body.scrollTop
  } else {  // grab the x-y pos.s if browser is NS
    tempX = e.pageX
    tempY = e.pageY
  }  
  // catch possible negative values in NS4
  if (tempX < 0){tempX = 0}
  if (tempY < 0){tempY = 0}  
  // show the position values in the form named Show
  // in the text fields named MouseX and MouseY
 document.getElementById("vignetta").style.left = (tempX-100)+"px";
  document.getElementById("vignetta").style.top = tempY+"px";
  return true
}

  
  su = "../immagini/vignetta_up_inversa.png";
 giu = "../immagini/vignetta_down_inverso.png";
  
document.getElementById("vignetta").innerHTML = '<table valign="bottom"><tr><td><table width="200" border="0" cellspacing="0" cellpadding="0"><tr><td></td><tr><td><img src="'+su+'" id="fuori" width="200" height="42" /></td></tr><tr><td background="../immagini/vignetta_centro_inversa.png"><table width="200" border="0" align="center" cellpadding="0" cellspacing="0"> <tr><td align="center"><strong>'+testo+'</strong></td> </tr></table></td></tr><tr><td><img src="'+giu+'" width="200" height="37" /></td></tr> <tr> <td></td></tr></table></td></tr></table>';

}

function addio()
 {  
document.getElementById("vignetta").style.display = "none";
  }  


  
  function suggestioni_completo(valore,tabella,campo,textbox,div)
 {  
 document.getElementById(div).style.display = "";
var http2 = new XMLHttpRequest();
var url = "satelliti/suggestioni.php";
var params = "key="+valore+"&tab="+tabella+"&campo="+campo+"&textbox="+textbox+"&div="+div;
http2.open("GET", url+"?"+params, true);

http2.onreadystatechange = function() {//Call a function when the state changes.
	if(http2.readyState == 4 && http2.status == 200) {
	
risult = http2.responseText;
document.getElementById(div).innerHTML = "";
document.getElementById(div).innerHTML = risult;
//initializemarquee();

}
}
http2.send(null);
  }  


function ins_ut(utente,textbox,div)
 {  
document.getElementById(textbox).value = utente;
document.getElementById(div).style.display = "none";
  }  



/* VARIABLES YOU COULD MODIFY */
	var boxSizeArray = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10];	// Array indicating how many items there is rooom for in the right column ULs
	
	var arrow_offsetX = -5;	// Offset X - position of small arrow
	var arrow_offsetY = 0;	// Offset Y - position of small arrow
	
	var arrow_offsetX_firefox = -6;	// Firefox - offset X small arrow
	var arrow_offsetY_firefox = -13; // Firefox - offset Y small arrow
	
	var verticalSpaceBetweenListItems = 3;	// Pixels space between one <li> and next	
											// Same value or higher as margin bottom in CSS for #dhtmlgoodies_dragDropContainer ul li,#dragContent li
	
											
	var indicateDestionationByUseOfArrow = true;	// Display arrow to indicate where object will be dropped(false = use rectangle)

	var cloneSourceItems = true;	// Items picked from main container will be cloned(i.e. "copy" instead of "cut").	
	var cloneAllowDuplicates = false;// Allow multiple instances of an item inside a small box(example: drag Student 1 to team A twice
	
	/* END VARIABLES YOU COULD MODIFY */
	
	var dragDropTopContainer = false;
	var dragTimer = -1;
	var dragContentObj = false;
	var contentToBeDragged = false;	// Reference to dragged <li>
	var contentToBeDragged_src = false;	// Reference to parent of <li> before drag started
	var contentToBeDragged_next = false; 	// Reference to next sibling of <li> to be dragged
	var destinationObj = false;	// Reference to <UL> or <LI> where element is dropped.
	var dragDropIndicator = false;	// Reference to small arrow indicating where items will be dropped
	var ulPositionArray = new Array();
	var mouseoverObj = false;	// Reference to highlighted DIV
	
	var MSIE = navigator.userAgent.indexOf('MSIE')>=0?true:false;
	var navigatorVersion = navigator.appVersion.replace(/.*?MSIE (\d\.\d).*/g,'$1')/1;

	
	var indicateDestinationBox = false;
	function getTopPos(inputObj)
	{		
	  var returnValue = inputObj.offsetTop;
	  while((inputObj = inputObj.offsetParent) != null){
	  	if(inputObj.tagName!='HTML')returnValue += inputObj.offsetTop;
	  }
	  return returnValue;
	}
	
	function getLeftPos(inputObj)
	{
	  var returnValue = inputObj.offsetLeft;
	  while((inputObj = inputObj.offsetParent) != null){
	  	if(inputObj.tagName!='HTML')returnValue += inputObj.offsetLeft;
	  }
	  return returnValue;
	}
		
	function cancelEvent()
	{
		return false;
	}
	function initDrag(e)	// Mouse button is pressed down on a LI
	{
		if(document.all)e = event;
		var st = Math.max(document.body.scrollTop,document.documentElement.scrollTop);
		var sl = Math.max(document.body.scrollLeft,document.documentElement.scrollLeft);
		
		dragTimer = 0;
		dragContentObj.style.left = e.clientX + sl + 'px';
		dragContentObj.style.top = e.clientY + st + 'px';
		contentToBeDragged = this;
		contentToBeDragged_src = this.parentNode;
		contentToBeDragged_next = false;
		if(this.nextSibling){
			contentToBeDragged_next = this.nextSibling;
			if(!this.tagName && contentToBeDragged_next.nextSibling)contentToBeDragged_next = contentToBeDragged_next.nextSibling;
		}
		timerDrag();
		return false;
	}
	
	function timerDrag()
	{
		if(dragTimer>=0 && dragTimer<10){
			dragTimer++;
			setTimeout('timerDrag()',10);
			return;
		}
		if(dragTimer==10){
			
			if(cloneSourceItems && contentToBeDragged.parentNode.id=='allItems'){
				newItem = contentToBeDragged.cloneNode(true);
				newItem.onmousedown = contentToBeDragged.onmousedown;
				contentToBeDragged = newItem;
			}
			dragContentObj.style.display='block';
			dragContentObj.appendChild(contentToBeDragged);
		}
	}
	
	function moveDragContent(e)
	{
		if(dragTimer<10){
			if(contentToBeDragged){
				if(contentToBeDragged_next){
					contentToBeDragged_src.insertBefore(contentToBeDragged,contentToBeDragged_next);
				}else{
					contentToBeDragged_src.appendChild(contentToBeDragged);
				}	
			}
			return;
		}
		if(document.all)e = event;
		var st = Math.max(document.body.scrollTop,document.documentElement.scrollTop);
		var sl = Math.max(document.body.scrollLeft,document.documentElement.scrollLeft);
		
		
		dragContentObj.style.left = e.clientX + sl + 'px';
		dragContentObj.style.top = e.clientY + st + 'px';
		
		if(mouseoverObj)mouseoverObj.className='';
		destinationObj = false;
		dragDropIndicator.style.display='none';
		if(indicateDestinationBox)indicateDestinationBox.style.display='none';
		var x = e.clientX + sl;
		var y = e.clientY + st;
		var width = dragContentObj.offsetWidth;
		var height = dragContentObj.offsetHeight;
		
		var tmpOffsetX = arrow_offsetX;
		var tmpOffsetY = arrow_offsetY;
		if(!document.all){
			tmpOffsetX = arrow_offsetX_firefox;
			tmpOffsetY = arrow_offsetY_firefox;
		}

		for(var no=0;no<ulPositionArray.length;no++){
			var ul_leftPos = ulPositionArray[no]['left'];	
			var ul_topPos = ulPositionArray[no]['top'];	
			var ul_height = ulPositionArray[no]['height'];
			var ul_width = ulPositionArray[no]['width'];
			
			if((x+width) > ul_leftPos && x<(ul_leftPos + ul_width) && (y+height)> ul_topPos && y<(ul_topPos + ul_height)){
				var noExisting = ulPositionArray[no]['obj'].getElementsByTagName('LI').length;
				if(indicateDestinationBox && indicateDestinationBox.parentNode==ulPositionArray[no]['obj'])noExisting--;
				if(noExisting<boxSizeArray[no-1] || no==0){
					dragDropIndicator.style.left = ul_leftPos + tmpOffsetX + 'px';
					var subLi = ulPositionArray[no]['obj'].getElementsByTagName('LI');
					
					var clonedItemAllreadyAdded = false;
					if(cloneSourceItems && !cloneAllowDuplicates){
						for(var liIndex=0;liIndex<subLi.length;liIndex++){
							if(contentToBeDragged.id == subLi[liIndex].id)clonedItemAllreadyAdded = true;
						}
						if(clonedItemAllreadyAdded)continue;
					}
					
					for(var liIndex=0;liIndex<subLi.length;liIndex++){
						var tmpTop = getTopPos(subLi[liIndex]);
						if(!indicateDestionationByUseOfArrow){
							if(y<tmpTop){
								destinationObj = subLi[liIndex];
								indicateDestinationBox.style.display='block';
								subLi[liIndex].parentNode.insertBefore(indicateDestinationBox,subLi[liIndex]);
								break;
							}
						}else{							
							if(y<tmpTop){
								destinationObj = subLi[liIndex];
								dragDropIndicator.style.top = tmpTop + tmpOffsetY - Math.round(dragDropIndicator.clientHeight/2) + 'px';
								dragDropIndicator.style.display='block';
								break;
							}	
						}					
					}
					
					if(!indicateDestionationByUseOfArrow){
						if(indicateDestinationBox.style.display=='none'){
							indicateDestinationBox.style.display='block';
							ulPositionArray[no]['obj'].appendChild(indicateDestinationBox);
						}
						
					}else{
						if(subLi.length>0 && dragDropIndicator.style.display=='none'){
							dragDropIndicator.style.top = getTopPos(subLi[subLi.length-1]) + subLi[subLi.length-1].offsetHeight + tmpOffsetY + 'px';
							dragDropIndicator.style.display='block';
						}
						if(subLi.length==0){
							dragDropIndicator.style.top = ul_topPos + arrow_offsetY + 'px'
							dragDropIndicator.style.display='block';
						}
					}
					
					if(!destinationObj)destinationObj = ulPositionArray[no]['obj'];
					mouseoverObj = ulPositionArray[no]['obj'].parentNode;
					mouseoverObj.className='mouseover';
					return;
				}
			}
		}
	}
	
	/* End dragging 
	Put <LI> into a destination or back to where it came from.
	*/	
	function dragDropEnd(e)
	{
		if(dragTimer==-1)return;
		if(dragTimer<10){
			dragTimer = -1;
			return;
		}
		dragTimer = -1;
		if(document.all)e = event;	
		
		
		if(cloneSourceItems && (!destinationObj || (destinationObj && (destinationObj.id=='allItems' || destinationObj.parentNode.id=='allItems')))){
			contentToBeDragged.parentNode.removeChild(contentToBeDragged);
		}else{	
			
			if(destinationObj){
				if(destinationObj.tagName=='UL'){
					destinationObj.appendChild(contentToBeDragged);
				}else{
					destinationObj.parentNode.insertBefore(contentToBeDragged,destinationObj);
				}
				mouseoverObj.className='';
				destinationObj = false;

				dragDropIndicator.style.display='none';
				if(indicateDestinationBox){
					indicateDestinationBox.style.display='none';
					document.body.appendChild(indicateDestinationBox);
				}
				contentToBeDragged = false;
				return;
			}		
			if(contentToBeDragged_next){
				contentToBeDragged_src.insertBefore(contentToBeDragged,contentToBeDragged_next);
			}else{
				contentToBeDragged_src.appendChild(contentToBeDragged);
			}
		}
		contentToBeDragged = false;
		dragDropIndicator.style.display='none';
		if(indicateDestinationBox){
			indicateDestinationBox.style.display='none';
			document.body.appendChild(indicateDestinationBox);
			
		}
		mouseoverObj = false;
		
	}
	
	/* 
	Preparing data to be saved 
	*/
	function saveDragDropNodes()
	{
		var saveString = "";
		var uls = dragDropTopContainer.getElementsByTagName('UL');
		for(var no=0;no<uls.length;no++){	// LOoping through all <ul>
			var lis = uls[no].getElementsByTagName('LI');
			for(var no2=0;no2<lis.length;no2++){
				if(saveString.length>0)saveString = saveString + ";";
				saveString = saveString + uls[no].id + '|' + lis[no2].id;
				document.getElementById("valori").value = saveString;
			}	
		}		
		
		
		document.getElementById('invia').submit();
	}
	
	function initDragDropScript()
	{
		dragContentObj = document.getElementById('dragContent');
		dragDropIndicator = document.getElementById('dragDropIndicator');
		dragDropTopContainer = document.getElementById('dhtmlgoodies_dragDropContainer');
		document.documentElement.onselectstart = cancelEvent;;
		var listItems = dragDropTopContainer.getElementsByTagName('LI');	// Get array containing all <LI>
		var itemHeight = false;
		for(var no=0;no<listItems.length;no++){
			listItems[no].onmousedown = initDrag;
			listItems[no].onselectstart = cancelEvent;
			if(!itemHeight)itemHeight = listItems[no].offsetHeight;
			if(MSIE && navigatorVersion/1<6){
				listItems[no].style.cursor='hand';
			}			
		}
		
		var mainContainer = document.getElementById('dhtmlgoodies_mainContainer');
		var uls = mainContainer.getElementsByTagName('UL');
		itemHeight = itemHeight + verticalSpaceBetweenListItems;
		for(var no=0;no<uls.length;no++){
			uls[no].style.height = itemHeight * boxSizeArray[no]  + 'px';
		}
		
		var leftContainer = document.getElementById('dhtmlgoodies_listOfItems');
		var itemBox = leftContainer.getElementsByTagName('UL')[0];
		
		document.documentElement.onmousemove = moveDragContent;	// Mouse move event - moving draggable div
		document.documentElement.onmouseup = dragDropEnd;	// Mouse move event - moving draggable div
		
		var ulArray = dragDropTopContainer.getElementsByTagName('UL');
		for(var no=0;no<ulArray.length;no++){
			ulPositionArray[no] = new Array();
			ulPositionArray[no]['left'] = getLeftPos(ulArray[no]);	
			ulPositionArray[no]['top'] = getTopPos(ulArray[no]);	
			ulPositionArray[no]['width'] = ulArray[no].offsetWidth;
			ulPositionArray[no]['height'] = ulArray[no].clientHeight;
			ulPositionArray[no]['obj'] = ulArray[no];
		}
		
		if(!indicateDestionationByUseOfArrow){
			indicateDestinationBox = document.createElement('LI');
			indicateDestinationBox.id = 'indicateDestination';
			indicateDestinationBox.style.display='none';
			document.body.appendChild(indicateDestinationBox);

			
		}
	}
	



ver = new Array();
arr_opt = new Array();
function verif(ver,formy)
{
if (formy == "scrivici")
{
user_esistente = "no";
}
w=0;
if ($('#registrati_username').length != 0)	{
	if (document.getElementById("registrati_username").value != "")
{
var esiste = new XMLHttpRequest();
var url = "go.php?act=profilo";
user = document.getElementById("registrati_username").value;
var params = 'username_esiste='+user+'';
esiste.open("GET", url+"&"+params, true);
esiste.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
esiste.setRequestHeader("Content-length", params.length);
esiste.setRequestHeader("Connection", "close");
esiste.onreadystatechange = function() {
	if(esiste.readyState == 4 && esiste.status == 200) {
	risult = esiste.responseText;
	risulti = risult.split("SEPARATOINCASA");
	//alert(risulti[1]);

	if (risulti[1] == "si")//se lusername è già  esistente, comunichiamolo
	{
	document.getElementById("usernamediv").innerHTML = "<span class='rosso_strong_undici'>Username giÃ  esistente, utilizzane un altro!</span>";
		//alert(user);
		w = 100;
		}
		else
		{
        w = 0;
        user_esistente = "no";
		document.getElementById("usernamediv").innerHTML = "Nome utente disponibile";
			}
            } //chiusura 
			} //chiusura 
esiste.send(null);			
}
}//fine se esiste registrati_username
if ($('#nuovo_indirizzo_presente').length != 0)
{

if (document.getElementById("aggiorna_spedizione").value == '')
{
document.getElementById("divspedizione").innerHTML = "<span class=\'rosso_strong_undici\'>Hai dimenticato di selezionare un metodo di spedizione!</span>";
w++;
}
else
{
document.getElementById("divspedizione").innerHTML = "";
}
if (document.getElementById("aggiorna_pagamento").value == '')
{
document.getElementById("divpagamento").innerHTML = "<span class=\'rosso_strong_undici\'>Hai dimenticato di selezionare un metodo di pagamento</span>";
w++;
}
else
{
document.getElementById("divpagamento").innerHTML = "";
}

if (document.getElementById("nuovo_indirizzo_presente").value == "no")
{

if 
((document.getElementById("tipo_fatturazione").value == '')&&(document.getElementById("nuovo_indirizzo_presente").value == 'no'))
{
document.getElementById("divfatturazione").innerHTML = "<span class=\'rosso_strong_undici\'>Hai dimenticato di selezionare un indirizzo di fatturazione!</span>";
w++;
}
else
{
document.getElementById("divfatturazione").innerHTML = "";
}

if (document.getElementById("tipo_indirizzo").value == '')
{
document.getElementById("divindirizzo").innerHTML = "<span class=\'rosso_strong_undici\'>Hai dimenticato di selezionare un metodo di spedizione!</span>";
w++;
}
else
{
document.getElementById("divindirizzo").innerHTML = "";
}

user_esistente = "no";

}//fine se non c'è un nuovo indirizzo
user_esistente = "no";
}//fine nuovo indirizzo diverso da undefined

if ($('#registrati_username').length != 0)
{
if ((document.getElementById("registrati_password").value == '') && (document.getElementById("registrati_username").value != ''))
{
document.getElementById("divpassword").innerHTML = "<span class=\'rosso_strong_undici\'>Devi inserire una password se hai scelto di utilizzare un nome utente !</span>";
w++;
}
else
{
user_esistente = "no";
document.getElementById("divpassword").innerHTML = "";
}
}//fine se siamo sul lato registrazione utente
for (i=0;i<ver.length;i++)
{
	
	//alert(ver[i]);
if (document.getElementById(ver[i]).value == "")
    {
		w++;
	//alert("il campo "+ver[i]+" e vuoto");
	document.getElementById(ver[i]+"div").innerHTML = "<span class=\'rosso_strong_undici\'>Hai dimenticato di compilare questo campo!</span>";
	}
	else
	{
    document.getElementById(ver[i]+"div").innerHTML = "";
	}

}

if (formy == 'registrazione')
{
user_esistente = "no";
}

	if ((w <= 0) && (user_esistente == "no"))//se i campi sono tutti compilati inoltriamo tutto!
{
document.getElementById(formy).submit();
}
}//fine funzione

function preleva_parolechiave(contenuto,url,categoria,campo)
{
	var http2 = new XMLHttpRequest();
var url = url;
var params = "domanda=preleva_parole_chiave&categoria="+categoria+"&campo="+campo;
http2.open("GET", url+"?"+params, true);

http2.onreadystatechange = function() {//Call a function when the state changes.
	if(http2.readyState == 4 && http2.status == 200) {
	
risult = http2.responseText;
splitti = risult.split("SEPARATORE");

document.getElementById(splitti[0]).value = document.getElementById(splitti[0]).value+','+splitti[1];
//initializemarquee();

}
}
http2.send(null);
	
}


////////////la funzione cosa dopo che mi sposta i livelli di sotto dopo che un livlelo superiore di è ingrandito a casusa di un div nascosto
function cosa_dopo(cosa,id)
{
if ($('#'+id).css('height') == "0px")
{

dim_id =  document.getElementById(id).offsetHeight+document.getElementById(id).offsetTop;
	cosa = eval(cosa);
	vecchia_dimensione = 0;
	 dopo_id_ultimo_div = id;
	for (var i in cosa)
	{ //vecchia dimensione, mi aggiunge l'altezza dei div che venivano prima
	spostamento = "";
	foo = "";
	vecchio_footer = "";
	
		
		document.getElementById(cosa[i]).style.top = (dim_id+vecchia_dimensione-spostamento+vecchio_footer)+"px";
		vecchia_dimensione =  document.getElementById(cosa[i]).offsetHeight+vecchia_dimensione;
	    dopo_id_ultimo_div = cosa[i];

	}
	}//fine se l'overflow non visibile
	if ((document.getElementById(dopo_id_ultimo_div).offsetHeight+document.getElementById(id_ultimo_div).offsetTop) < pageY)
{

document.getElementById("footer_principale").style.top = $(document).height()+'px';

}
else
{

document.getElementById("footer_principale").style.top = (dim_id+vecchia_dimensione)+"px";
}
	



    
}
///fine funzione per spostare livelli


function initialize()
{
}
lista_divs = new Array();



function getElementLeft(Elem) {
	if (1==2) {
		var elem = getObjNN4(document, Elem);
		return elem.pageX;
	} else {
		var elem;
		if(document.getElementById) {
			var elem = document.getElementById(Elem);
		} else if (document.all){
			var elem = document.all[Elem];
		}
		xPos = elem.offsetLeft;
		tempEl = elem.offsetParent;
  		while (tempEl != null) {
  			xPos += tempEl.offsetLeft;
	  		tempEl = tempEl.offsetParent;
  		}
		return xPos;
	}
}


function getElementTop(Elem) {
	if (1==2) {
		var elem = getObjNN4(document, Elem);
		return elem.pageY;
	} else {
		if(document.getElementById) {	
			var elem = document.getElementById(Elem);
		} else if (document.all) {
			var elem = document.all[Elem];
		}
		yPos = elem.offsetTop;
		tempEl = elem.offsetParent;
		while (tempEl != null) {
  			yPos += tempEl.offsetTop;
	  		tempEl = tempEl.offsetParent;
  		}
		return yPos;
	}
}


function pannello_rapido()
{
	//il pannello per l'accesso rapido alle configurazioni
	//mostra il div del pannello rapido
	document.getElementById('pannello_rapido_contenitore').style.display = "";
}


function caricamento_rapido_immagini()
{
	//il pannello per l'accesso rapido alle configurazioni
	//mostra il div del pannello rapido
	document.getElementById('pannello_rapido_immagini').style.display = "";
	var currentHref = window.location.href;
window.location.href = currentHref.substr(0, currentHref.lastIndexOf("#")) + "#testa_pagina";
}
function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
	function ReadCookie(cookieName) {
 var theCookie=""+document.cookie;
 var ind=theCookie.indexOf(cookieName);
 if (ind==-1 || cookieName=="") return ""; 
 var ind1=theCookie.indexOf(';',ind);
 if (ind1==-1) ind1=theCookie.length; 
 return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}

var cook = ReadCookie("users_resolution");
	//alert(cook);
	if (cook == "")
	{
	valoreriso = screen.width+"x"+screen.height+"px";
setCookie("users_resolution",valoreriso,7);
	}
	
	function dim_fin()
{
 this.windowX = (document.documentElement && document.documentElement.clientWidth) || window.innerWidth || self.innerWidth || document.body.clientWidth; this.windowY = (document.documentElement && document.documentElement.clientHeight) || window.innerHeight || self.innerHeight || document.body.clientHeight; 
 this.scrollX = (document.documentElement && document.documentElement.scrollLeft) || window.pageXOffset || self.pageXOffset || document.body.scrollLeft; 
 this.scrollY = (document.documentElement && document.documentElement.scrollTop) || window.pageYOffset || self.pageYOffset || document.body.scrollTop; 
 this.pageX = (document.documentElement && document.documentElement.scrollWidth) ? document.documentElement.scrollWidth : (document.body.scrollWidth > document.body.offsetWidth) ? document.body.scrollWidth : document.body.offsetWidth; 
this.pageY = $(document).height();
} 


jQuery.fn.center = function(params) {

		var options = {

			vertical: true,
			horizontal: true

		}
		op = jQuery.extend(options, params);

   this.each(function(){

		//initializing variables
		var $self = jQuery(this);
		//get the dimensions using dimensions plugin
		var width = $self.width();
		var height = $self.height();
		//get the paddings
		var paddingTop = parseInt($self.css("padding-top"));
		var paddingBottom = parseInt($self.css("padding-bottom"));
		//get the borders
		var borderTop = parseInt($self.css("border-top-width"));
		var borderBottom = parseInt($self.css("border-bottom-width"));
		//get the media of padding and borders
		var mediaBorder = (borderTop+borderBottom)/2;
		var mediaPadding = (paddingTop+paddingBottom)/2;
		//get the type of positioning
		var positionType = $self.parent().css("position");
		// get the half minus of width and height
		var halfWidth = (width/2)*(-1);
		var halfHeight = ((height/2)*(-1))-mediaPadding-mediaBorder;
		// initializing the css properties
		var cssProp = {
			position: 'absolute'
		};

		if(op.vertical) {
			cssProp.height = height;
			cssProp.top = '50%';
			cssProp.marginTop = halfHeight;
		}
		if(op.horizontal) {
			cssProp.width = width;
			cssProp.left = '50%';
			cssProp.marginLeft = halfWidth;
		}
		//check the current position
		if(positionType == 'static') {
			$self.parent().css("position","relative");
		}
		//aplying the css
		$self.css(cssProp);


   });

};

/**
 * Magic time parsing, based on Simon Willison's Magic date parser
 * @see http://simon.incutio.com/archive/2003/10/06/betterDateInput
 * @author Stoyan Stefanov &lt;stoyan@phpied.com&gt;
 */


/**
 * This is the place to customize the result format,
 * once the date is figured out
 *
 * @param Date d A date object
 * @return string A time string in the preferred format
 */
function getReadable(d) {
    return padAZero(d.getHours())
           + ':'
           + padAZero(d.getMinutes())
           + ':'
           + padAZero(d.getSeconds());
}
/**
 * Helper function to pad a leading zero to an integer
 * if the integer consists of one number only.
 * This function s not related to the algo, it's for
 * getReadable()'s purposes only.
 *
 * @param int s An integer value
 * @return string The input padded with a zero if it's one number int
 * @see getReadable()
 */
function padAZero(s) {
    s = s.toString();
    if (s.length == 1) {
        return '0' + s;
    } else {
        return s;
    }
}


/**
 * Array of objects, each has:
 * <ul><li>'re' - a regular expression</li>
 * <li>'handler' - a function for creating a date from something
 *     that matches the regular expression</li>
 * <li>'example' - an array of examples that show matching examples</li>
 * Handlers may throw errors if string is unparseable.
 * Examples are used for automated testing, so they should be updated
 *   once a regexp is added/modified.
 */
var timeParsePatterns = [
    // Now
    {   re: /^now/i,
        example: new Array('now'),
        handler: function() {
            return new Date();
        }
    },
    // p.m.
    {   re: /(\d{1,2}):(\d{1,2}):(\d{1,2})(?:p| p)/,
        example: new Array('9:55:00 pm','12:55:00 p.m.','9:55:00 p','11:5:10pm','9:5:1p'),
        handler: function(bits) {
            var d = new Date();
            var h = parseInt(bits[1], 10);
            if (h < 12) {h += 12;}
            d.setHours(h);
            d.setMinutes(parseInt(bits[2], 10));
            d.setSeconds(parseInt(bits[3], 10));
            return d;
        }
    },
    // p.m., no seconds
    {   re: /(\d{1,2}):(\d{1,2})(?:p| p)/,
        example: new Array('9:55 pm','12:55 p.m.','9:55 p','11:5pm','9:5p'),
        handler: function(bits) {
            var d = new Date();
            var h = parseInt(bits[1], 10);
            if (h < 12) {h += 12;}
            d.setHours(h);
            d.setMinutes(parseInt(bits[2], 10));
            d.setSeconds(0);
            return d;
        }
    },
    // p.m., hour only
    {   re: /(\d{1,2})(?:p| p)/,
        example: new Array('9 pm','12 p.m.','9 p','11pm','9p'),
        handler: function(bits) {
            var d = new Date();
            var h = parseInt(bits[1], 10);
            if (h < 12) {h += 12;}
            d.setHours(h);
            d.setMinutes(0);
            d.setSeconds(0);
            return d;
        }
    },
    // hh:mm:ss
    {   re: /(\d{1,2}):(\d{1,2}):(\d{1,2})/,
        example: new Array('9:55:00','19:55:00','19:5:10','9:5:1','9:55:00 a.m.','11:55:00a'),
        handler: function(bits) {
            var d = new Date();
            d.setHours(parseInt(bits[1], 10));
            d.setMinutes(parseInt(bits[2], 10));
            d.setSeconds(parseInt(bits[3], 10));
            return d;
        }
    },
    // hh:mm
    {   re: /(\d{1,2}):(\d{1,2})/,
        example: new Array('9:55','19:55','19:5','9:55 a.m.','11:55a'),
        handler: function(bits) {
            var d = new Date();
            d.setHours(parseInt(bits[1], 10));
            d.setMinutes(parseInt(bits[2], 10));
            d.setSeconds(0);
            return d;
        }
    },
    // hhmmss
    {   re: /(\d{1,6})/,
        example: new Array('9','9a','9am','19','1950','195510','0955'),
        handler: function(bits) {
            var d = new Date();
            var h = bits[1].substring(0,2);
            var m = parseInt(bits[1].substring(2,4), 10);
            var s = parseInt(bits[1].substring(4,6), 10);
            if (isNaN(m)) {m = 0;}
            if (isNaN(s)) {s = 0;}
            d.setHours(parseInt(h, 10));
            d.setMinutes(parseInt(m, 10));
            d.setSeconds(parseInt(s, 10));
            return d;
        }
    },


];

/**
 * Method that loops through all regexp's examples and lists them.
 * Optionally, the method can also run tests with the examples.
 *
 * @param boolean run_test TRUE is tests should be run on the examples, FALSE if only to show examples
 * @return object An XML 'ul' node
 */
function getExamples(run_tests) {
    var xml = document.createElement('ul');
    xml.setAttribute('id', 'time-parser-examples');
    for (var i = 0; i < timeParsePatterns.length; i++) {
        try {
            var example = timeParsePatterns[i].example;
            for (var j = 0; j < example.length; j++) {
                var list_item = document.createElement('li');
                if (!run_tests) {
                    var list_item_value = document.createTextNode(example[j]);
                } else {
                    var parsed = parseTimeString(example[j])
                    var result = getReadable(parsed) + ' -> ' + parsed.toTimeString();
                    var list_item_value = document.createTextNode(example[j] + ' -> ' + result)
                }
                list_item.appendChild(list_item_value)
                xml.appendChild(list_item);
            }
        } catch(e){}
    }
    return xml;
}

/**
 * Parses a string to figure out the time it represents
 *
 * @param string s String to parse
 * @return Date a valid Date object
 * @throws Error
 */
function parseTimeString(s) {
    for (var i = 0; i < timeParsePatterns.length; i++) {
        var re = timeParsePatterns[i].re;
        var handler = timeParsePatterns[i].handler;
        var bits = re.exec(s);
        if (bits) {
            return handler(bits);
        }
    }
    throw new Error("Invalid time string");
}

function magicTime(input) {
    var messagespan = input.id + '-messages';
    try {
        var d = parseTimeString(input.value);
        input.value = getReadable(d);
        input.className = '';
        try {
            // Human readable time
            el = document.getElementById(messagespan);
            el.firstChild.nodeValue = d.toTimeString();
            el.className = 'normal';
        }
        catch (e) {
            // the message div is not in the document
        }
    }
    catch (e) {
        input.className = 'error';
        try {
            el = document.getElementById(messagespan);
            var message = e.message;
            // Fix for IE6 bug
            if (message.indexOf('is null or not an object') > -1) {
                message = 'Invalid time string';
            }
            el.firstChild.nodeValue = message;
            el.className = 'error';
        } catch (e){} // no message div
    }
}

/*
 * Input Floating Hint Box - jQuery plugin 1.1 Beta
 *
 * Copyright (c) 2008 Nicolae Namolovan (nicolae.namolovan gmail.com)
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: 20
 *
 */
 /**
  * Home page http://nicolae.namolovan.googlepages.com/jquery.inputHintBox.html
  * Demo http://nicolae.namolovan.googlepages.com/jquery.inputHintBox.demo.html
  **/

/**
 * Provide an automatic box hint in the right side of a input when user click it, it disapear when focus change (blur)
 *
 * Depends on dimensions plugin's offset method for correct positioning of the hint box element
 *
 * The source(@source) of the text/html can be an attribute (title for example), or a pure html.
 * Attribute can contain escaped html, example: title="This will be &lt;b&gt;Bold&lt;/b&gt;"
 *
 * All hints can use one div element(@div option) with your custom design, and only some subelement of 
 * this @div will change (according to source).
 *
 * You can provide only the @className, and for each input a separate <div> element will be created
 * with @className as class.
 *
 * If user click on the box to select some text (for copy/paste for example), box will not disappear.
 *
 * If you need to make the box appear in more left, use incrementLeft, same for top - incrementTop,
 * you can use - sign if you want to decrement.
 **/

/**
 * Example, you have a shiny div and you want to use it as a Shell for hint messages
 * <div id="shiny_box">
 * 	<span id="round-tleft"><span id="round-tright">
 *	<div class="shiny_box_body"></div>
 * 	<span id="round-bleft"><span id="round-bright">
 * </div>
 *
 * You have a inputs like:
 * <input name="username" type="text" class="titleHintBox" title="Only letters &lt;b&gt;(a-z)&lt;/b&gt;, numbers (0-9), and periods (.) are allowed">
 * <input name="password" type="text" class="titleHintBox" title="Minimum of 8 characters in length">
 *
 * Here is an example of js to use:
 * $('.titleHintBox').inputHintBox({div:$('#shiny_box'),div_sub:'.shiny_box_body',source:'attr',attr:'title',incrementLeft:12,incrementTop:-12});
 **/

/**
 * Provide a hint box near input as a absolute positioned div.
 * @name InputHintBox
 * @cat Plugins/Forms
 * @type $
 * @param Map options Optional settings
 * @option jQueryDom @div box to show, if this is set then className do not apply
 * @option String @div_sub css selector, use this when you need to write the Dynamic html into a element Inside the @div box,
 							example: .body, this will search for .body in context of @div
 * @option String @className This class will be added to the dynamic created div box. Default: "input_hint_box"
 * @option String @source Source of box message text html: attr | html, Default: "attr"
 * @option String @attr If @source = "attr" then html will be taken from the attribute named @attr. Default: "title"
 * @option String @html If @source = "html" them html will be taken from @html
 * @option Integer @incrementLeft This value will be incremented to the left property of the absolute positioned hint box. Default: 10
 * @option Integer @incrementTop This value will be incremented to the top property of the absolute positioned hint box. Default: 10
 * @option String @attachTo Hint box will be appended to this. Default: "body"
 */

(function($) {
$.fn.inputHintBox = function(options) {
	options = $.extend({}, $.inputHintBoxer.defaults, options);
	
	this.each(function(){
		new $.inputHintBoxer(this,options);
	});
	return this;
}

$.inputHintBoxer = function(input, options) {
	var $guideObject,$input = $guideObject = $(input), box, boxMouseDown = false;
	
	//$guideObject - in left of this object hint box will be positioned
	
	// If @type=radio then it must be inside a label and we should put the hint box in the right side of the label
	if ( ($input.attr('type') == 'radio' || $input.attr('type') == 'checkbox') && $input.parent().is('label') ) {
		$guideObject = $( $input.parent() );
	}
	

	function init() {
		var boxHtml = options.html != ''?options.html:
					  	options.source == 'attr'?$input.attr(options.attr): '';
			
		if (typeof boxHtml === "undefined") boxHtml = '';
		box = options.div != '' ? options.div.clone() : $("<div/>").addClass(options.className);
		box = box.css('display','none').addClass('_hintBox').appendTo(options.attachTo);
		
		if (options.div_sub == '') box.html(boxHtml);
		else $(options.div_sub,box).html(boxHtml);
		
		$input.focus(function() {
			$('body').mousedown(global_mousedown_listener);
			show();
		}).blur(function(){
			prepare_hide();
		});
	}
	
	// This is evaluated each time to prevent probs with elements with display none
	function align() {
		var offsets = $guideObject.position(),
			left = offsets.left + $guideObject.width() + options.incrementLeft + 5 + ($.browser.safari?5:($.browser.msie?10:($.browser.mozilla?6:0))),
			top = offsets.top + options.incrementTop + ($.browser.msie?14:($.browser.mozilla?8:0));
		box.css({position:"absolute",top:top,left:left});
	}
	
	function show() {
		align();
		box.fadeIn('slow');
	}
	
	function prepare_hide() {
		// We want to allow user to select and copy/paste content from the box
		// So delay a bit to see where user click
		$('body').click(global_click_listener);
		if (boxMouseDown) return;
		$.inputHintBoxer.mostRecentHideTimer = setTimeout(function(){hide()},300);
	}
	
	var global_click_listener = function(e) {
		var $e = $(e.target),c='._hintBox';
		clearTimeout($.inputHintBoxer.mostRecentHideTimer);
		if ($e.parents(c).length == 0 && $e.is(c) == false) hide();
	};
	
	// Prevent hiding when selecting..
	// When user Select a text to select, a Mousedown is fired BEFORE blur of input
	// This why we need to know when a Mousedown is done to our object
	var global_mousedown_listener = function(e) {
		var $e = $(e.target),c='._hintBox';
		boxMouseDown = ($e.parents(c).length != 0 || $e.is(c) != false);
	}
	
	function hide() {
		$('body').unbind('click',global_click_listener);
		$('body').unbind('mousedown',global_mousedown_listener);
		align();
		box.fadeOut('slow');
	}
	
	init();
	return {}
};

$.inputHintBoxer.mostRecentHideTimer = 0;

$.inputHintBoxer.defaults = {
	div: '',
	className: 'input_hint_box',
	source: 'attr', // attr or html
	div_sub: '', // Where to write
	attr: 'title',
	html: '',
	incrementLeft: 5,
	incrementTop: 0,
	attachTo: 'body'
}

})(jQuery);


/*
 * jQuery resize event - v1.1 - 3/14/2010
 * http://benalman.com/projects/jquery-resize-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,h,c){var a=$([]),e=$.resize=$.extend($.resize,{}),i,k="setTimeout",j="resize",d=j+"-special-event",b="delay",f="throttleWindow";e[b]=250;e[f]=true;$.event.special[j]={setup:function(){if(!e[f]&&this[k]){return false}var l=$(this);a=a.add(l);$.data(this,d,{w:l.width(),h:l.height()});if(a.length===1){g()}},teardown:function(){if(!e[f]&&this[k]){return false}var l=$(this);a=a.not(l);l.removeData(d);if(!a.length){clearTimeout(i)}},add:function(l){if(!e[f]&&this[k]){return false}var n;function m(s,o,p){var q=$(this),r=$.data(this,d);r.w=o!==c?o:q.width();r.h=p!==c?p:q.height();n.apply(this,arguments)}if($.isFunction(l)){n=l;return m}else{n=l.handler;l.handler=m}}};function g(){i=h[k](function(){a.each(function(){var n=$(this),m=n.width(),l=n.height(),o=$.data(this,d);if(m!==o.w||l!==o.h){n.trigger(j,[o.w=m,o.h=l])}});g()},e[b])}})(jQuery,this);
