var fpw,fph,tp,cp;
var nc,nmu,timeout=1000;
$(document).ready(function(){
	//TABLESORTER PARSER
	// add parser through the tablesorter addParser method 
  $.tablesorter.addParser({ 
      // set a unique id 
      id: 'datait', 
      is: function(s) { 
          // return false so this parser is not auto detected 
          return false; 
      }, 
      format: function(s) { 
          // format your data for normalization 
//           return s.toLowerCase().replace(/good/,2).replace(/medium/,1).replace(/bad/,0);
//                          MESE            GIORNO            ANNO
          var dt=new Date(s.substr(3,2)+','+s.substr(0,2)+','+s.substr(8,2));
          if(isNaN(dt.getTime())){
            return 0;
          }else{
            return dt.getTime();
          } 
      }, 
      // set type, either numeric or text 
      type: 'numeric' 
  });   
  //ATTIVAZIONE TABLESORTER
	//////////////////////////////////////////////////////////////////////////////
	$("#interface_travel_table").tablesorter();
  $("#interface_list_table").tablesorter();
  $("#interface_dediche_table").tablesorter();
  $("#interface_blog_table").tablesorter();
  $("#interface_carrello_table").tablesorter();
  $("#interface_access_table").tablesorter();
  $('#interface_adv_table').tablesorter();
  $('#interface_sms_table').tablesorter();
  $('#interface_catalogo_table').tablesorter();
  $('#interface_prodotti_table').tablesorter();
  $('#interface_categorie_table').tablesorter();
  $('#interface_manufact_table').tablesorter();
  $('#interface_attributi_table').tablesorter();
  //////////////////////////////////////////////////////////////////////////////
  //PRELOAD IMMAGINI
  //////////////////////////////////////////////////////////////////////////////
//   $.preloadCssImages({ imgDir: 'style/style_image' });
  //////////////////////////////////////////////////////////////////////////////
  //CARICAMENTO video embedded
  //////////////////////////////////////////////////////////////////////////////
//   $.mb_audioEmbedder.playerPath="sys_include_js/ext_mb/player.swf";
  $.mb_videoEmbedder.defaults.width=500;
  //////////////////////////////////////////////////////////////////////////////
});
//AGGIORNA PREZZO NELLA SCHEDA PRODOTTO
function aggiorna_prezzo(){
  var costo_markuppato=0;
  var costo_scontato=0;
  var costo_vendita_scontato=0;
  var costo_vendita=0;
  var ingrosso=$('#prezzo_ingrosso').val();
  var markup=UTF8.decode($('#mark_up option:selected').text());
  var sconto=UTF8.decode($('#sconto option:selected').text());
  var aliquota=UTF8.decode($('#aliquota option:selected').text());
//   alert('ingrosso '+ingrosso+' markup'+markup+' sconto '+sconto+' aliquota'+aliquota);
  //MARK UP FISSO O %
  if((posm=markup.indexOf("%"))!=-1){
    percentuale_markup=parseFloat(markup.slice(0,posm))/100;
    valore_markup=parseFloat(ingrosso)*percentuale_markup;
    costo_markuppato=parseFloat(ingrosso)+valore_markup;
  }else if(markup.indexOf("-->")!=-1){
    costo_markuppato=parseFloat(ingrosso);
  }else{
    fisso_markup=parseFloat(markup);
    costo_markuppato=parseFloat(ingrosso)+parseFloat(fisso_markup);
  }
  //SCONTO FISSO O %
  if((poss=sconto.indexOf("%"))!=-1){
    percentuale_sconto=parseFloat(sconto.slice(0,poss))/100;
    valore_sconto=parseFloat(costo_markuppato)*percentuale_sconto;
    costo_scontato=parseFloat(costo_markuppato)-valore_sconto;
  }else if(sconto.indexOf("-->")!=-1){
    costo_scontato=parseFloat(costo_markuppato);
  }else{
    fisso_sconto=parseFloat(sconto);
    costo_scontato=parseFloat(costo_markuppato)-parseFloat(fisso_sconto);
  }
  //ALIQUOTA
  if((poss=aliquota.indexOf("%"))!=-1){
    percentuale_aliquota=parseFloat(aliquota.slice(0,poss))/100;
    valore_aliquota_scontato=parseFloat(costo_scontato)*percentuale_aliquota;
    valore_aliquota_vendita=parseFloat(costo_markuppato)*percentuale_aliquota;
    costo_vendita_scontato=parseFloat(costo_scontato)+valore_aliquota_scontato;
    costo_vendita=parseFloat(costo_markuppato)+valore_aliquota_vendita;
  }else{
    costo_vendita_scontato=parseFloat(costo_scontato);
    costo_vendita=parseFloat(costo_markuppato);
  }
  $('#prezzo_vendita').val(costo_vendita);
  $('#prezzo_scontato').val(costo_vendita_scontato);
}
//CODIFICA/DECODIFICA UTF-8
UTF8 = {
	encode: function(s){
		for(var c, i = -1, l = (s = s.split("")).length, o = String.fromCharCode; ++i < l;
			s[i] = (c = s[i].charCodeAt(0)) >= 127 ? o(0xc0 | (c >>> 6)) + o(0x80 | (c & 0x3f)) : s[i]
		);
		return s.join("");
	},
	decode: function(s){
		for(var a, b, i = -1, l = (s = s.split("")).length, o = String.fromCharCode, c = "charCodeAt"; ++i < l;
			((a = s[i][c](0)) & 0x80) &&
			(s[i] = (a & 0xfc) == 0xc0 && ((b = s[i + 1][c](0)) & 0xc0) == 0x80 ?
			o(((a & 0x03) << 6) + (b & 0x3f)) : o(128), s[++i] = "")
		);
		return s.join("");
	}
};
//CAMBIA CLASSI
function classi_obb(campo,campi){
  var cc=$('#'+campo.id).val();
  switch (cc){
    case "null":
      alert('Devi selezionare lo stato della quota!!');
    break;
    case '1': //Da Acquistare
      var pv = campi.split(';');
      for(var param in pv){
        nome_campo = pv[param].substr(0,pv[param].indexOf("_"));
        js_campo = pv[param].substr(pv[param].indexOf("_")+1);
        $('#'+nome_campo+"_label").removeClass("code_form_label_obbl");
        $('#'+nome_campo+"_label").addClass("code_form_label");        
        $('div').remove('#'+nome_campo+"_cli");
        $('#'+nome_campo).removeAttr('onblur');
        $('#'+nome_campo).addClass("code_form_text_blur");
        $('#'+nome_campo).removeClass("code_form_text_error");
      }
      $('#data_acquisto_label').removeClass("code_form_label_obbl");
      $('#data_acquisto_label').addClass("code_form_label");
      $('div').remove('#data_acquisto_cli');
      $('#data_acquisto').removeAttr('onblur');
      $('#data_acquisto').addClass("code_form_text_blur");
      $('#data_acquisto').removeClass("code_form_text_error");
      $('#data_opzione_label').removeClass("code_form_label_obbl");
      $('#data_opzione_label').addClass("code_form_label");
      $('div').remove('#data_opzione_cli');
      $('#data_opzione').removeAttr('onblur');
      $('#data_opzione').addClass("code_form_text_blur");
      $('#data_opzione').removeClass("code_form_text_error");
    break;
    case '2': //Acquistata
      var pv = campi.split(';');
      for(var param in pv){
        nome_campo = pv[param].substr(0,pv[param].indexOf("_"));
        js_campo = pv[param].substr(pv[param].indexOf("_")+1);
        $('#'+nome_campo+'_label').removeClass("code_form_label");
        $('#'+nome_campo+'_label').addClass("code_form_label_obbl");
        $('#'+nome_campo).after('<div id=\"'+nome_campo+'_cli\" class=\"error_input\" style=\"display:none;\"></div>');
        $('#'+nome_campo).attr('onBlur',js_campo+'(this);');
      }
      $('#data_acquisto_label').removeClass("code_form_label");
      $('#data_acquisto_label').addClass("code_form_label_obbl");
      $('#data_acquisto').after('<div id=\"data_acquisto_cli\" class=\"error_input\" style=\"display:none;\"></div>');
      $('#data_acquisto').attr('onBlur','outdate(this);');
      $('#data_opzione_label').removeClass("code_form_label_obbl");
      $('#data_opzione_label').addClass("code_form_label");
      $('div').remove('#data_opzione_cli');
      $('#data_opzione').removeAttr('onblur');
      $('#data_opzione').addClass("code_form_text_blur");
      $('#data_opzione').removeClass("code_form_text_error");
    break;
    case '3': //Opzionata
      var pv = campi.split(';');
      for(var param in pv){
        nome_campo = pv[param].substr(0,pv[param].indexOf("_"));
        js_campo = pv[param].substr(pv[param].indexOf("_")+1);
        $('#'+nome_campo+"_label").removeClass("code_form_label");
        $('#'+nome_campo+"_label").addClass("code_form_label_obbl");
        $('#'+nome_campo).after('<div id=\"'+nome_campo+'_cli\" class=\"error_input\" style=\"display:none;\"></div>');
        $('#'+nome_campo).attr('onBlur',js_campo+'(this);');
      }
      $('#data_opzione_label').removeClass("code_form_label");
      $('#data_opzione_label').addClass("code_form_label_obbl");
      $('#data_opzione').after('<div id=\"data_opzione_cli\" class=\"error_input\" style=\"display:none;\"></div>');
      $('#data_opzione').attr('onBlur','outdate(this);');
      $('#data_acquisto_label').removeClass("code_form_label_obbl");
      $('#data_acquisto_label').addClass("code_form_label");
      $('div').remove('#data_acquisto_cli');
      $('#data_acquisto').removeAttr('onblur');
      $('#data_acquisto').addClass("code_form_text_blur");
      $('#data_acquisto').removeClass("code_form_text_error");
    break;
  }//end switch
}//end classi_obb
//APRIRE FINESTRA NUOVA PER PDF
function apri_link_new_win(link,nomefi){
  window.open(link,nomefi)
//   if(nomefi=='siref'){
//     setTimeout(function () {
//   	window.location.replace('index.php?action=home&'+new Date().getTime());
//   	}, 1800);
//   }
}
//CONTEGGIO MASSIMO CARATTERI
function max_char(campo,max){
  var testo=$('#'+campo).val();
  var num=testo.length;
  if(num>max){
    alert('Numero caratteri massimo raggiunto!!');
    var testo_new=testo.slice(0,num-1);
    $('#'+campo).text(testo_new);
    return false;
  }else{    
    var rimasti=max-num;
    $('#'+campo+"_max_label").html("["+rimasti+"/"+max+"]");
    return false;
  }
}
//CHIUSURA DIV TRANSAZIONI
function close_trans(){
  $('#transazioni').empty();
}
//ATTIVA NUMEROSITA' IN CASO DI QUOTA FISSA
function chek_type(iDiv){
  if($('#'+iDiv.id).val()==1){
    $('#numerosita').css('display','block');
  }else{
    $('#numerosita').css('display','none');
  }
}
//VISUALIZZA O NASCONDE ICONA CANCELLA
function js_edit(num){
  for(var i=0;i<=num;i++){
    $('#elimina'+i).css('display','none');
    $('#remove'+i).removeClass('icon_remove_over').addClass('icon_remove');
    var state=$('#remove'+i).css('display');
    switch (state){
      case "block":
        $('#remove'+i).css('display','none');
      break;
      case "none":
        $('#remove'+i).css('display','block');
      break;
    }//end switch
  }
}//fine edit
//VISUALIZZA O NASCONDE BOTTONE CANCELLA
function js_remove(num){
  if($('#remove'+num).hasClass('icon_remove')){
    $('#remove'+num).removeClass('icon_remove').addClass('icon_remove_over');
    $('#elimina'+num).css('display','block');
  }else if($('#remove'+num).hasClass('icon_remove_over')){
    $('#remove'+num).removeClass('icon_remove_over').addClass('icon_remove');
    $('#elimina'+num).css('display','none');
  }  
}//fine remove
function list_over(value,color){
  $('#'+value).css('background-color',''+color);
// 	document.getElementById(value).style.backgroundColor='.color.';
}//fine over
function list_out(value,color){
  color=typeof(color)!='undefined'?color:"";
  if(color!=""){
    $('#'+value).css('background-color','');
    $('#'+value).addClass(''+color+'');
  }else{
    $('#'+value).css('background-color','transparent');
  }
// 	document.getElementById(value).style.backgroundColor='transparent';
}//
// Javascript
//   $(function(){
// 		$.fn.fancyzoom.defaultsOptions.imgDir='../gestione-adv/script/js/jqueryfancyzoom/img/';//very important must finish with a /
//         $('#gallery a').fancyzoom(); 
//         $('a.tozoom').fancyzoom({Speed:400});
//         $('a').fancyzoom({overlay:0.8});
//         $("img.fancyzoom").fancyzoom();
// 			$('#alert_div').corner();
// 			$('#menu_su').corner("bottom 6px");
// 			$('#b_giu').corner("top 6px");
// 	});
// function home_page(){
//   action('get','toolbar','');
// }
//INIZIALIZZAZIONE MAPPE CON DIREZIONI
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;

function calcRoute(sMappa,sStart,sEnd) {
  var start = $('#'+sStart).attr("value"); //document.getElementById("start").value;
  var end = $('#'+sEnd).attr("value"); //document.getElementById("end").value;
  var request = {
    origin:start,
    destination:end,
    travelMode: google.maps.TravelMode.DRIVING
  };
  directionsService.route(request, function(result, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(result);
    }else if(status==google.maps.DirectionsStatus.ZERO_RESULTS){
      alert("Nessun risultato per il percorso richiesto!");
    }else if(status==google.maps.DirectionsStatus.OVER_QUERY_LIMIT){
      alert("Troppe richieste. Riprovare pił tardi!");
    }else if(status==google.maps.DirectionsStatus.REQUEST_DENIED){
      alert("Accesso a Google Maps non riuscito. Riprovare pił tardi!");
    }else if(status==google.maps.DirectionsStatus.INVALID_REQUEST){
      alert("Parametri indirizzi inseriti in modo errato. Riprovare!");
    }else if(status==google.maps.DirectionsStatus.NOT_FOUND){
      alert("Nessun risultato per il percorso richiesto!");
    }else if(status==google.maps.DirectionsStatus.MAX_WAYPOINTS_EXCEEDED){
      alert("Troppi Waypoints inseriti tra origine e destinazione.");
    }else{
			alert("Problema nella ricerca dell'indirizzo: " + status);
  		}
  });
}
//INIZIALIZZAZIONE GOOGLE MAPS
// var initialize = function() {
function initialize(typeMap,iZoom){
  iZoom=typeof(iZoom)!='undefined'?iZoom:5;
  if(typeMap=="route"){
    directionsDisplay = new google.maps.DirectionsRenderer();
  }else{
    var geocoder = new google.maps.Geocoder();
  }
  var latlng = new google.maps.LatLng(42.745334,12.738430);
  var options = {
    zoom: iZoom,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    disableDefaultUI: true
  };
  var map = new google.maps.Map(document.getElementById('map'), options);
  if(typeMap=="route"){
    directionsDisplay.setMap(map);
  }
}
//FUNZIONE PER CREARE LA MAPPA E CENTRARLA SULL INDIRIZZO DELLA FESTA
function createMap(sMappa,campo,iZoom,markerTitle,contentString,markerPan,markerImage){
  var geocoder = new google.maps.Geocoder();
  var address = $('#'+campo).attr("value"); //document.getElementById(campo).value;
  if(address!=""){
  	if(geocoder){
    	geocoder.geocode( {'address': address}, function(results,status) {
    		if (status == google.maps.GeocoderStatus.OK) {
    			var options = {
    				zoom: iZoom,
    				center: results[0].geometry.location,
    				mapTypeId: google.maps.MapTypeId.ROADMAP,
    				disableDefaultUI: true,
    				panControl: false,
            zoomControl: true,
            scaleControl: false,
    				draggable: false
    			};
//       		var map = new google.maps.Map(document.getElementById('map'), options);
      		var map = new google.maps.Map(eval("document.getElementById(\"" + sMappa + "\")"), options);
      		if(markerTitle!="" && contentString!=""){
      		  map.panBy(0,markerPan);
            var infowindow = new google.maps.InfoWindow({
                content: contentString
            });
            var marker = new google.maps.Marker({
              position: results[0].geometry.location,
              title: markerTitle,
              icon: markerImage,
              map: map
            });
            marker.setMap(map);
        		infowindow.open(map,marker);
        	}
    		}else if(status==google.maps.GeocoderStatus.ZERO_RESULTS){
          alert("Nessun risultato per l\'indirizzo richiesto!");
        }else if(status==google.maps.GeocoderStatus.OVER_QUERY_LIMIT){
          alert("Troppe richieste. Riprovare pił tardi!");
        }else if(status==google.maps.GeocoderStatus.REQUEST_DENIED){
          alert("Accesso a Google Maps non riuscito. Riprovare pił tardi!");
        }else if(status==google.maps.GeocoderStatus.INVALID_REQUEST){
          alert("Parametri indirizzo inseriti in modo errato. Riprovare!");
        }else{
    			alert("Problema nella ricerca dell'indirizzo: " + status);
      		}
    	});
    }
  }else{
    alert('Inserisci un indirizzo per visualizzarlo sulla mappa');
    $('#address').focus();
    return false;
  }
}

// CARICA TYNIMCE
// tinyMCE.init({
function carica_tiny(cplx,idty){
  	// Theme options
  	switch(cplx){
      case '1': //SEMPLICE
        $('#'+idty).tinymce({
          script_url : 'script/js/tiny_mce/tiny_mce.js',
        	// General options
        	language : "it",
        	mode : "textareas",
        	theme : "simple",
//         	plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
//           theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
//           theme_advanced_toolbar_location : "top",
//         	theme_advanced_toolbar_align : "left",
//         	theme_advanced_statusbar_location : "bottom",
//         	theme_advanced_resizing : false,
//         	// Example content CSS (should be your site CSS)
//         	content_css : "script/js/tiny_mce/themes/advanced/skins/default/content.css",
        	// Drop lists for link/image/media/template dialogs
      //   	template_external_list_url : "lists/template_list.js",
      //   	external_link_list_url : "lists/link_list.js",
      //   	external_image_list_url : "lists/image_list.js",
      //   	media_external_list_url : "lists/media_list.js",
//         	file_browser_callback : 'myFileBrowser',
//         	save_enablewhendirty : true,
//         	// Replace values for the template plugin
//         	template_replace_values : {
//         		username : "Some User",
//         		staffid : "991234"
//         	}
        });
        break;
      case '2':   //COMPLETO
        $('#'+idty).tinymce({
          script_url : 'script/js/tiny_mce/tiny_mce.js',
        	// General options
        	language : "it",
        	mode : "textareas",
        	theme : "advanced",
        	plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
          theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
          theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,|,forecolor,backcolor",
          theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
    	    theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
    	    theme_advanced_toolbar_location : "top",
        	theme_advanced_toolbar_align : "left",
        	theme_advanced_statusbar_location : "bottom",
        	theme_advanced_resizing : false,
        	// Example content CSS (should be your site CSS)
        	content_css : "script/js/tiny_mce/themes/advanced/skins/default/content.css",
        	// Drop lists for link/image/media/template dialogs
      //   	template_external_list_url : "lists/template_list.js",
      //   	external_link_list_url : "lists/link_list.js",
      //   	external_image_list_url : "lists/image_list.js",
      //   	media_external_list_url : "lists/media_list.js",
        	file_browser_callback : 'myFileBrowser',
        	save_enablewhendirty : true,
        	// Replace values for the template plugin
        	template_replace_values : {
        		username : "Some User",
        		staffid : "991234"
        	}
        });
        break;
      default:
        $('#'+idty).tinymce({
          script_url : 'script/js/tiny_mce/tiny_mce.js',
        	// General options
        	language : "it",
        	mode : "textareas",
        	theme : "advanced",
        	plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
          theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect",
          theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,|,forecolor,backcolor",
          theme_advanced_toolbar_location : "top",
        	theme_advanced_toolbar_align : "left",
        	theme_advanced_statusbar_location : "bottom",
        	theme_advanced_resizing : false,
        	// Example content CSS (should be your site CSS)
        	content_css : "script/js/tiny_mce/themes/advanced/skins/default/content.css",
        	// Drop lists for link/image/media/template dialogs
      //   	template_external_list_url : "lists/template_list.js",
      //   	external_link_list_url : "lists/link_list.js",
      //   	external_image_list_url : "lists/image_list.js",
      //   	media_external_list_url : "lists/media_list.js",
          file_browser_callback : 'myFileBrowser',
        	save_enablewhendirty : true,
        	// Replace values for the template plugin
        	template_replace_values : {
        		username : "Some User",
        		staffid : "991234"
        	}
        });
    }
}
//FUNZIONE MYFILE-BROWSER
function myFileBrowser (field_name, url, type, win) {

//      alert("Field_Name: " + field_name + "\nURL: " + url + "\nType: " + type + "\nWin: " + win); // debug/testing

    /* If you work with sessions in PHP and your client doesn't accept cookies you might need to carry
       the session name and session ID in the request string (can look like this: "?PHPSESSID=88p0n70s9dsknra96qhuk6etm5").
       These lines of code extract the necessary parameters and add them back to the filebrowser URL again. */

    var cmsURL = "/honey5/script/filebrowser-ajax.php" //window.location.toString();    // script URL - use an absolute path!
    if (cmsURL.indexOf("?") < 0) {
        //add the type as the only query parameter
        cmsURL = cmsURL + "?type=" + type;
    }
    else {
        //add the type as an additional query parameter
        // (PHP session ID is now included if there is one at all)
        cmsURL = cmsURL + "&type=" + type;
    }

    tinyMCE.activeEditor.windowManager.open({
        file : cmsURL,
        title : 'My File Browser',
        width : 660,  // Your dimensions may differ - toy around with them!
        height : 400,
        resizable : "no",
        inline : "yes",  // This parameter only has an effect if you use the inlinepopups plugin!
        close_previous : "no",
        popup_css : false
    }, {
        window : win,
        input : field_name
    });
    return false;
  }
// //FUNZIONI DI APPOGGIO
//   function supporto(dati){
//     setTimeout(function(){
//       if(dati['funzione']=='action'){
//         action(dati['tipo'],dati['azione'],dati['parametro_valore'],dati['form'],dati['div']);
//       }else if(dai['funzione']=='verform'){
//         verifica_form(dati['tipo'],dati['azione'],dati['parametro_valore'],dati['sForm'],dati['azione_dopo'],dati['parametro_dopo'],dati['sDiv'],dati['sDivDopo']);
//       }    
//     },200);
//   }
  function supporto_action(tipo,azione,parametro_valore,sForm,sDiv,sPagina){
    setTimeout(function(){
      action(tipo,azione,parametro_valore,sForm,sDiv,sPagina);
    },200);
  }
  function supporto_action_rec(tipo,azione,parametro_valore,sForm,sDiv,azione_dopo,parametro_dopo,sDivDopo){
    setTimeout(function(){
      action_rec(tipo,azione,parametro_valore,sForm,sDiv);
    },200);
  }
//   function supporto_form(tipo,azione,parametro_valore,sForm,azione_dopo,parametro_dopo,sDiv,sDivDopo){
//     setTimeout(function(){
//       verifica_form(tipo,azione,parametro_valore,sForm,azione_dopo,parametro_dopo,sDiv,sDivDopo);
//     },200);
//   }
// function chiama_template()
// {
//   setTimeout(function () {
//     action('get','elenco_template','cliente_1');
//   }, 300);
// }
// function paga_template(id,costo)
// {
//   setTimeout(function () {
//     action('get','carica_carrello','tipo_1;idacq_'+id+';valore_'+costo+';descrizione_template','','esito_op');
//   }, 300);
// }
//FUNZIONE VERIFICA DATA
function IsDate(txtDate)
{
    try
    {
      if(txtDate.length==19){
        if(isNaN(txtDate.substring(0, 4))||txtDate.substring(4, 5) != "-"||isNaN(txtDate.substring(5, 7))||txtDate.substring(7, 8) != "-" ||isNaN(txtDate.substring(8, 10))||txtDate.substring(10,11)!= " " ||isNaN(txtDate.substring(11,13))||txtDate.substring(13,14)!= ":" ||isNaN(txtDate.substring(14,16))||txtDate.substring(16,17)!= ":" ||isNaN(txtDate.substring(17,19)))
        {
          return false;
        }else{
          return true;
        }
      }else if(txtDate.length==10){
        if(isNaN(txtDate.substring(0, 4))||txtDate.substring(4, 5) != "-"||isNaN(txtDate.substring(5, 7))||txtDate.substring(7, 8) != "-"||isNaN(txtDate.substring(8, 10)))
        {
          return false;
        }else{
          return true;
        }
      }else{
          return null;
      }
    }
    catch (e)
    {
        return null;
    }
}
// //FUNZIONE DI ATTIVAZIONE LINK --MODIFICARE CON JQUERY--
// function attiva_link(sElement,sFunzione,sParametri){
//   var parametri='';
//   var i=0;
//   if(sParametri!='')
// 	 {
//       var vPar = sParametri.split(';');
//       for(var iPar in vPar)
//       {
//         if(i==0)
//         {
//           parametri = "'" + vPar[iPar] + "'";
//         }else{
//           parametri = parametri + ",'" + vPar[iPar] + "'";
//         }
//         ++i;
//       }
//   }
// 	sLink = "javascript: " + sFunzione + "(" + parametri + ")";
// 	$('#'+sElement).attr("href",sLink);
// }
//FUNZIONE PER CATTURARE SCRIPT ALL'INTERNO PAGINA CARICATA CON AJAX
EvalJS = function(elementId) {
	var scripts = document.getElementById(elementId).getElementsByTagName('script');
	var code;
	for (var i = 0; i < scripts.length; i++) {
		code =	scripts[i].innerHTML ? scripts[i].innerHTML : 
			scripts[i].text ? scripts[i].text : 
			scripts[i].textContent;
		try {
			eval(code);
		} catch(e) {
			alert(e);
		}
	}
}
// //FUNZIONE PER RIEMPIMENTO CAMPO
// function riempi_campo(campo,valore,metodo)
// {
//   metodo=typeof(metodo)!='undefined'?metodo:0;
//   sElement=campo;
//   if(metodo==0)
//   {
//     eval("document.getElementById(\"" + sElement + "\")").value = valore;
//   }else{
//     eval("document.getElementById(\"" + sElement + "\")").value = replace_stringa(valore," ","_");
//   }
// }
// //FUNZIONE PER CAMBIO STRINGA
// function replace_stringa(stringa,dasos,sostituto) {
// 	while (stringa.indexOf(dasos)>-1) {
// 		pos = stringa.indexOf(dasos);
// 		stringa = '' + (stringa.substring(0, pos) + sostituto + stringa.substring((pos + dasos.length), stringa.length));
// 	}
// 	return stringa;
// }
//FUNZIONE PER CAMBIO IMMAGINE CON DIMENSIONI
function cambia_img(sElement,sPercorso,sImageWH,sImmNull){
  var pv = sImageWH.split('|');
  sImage=pv[0];
  iW=pv[1];
  iH=pv[2];
  sImage=unescape(sImage.toLowerCase());
  var objImm = eval("document.getElementById(\"" + sElement + "\")");
  if(sImage=="no-image" || sImage=="-->.jpg" || sImage.search("scegli")==0)
  {
    ImgTag="<img src=\"" + sPercorso + "no_image.png\">";
  }else if(sImage=="Foto partecipazione"){
    ImgTag="<img src=\"" + sPercorso + "partecipazione.png\" width=\"297px\" height=\"142px\">";
  }else if(sImage=="null"){
    typeof(iW)=='undefined'? ImgTag="<img src=\"" + sImmNull + "\" alt=\"" + sImage + "\">" : ImgTag="<img src=\"" + sImmNull + "\"  alt=\"" + sImage + "\" width=\"" + iW + "\" height=\"" + iH + "\">";
  }else{
    typeof(iW)=='undefined'? ImgTag="<img src=\"" + sPercorso + sImage + "\" alt=\"" + sImage + "\">" : ImgTag="<img src=\"" + sPercorso + sImage + "\"  alt=\"" + sImage + "\" width=\"" + iW + "\" height=\"" + iH + "\">";
  }
  objImm.innerHTML=ImgTag;
}
// //Funzione per download file
// function apri_file(dir,file,idDiv,bhp)
// {
//   var percorso = 'includes/download-inc.php?file='+file+'&dir='+dir;
//   window.open(percorso,'down_file')
//   bhp=typeof(bhp)!='undefined'?bhp:'0';
//   if(bhp=='1')
//   {
//     setTimeout(function () {
//   	window.location.replace('index.php?do=HO'+new Date().getTime());
//   	}, 1800);
//   }
// }
function apri_link_new_win(link,nomefi){
  window.open(link,nomefi)
}
//FUNZIONI PER CALENDARIO
var oldLink = null;
function setActiveStyleSheet(link, title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  }
  if (oldLink) oldLink.style.fontWeight = 'normal';
  oldLink = link;
  link.style.fontWeight = 'bold';
  return false;
}
// This function gets called when the end-user clicks on some date.
function selected(cal, date) {
  cal.sel.value = date; // just update the date in the input field.
  if (cal.dateClicked && (cal.sel.id == "sel1" || cal.sel.id == "sel3"))
    cal.callCloseHandler();
}
function closeHandler(cal) {
  cal.hide();                        // hide the calendar
//  cal.destroy();
  _dynarch_popupCalendar = null;
}
function showCalendar(id, format, showsTime, showsOtherMonths) {
  var el = document.getElementById(id);
  if (_dynarch_popupCalendar != null) {
    // we already have some calendar created
    _dynarch_popupCalendar.hide();                 // so we hide it first.
  } else {
    // first-time call, create the calendar.
    var cal = new Calendar(1, null, selected, closeHandler);
    // uncomment the following line to hide the week numbers
    // cal.weekNumbers = false;
    if (typeof showsTime == "string") {
      cal.showsTime = true;
      cal.time24 = (showsTime == "24");
    }
    if (showsOtherMonths) {
      cal.showsOtherMonths = true;
    }
    _dynarch_popupCalendar = cal;                  // remember it in the global var
    cal.setRange(1900, 2070);        // min/max year allowed.
    cal.create();
  }
  _dynarch_popupCalendar.setDateFormat(format);    // set the specified date format
  _dynarch_popupCalendar.parseDate(el.value);      // try to parse the text in field
  _dynarch_popupCalendar.sel = el;                 // inform it what input field we use
  _dynarch_popupCalendar.showAtElement(el.nextSibling, "Br");        // show the calendar
  return false;
}
var MINUTE = 60 * 1000;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;
var WEEK = 7 * DAY;

function isDisabled(date) {
  var today = new Date();
  return (Math.abs(date.getTime() - today.getTime()) / DAY) > 10;
}
function flatSelected(cal, date) {
  var el = document.getElementById("preview");
  el.innerHTML = date;
}
function showFlatCalendar() {
  var parent = document.getElementById("display");

  var cal = new Calendar(0, null, flatSelected);

  cal.weekNumbers = false;

  cal.setDisabledHandler(isDisabled);
  cal.setDateFormat("%A, %B %e");

  cal.create(parent);

  cal.show();
}
//FADE IMMAGINI TESTA
var i = 0;
var z = 0;
var conteggio = 0;
fadebackground = {
  base: {
      time: 5000,
      fadeIn: 2000
  },
  vai: function() {
      $('#bgFader').find('.img' + i).fadeOut(5000);
      z = i + 1;
      if (z >= conteggio) {
          z = 0;
          i = -1;
      }
      $('#bgFader').find('.img' + z).fadeIn(fadebackground.base.fadeIn);

      i++;
  },
  funtimer: function() {
      var timer = 0;
      var i = 0;
      timer = setInterval(function() { fadebackground.vai() }, fadebackground.base.time);
  },
  init: function(config) {
      conteggio = $('#bgFader img').length;
      if (config) {
          for (prop in config) {
              fadebackground.base[prop] = config[prop];
          }
      }
      var j = 0;
      $('#bgFader img').each(function() {
          $(this).addClass("img" + j);
          j++
      })
      for (j = 1; j < conteggio; j++) {
          $('#bgFader .img' + j).addClass("invisibile");
      }
      fadebackground.funtimer()
  }
}
