/**
 * jQuery Plugin to obtain touch gestures from iPhone, iPod Touch and iPad, should also work with Android mobile phones (not tested yet!)
 * Common usage: wipe images (left and right to show the previous or next image)
 * 
 * @author Andreas Waltl, netCU Internetagentur (http://www.netcu.de)
 * @version 1.1.1 (9th December 2010) - fix bug (older IE's had problems)
 * @version 1.1 (1st September 2010) - support wipe up and wipe down
 * @version 1.0 (15th July 2010)
 */
(function($) { 
   $.fn.touchwipe = function(settings) {
     var config = {
    		min_move_x: 20,
    		min_move_y: 20,
 			wipeLeft: function() { },
 			wipeRight: function() { },
 			wipeUp: function() { },
 			wipeDown: function() { },
			preventDefaultEvents: true
	 };
     
     if (settings) $.extend(config, settings);
 
     this.each(function() {
    	 var startX;
    	 var startY;
		 var isMoving = false;

    	 function cancelTouch() {
    		 this.removeEventListener('touchmove', onTouchMove);
    		 startX = null;
    		 isMoving = false;
    	 }	
    	 
    	 function onTouchMove(e) {
    		 if(config.preventDefaultEvents) {
    			 e.preventDefault();
    		 }
    		 if(isMoving) {
	    		 var x = e.touches[0].pageX;
	    		 var y = e.touches[0].pageY;
	    		 var dx = startX - x;
	    		 var dy = startY - y;
	    		 if(Math.abs(dx) >= config.min_move_x) {
	    			cancelTouch();
	    			if(dx > 0) {
	    				config.wipeLeft();
	    			}
	    			else {
	    				config.wipeRight();
	    			}
	    		 }
	    		 else if(Math.abs(dy) >= config.min_move_y) {
		    			cancelTouch();
		    			if(dy > 0) {
		    				config.wipeDown();
		    			}
		    			else {
		    				config.wipeUp();
		    			}
		    		 }
    		 }
    	 }
    	 
    	 function onTouchStart(e)
    	 {
    		 if (e.touches.length == 1) {
    			 startX = e.touches[0].pageX;
    			 startY = e.touches[0].pageY;
    			 isMoving = true;
    			 this.addEventListener('touchmove', onTouchMove, false);
    		 }
    	 }    	 
    	 if ('ontouchstart' in document.documentElement) {
    		 this.addEventListener('touchstart', onTouchStart, false);
    	 }
     });
 
     return this;
   };
 
 })(jQuery);

/* azioni eseguite al caricamento di questo file */

(function(jQuery) {


  /* homepage carousel */
  
  ILLY.init_hp_carousel = function() {
    jQuery('.hp_carousel_contents_wrapper').each(function() {
      var hp_carousel_allow_bullet_click = true; /* flag per permettere l'azione sui bullets solo se non vi sono transizioni in corso */
      var cur_car = jQuery(this);
      var cur_car_list_array = cur_car.find('li');
      var cur_car_size = cur_car_list_array.size();
      var is_carousel = (cur_car_size > 1) ? true : false;
      if (is_carousel) { /* se c'è più di un contenuto nei blocchetti della parte alta dell'hp viene istanziato il carousel */
        var cur_car_index = 0;
        /* genero il markup per i bullets */
        var bullet_code = '<div><ul class="hp_carousel_controls_bullets_wrapper">';
        cur_car_list_array.each(function() {
          var me = jQuery(this);
          me.attr('rel', cur_car_index);
          var desc = me.find('img').attr('alt');
          var is_current = (me.hasClass('current')) ? ' class="current"' : '';
          var ga_id = me.find('img').attr('data-ga_id');
          bullet_code += '<li' + is_current + '><a onclick="_gaq.push([\'_trackEvent\',\'Cards\',\'View\',\'' + ga_id + '\']);" href="javascript:void(0)" class="hp_carousel_controls_bullet lbl" title="' + desc + '" rel="' + (cur_car_index++) + '">' + desc + '</a></li>';
        });
        bullet_code += '</ul></div>';
        /* inserisco i bullets */
        cur_car.prev('.hp_carousel_controls_wrapper').append(bullet_code);
        
        var cur_bul_list_wrapper = cur_car.prev('.hp_carousel_controls_wrapper').find('.hp_carousel_controls_bullets_wrapper');
        var cur_bul_list = cur_bul_list_wrapper.find('li');
        
        /* associo le azioni al click sui bullets */
        cur_bul_list.find('a').click(function() {
          if (hp_carousel_allow_bullet_click) {
            clearInterval(cur_handler);
            hp_carousel_allow_bullet_click = false;
            var cur_bul = cur_bul_list_wrapper.find('.current');
            var cur_img = cur_car.find('.current');
            var next_bul = jQuery(this);
            var next_img = cur_car_list_array.eq(parseInt(next_bul.attr('rel')));
            
            cur_img.fadeOut(ILLY.HP_CAROUSEL_FADING, function() {
              cur_img.removeClass('current');
              cur_bul.removeClass('current');
            });
            next_img.fadeIn(ILLY.HP_CAROUSEL_FADING, function() {
              next_img.addClass('current');
              next_bul.parents('li').addClass('current');
              hp_carousel_allow_bullet_click = true;
            });
          }
          else {
            return false;
          }
        });
        
        /* avanzamento automatico dei carousel */
        var cur_img, cur_bul, next_img, next_bul;
        var cur_handler = setInterval(function() {
            
          cur_img = cur_car.find('.current');
          cur_bul = cur_bul_list_wrapper.find('.current');
          if (parseInt(cur_img.attr('rel')) < (cur_car_size - 1)) {
            next_img = cur_img.next();
            next_bul = cur_bul.next();
          }
          else {
            next_img = cur_car_list_array.eq(0);
            next_bul = cur_bul_list.eq(0);
          }
          
          /* dissolvenza immagini */
          hp_carousel_allow_bullet_click = false;
          cur_img.fadeOut(ILLY.HP_CAROUSEL_FADING, function() {
            cur_img.removeClass('current');
            cur_bul.removeClass('current');
          });
          next_img.fadeIn(ILLY.HP_CAROUSEL_FADING, function() {
            next_img.addClass('current');
            next_bul.addClass('current');
            hp_carousel_allow_bullet_click = true;
          });
          
        }, (ILLY.HP_CAROUSEL_DURATION + 2 * ILLY.HP_CAROUSEL_FADING));
      }
      else {
        /* se c'è solo un contenuto al momento non viene eseguito nulla */
      }
    });
  }
  
  
  /* overlay homepage */
  
  ILLY.overlay_hp_fade_out = function() {
    var homepage_overlay_handler = setTimeout(function() {
      jQuery('.homepage_overlay_wr').fadeOut(ILLY.OVERLAY_HP_FADE_TIME, ILLY.init_hp_carousel) /* al fade out dell'overlay lancio l'inizializzazione dei carousel  */
    }, ILLY.OVERLAY_HP_DURATION);
  }
  
  
  
  /* inizializzazione dei carousel realizzati con jQuery Tools */
  ILLY.fire_scrollable = function(scrollable_wrapper_selector, size, options) {

    var scrollable_wr = jQuery(scrollable_wrapper_selector); // Get the Scrollable object wrapper
	var slides = scrollable_wr.find('figure');
	
	
	if (slides.length <= size) {
		scrollable_wr.parent().find('> a').addClass("disabled extradisabled");
	}
	
    if (options) {
      if (options.navigator) {
        var instance = scrollable_wr.scrollable().navigator().data('scrollable'); // Initialize the Scrollable control with navigator and get his API
		
       /* NOTA PER ANALYTICS:
        * nel markup assegnare da WCM i valori appropriati ahli attributi "data-ga_id" relativi alle figures
        * impostare a true il parametro ga_enabled nella chiamata allo scrollable
        * la chiamata all'analytycs sarà del tipo " _gaq.push(['_trackEvent','Cards','View','id']) " dove id è il valore associato all'attributo data-ga_id
        */


        if(options.ga_enabled){
          
          jQuery(instance.getNaviButtons()[2]).find('a').each(function(){
            var index = parseInt(jQuery(this).attr('href').substr(1));
            var cur_ga_id = jQuery(slides[index]).attr('data-ga_id');
            jQuery(this).click(function(){
              _gaq.push(['_trackEvent','Cards','View',cur_ga_id]);
            });
          });
        }
      }
	  
      
      if (options.number_navigator) {
        var numero = options.number_navigator - 1;
        var new_code = "";
        for (i = size-1; i <= numero; i++) {
          //console.log(jQuery(scrollable_wrapper_selector).find('figure').eq(i).attr('data-ga_id'));
          var ga_id = jQuery(scrollable_wrapper_selector).find('figure').eq(i).attr('data-ga_id');
          if (i == size-1) {
            new_code += '<a href="#' + i + '" class="active" onclick="_gaq.push([\'_trackEvent\',\'Cards\',\'View\',\'' + ga_id + '\']);"></a>';
          } else {
            new_code += '<a href="#' + i + '" onclick="_gaq.push([\'_trackEvent\',\'Cards\',\'View\',\'' + ga_id + '\']);"></a>';
          }
        }
        jQuery('.navi').html(new_code);
        scrollable_wr.scrollable().navigator({
          navi: '.navi',
          naviItem: 'a'
        });
      }
	   
      if (options.vertical) {
        scrollable_wr.scrollable({
          vertical: true
        }); // Initialize the Scrollable control with vertical orientation
      }
    }
    else {
      scrollable_wr.scrollable(); // Initialize the Scrollable control
    }
    
	
    var scrollable = scrollable_wr.data('scrollable'); // Get the Scrollable control
	if (scrollable) {
	
		scrollable.onSeek(function(event, index) { // Handle the Scrollable control's onSeek event
		  if (this.getIndex() >= this.getSize() - size) { // Check to see if we're at the end
			scrollable_wr.next('a.next').addClass('disabled'); // Disable the Next link
		  }
		});
    
		scrollable.onBeforeSeek(function(event, index) { // Handle the Scrollable control's onBeforeSeek event
		  if (this.getIndex() >= this.getSize() - size) { // Check to see if we're at the end
			if (index > this.getIndex()) { // Check to see if we're trying to move forward
			  return false; // Cancel navigation
			}
		  }
		  
		});
	}    
  }

  /* jQuery Tools box Overlay */
  ILLY.media_loader = function(overlay_obj) {
    ILLY.overlay_wrapper = overlay_obj.getOverlay().find('.content_wr');
    var trigger = overlay_obj.getTrigger();
    var media_type = trigger.attr('data-rev');
    var media_url = trigger.attr('href');
	
    //overlay_obj.getOverlay().css('width', overlay_obj.getOverlay().get(0).offsetWidth + 'px');
	
    switch (media_type) {
      case 'img':
        ILLY.overlay_wrapper.addClass('bordered');
        var inner_code = '<div class="cl"><img src="' + media_url + '" /></div>';
        if (trigger.attr('data-innerdescription')) {
          inner_code += '<div class="descphoto"><p>' + trigger.attr('data-innerdescription') + '</p></div>';
        }
		
        if (trigger.attr('data-innerlink')) {
          inner_code += '<a style="font-size:12px; display:inline-block; border-width:5px 0; border-color:#fff; border-style:solid;" class="red_button_link" title="' + trigger.attr('data-innertext') + '" href="' + trigger.attr('data-innerlink') + '">' + trigger.attr('data-innertext') + '</a>';
        }
        ILLY.overlay_wrapper.html(inner_code);
        ILLY.overlay_wrapper.css({
          textAlign: 'center'
        });
		
        break;
      case 'ytb':
        ILLY.overlay_wrapper.addClass('bordered');
        if (media_url.split(ILLY.YT_INPAGE_VIDEO_PREF).length > 1) {
          /* genero la url diretta al video se nel cms è stato inserito il link esteso */
          var m_u = ILLY.YT_DIRECT_VIDEO_PREF + media_url.split(ILLY.YT_INPAGE_VIDEO_PREF)[1];
        }
        else {
          /* genero la url diretta al video se nel cms è stato inserito il link abbreviato */
          var m_u = ILLY.YT_DIRECT_VIDEO_PREF + media_url.split(ILLY.YT_SHORT_VIDEO_PREF)[1];
        }
		console.log(ILLY.overlay_wrapper.length);
        ILLY.overlay_wrapper.parent().css({ width: '650px', position: 'absolute', display: 'block', marginLeft: '-275px', left: '50%', marginTop: ($(window).scrollTop() + 20)+'px'});
        ILLY.overlay_wrapper.html('<object width="640" height="390" id="videoplayerobj"><param id="videoplayerobj_movie" name="movie" value="' + m_u + '"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed id="videoplayerembed" src="' + m_u + '" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="390"></embed></object>');
		break;
      case 'vid':

        /* metto in pausa gli eventuali video in riproduzione presenti in pagina ( caratterizzati dall'avere la classe embedded_video ) prima di aprire il nuovo video in overlay */
       if(jQuery.browser.msie){
          jQuery('object.vjs-flash-fallback').each(function(){
            this.pauseMovie();
            jQuery(this).addClass('embedded_video_paused');
          });
       }else{
          $('video.embedded_video.vjs-playing').each(function(){
            this.pause();
            jQuery(this).addClass('embedded_video_paused');
          });
       }
        
        ILLY.overlay_wrapper.addClass('bordered');
        
        var video_height = trigger.attr('data-videoheight');
        var video_width = trigger.attr('data-videowidth');
        var video_poster = trigger.attr('data-videoposter');
        var video_id = trigger.attr('data-video-id');
        var video_nome_ogv = trigger.attr('data-videonome-ogv');
				var video_nome_mp4 = trigger.attr('data-videonome-mp4');
				var video_nome_webm = trigger.attr('data-videonome-webm');
        var video_autoplay = (trigger.attr('data-video-autoplay') == 'true')?'autoplay="autoplay"':'';
	      var video_autoplay_flash = trigger.attr('data-video-autoplay');
	      var video_autoloop = (trigger.attr('data-video-autoloop'))? 'loop="loop"' : '';
	      var video_autoloop_flash = trigger.attr('data-video-autoloop')? 'true' : 'false';
	      var video_controls = trigger.attr('data-video-controls');
          
   		  var qsflash = 'r='+ Math.random() +'&videoUrl='+video_nome_mp4+'&autoPlay='+video_autoplay_flash+'&loop='+video_autoloop_flash+'&videoID='+video_id+'&controlli=true';


        var flash_code =  '<object id="'+video_id+'" class="vjs-flash-fallback" width="'+video_width+'" height="'+video_height+'" type="application/x-shockwave-flash" data="' + ILLY.SWF_PATH + 'player_video.swf?' + qsflash + '">';
            flash_code += '<param name="movie" value="' + ILLY.SWF_PATH + 'player_video.swf?' + qsflash + '" />';
            flash_code += '<param name="wmode" value="transparent" />';
            flash_code += '<param name="allowfullscreen" value="true" />';
            flash_code += '<param name="bgcolor" value="#000000" />';
            flash_code += '<param name="flashVars" value="'  +  qsflash +'" />';
            flash_code += '<img src="'+video_poster+'" width="'+video_width+'" height="'+video_height+'" alt="Poster Image" title="No video playback capabilities." />';
            flash_code += '<a href="http://get.adobe.com/it/flashplayer/" title="Get Adobe Flash Player"';
            flash_code += 'target="_blank" border="0"><img src="http://www.adobe.com/macromedia/style_guide/images/160x41_Get_Flash_Player.jpg" /></a>';
			
            flash_code += '</object>';

        var player_code =  '<div class="video-js-box show-big-play"' + video_autoloop + ' height="'+video_height+'" preload="auto" poster="'+video_poster+'" '+video_autoplay+' >';
	          player_code += '<video id="'+video_id+'" class="video-js" width="'+video_width+'" controls preload="auto" ' + video_autoloop + ' height="'+video_height+'" preload="auto" poster="'+video_poster+'">';
	          player_code += '<source src="'+video_nome_mp4+'" type=\'video/mp4; codecs="avc1.42E01E, mp4a.40.2"\'/>';
	          player_code += '<source src="'+video_nome_ogv+'" type=\'video/ogg; codecs="theora, vorbis"\' />';
	          player_code += '<source src="'+video_nome_webm+'" type=\'video/webm; codecs="vp8, vorbis"\'/>';
	          player_code += flash_code;
	          player_code += '</video>';
	          player_code += '</div>';
              
        
        if (jQuery.browser.msie) {
          ILLY.overlay_wrapper.html('<div class="video-js-box">' + flash_code + '</div>');
          ILLY.overlay_wrapper.find('.video-js-box').css({ width: video_width + "px", height: video_height + "px"})
            .parent().css({ width: video_width + "px", height: video_height + "px"});
            ILLY.overlay_wrapper.closest('.overlay_wr').css({
                width: video_width + "px",
                height: video_height + "px",
                left    : "50%",
                marginLeft : (video_width/-2) + "px",
                marginTop: ($(window).scrollTop() + 20) + 'px'
            }).show();
				} else {
          ILLY.overlay_wrapper.html(player_code);
          var myPlayer = VideoJS.setup(video_id);
          jQuery('#'+video_id).css('height','auto');
          ILLY.video_listener(video_id,false,false,true); /* params: _video_id,_video_autoloop,_video_autoplay, _show_controls */

          if (trigger.attr('data-video-autoplay') == 'true') {
            ILLY.overlay_wrapper.find('video').get(0).play();
          }
        }
        
        break;
      default:
        ILLY.overlay_wrapper.html(media_type);
    }
  }
  
  // end ILLY.media_loader
  
  
  // create custom animation algorithm for jQuery called "drop" 
  $.easing.drop = function (x, t, b, c, d) {
	  return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
  };

	// loading animation
  $.tools.overlay.addEffect("drop", function(css, done) { 
	 
	 // use Overlay API to gain access to crucial elements
	 var conf = this.getConf(),
		 overlay = this.getOverlay();           
	 
	 // determine initial position for the overlay
	 if (conf.fixed)  {
		css.position = 'fixed';
	 } else {
		css.top += $(window).scrollTop();
		css.left += $(window).scrollLeft();
		css.position = 'absolute';
	 }
	 
	 
	  $.when(overlay.find('img').deferredImageLoader()) /* endwhen */
	  .done(function() {
		
		  var clone = overlay.find('img').clone();
		  clone.css({ position: "absolute", top: "-9999em" }).appendTo('body');
		  var w = clone.width();
		  overlay.css(css)
		  if (overlay.find('.descphoto').length) {
			overlay.find('.descphoto').css('width', (w-10) +'px')
		  }
		  overlay.css({left: "50%", marginLeft: -(w/2) + "px" }).show();
		  done();
	  }) 

	 
	 /* closing animation */
	 }, function(done) {
		this.getOverlay().hide();
  	    done.call();      
	 }
  );
  
  
  /* inizializzazione delle finestre modali realizzate con jQuery Tools */
  ILLY.initialize_carousel_overlay = function() {
    if (!ILLY.INITIALIZED_CAROUSEL_OVERLAY) {
      jQuery('a[data-rel="overlay"]').each(function() {
        var cur_link = jQuery(this);
        /* i link che aprono delle finestre modali devono avere rel="nofollow" per specifiche SEO, ma jQuery Tools richiede rel="#overlay". Quindi indico i link con l'attributo data-rel="overlay" ed effettuo la sostituzione dinamicamente */
        if (cur_link.attr('data-rel') == 'overlay') {
          cur_link.attr('rel', '#overlay');
          /* inizializzo per i link aventi l'attributo data-rel="overlay" le funzionalità di overlay di jQuery Tools */
          cur_link.overlay({
            mask: {
              color: '#000',
              loadSpeed: 200,
              opacity: 0.25
            },

            speed : 600,
      			effect: "drop",
      			fixed : false,
      			left  : "center",
            
            onBeforeLoad: function() {
                
              /* cose da fare prima di aprire l'overlay */
              if (ILLY.IS_IPAD || ILLY.IS_IPHONE_OR_IPOD) {
                $('video').each(function(i) {
                  if ($(this).attr('controls')) {
                    $(this).data('tempcontrols', '1');
                    $(this).removeAttr('controls');
                  }
                });
              }
              
              ILLY.media_loader(this);
                
			  
            },
            onLoad: function() {
                
				/* centro le finestre contenenti immagini molto grandi */
				/*
				ILLY.overlay_wrapper.parent().animate({
				  'left': Math.ceil(((jQuery(window).width() - ILLY.overlay_wrapper.width()) / 2) - parseInt(ILLY.overlay_wrapper.css('borderLeftWidth'))) + 'px'
				});
				*/
				
				
			  
			  /*
              ILLY.overlay_wrapper.parent().hide().css({
                'left': Math.ceil(((jQuery(window).width() - ILLY.overlay_wrapper.width()) / 2) - parseInt(ILLY.overlay_wrapper.css('borderLeftWidth'))) + 'px'
              }).show();*/
              
              /* direttive specifiche per iOS */
              /*
			  if (ILLY.IS_IPAD || ILLY.IS_IPHONE_OR_IPOD) {
                var overlay_offset_top = 40;
                ILLY.overlay_wrapper.parent().animate({
                  'top': (jQuery(window).scrollTop() + overlay_offset_top) + 'px'
                })
              }*/
              //var myPlayer = window.VideoJS.setup("All");
              
              
              
              
            },
            onClose: function() {
              var media_type = cur_link.attr('data-rev');
              var _video_id = cur_link.attr('data-video-id');
              if(media_type == 'vid'){
                //console.log(_video_id);
                _gaq.push(['_trackEvent','video','close',_video_id]);
              }
			  			ILLY.overlay_wrapper.removeClass('bordered');
              ILLY.overlay_wrapper.empty();
							/* riprendo la riproduzione di eventuali video in pagina sospesi all'apertura dell'overlay */
							jQuery('.embedded_video_paused').each(function(){
			          if (jQuery.browser.msie) {
			            jQuery(this).get(0).playMovie();
			          }else{
  				        this.play();
			          }
				        jQuery(this).removeClass('embedded_video_paused');
				      });
                            
                /* cose da fare una volta chiuso l'overlay */
                if (ILLY.IS_IPAD || ILLY.IS_IPHONE_OR_IPOD) {
                  $('video').each(function(i) {
                    if (("string" === typeof($(this).data('tempcontrols')))
                        && $(this).data('tempcontrols') === '1') {
                      $(this).data('tempcontrols', '0');
                      $(this).attr('controls', 'controls');
                    }
                  });
                }
                
            }
          });
        }
      });
      ILLY.INITIALIZED_CAROUSEL_OVERLAY = true;
    }
  }
  
  
  
  ILLY.applyajaxcarousel = function() {
      jQuery('li.newer a[data-rel="overlay"]').each(function() {
        var cur_link = jQuery(this);
        /* i link che aprono delle finestre modali devono avere rel="nofollow" per specifiche SEO, ma jQuery Tools richiede rel="#overlay". Quindi indico i link con l'attributo data-rel="overlay" ed effettuo la sostituzione dinamicamente */
        if (cur_link.attr('data-rel') == 'overlay') {
          cur_link.attr('rel', '#overlay');
          /* inizializzo per i link aventi l'attributo data-rel="overlay" le funzionalità di overlay di jQuery Tools */
          cur_link.overlay({
            mask: {
              color: '#000',
              loadSpeed: 200,
              opacity: 0.25
            },
            speed : 600,
            effect: "drop",
      			fixed : false,
      			left  : "center",
            
            onBeforeLoad: function() {

            /* cose da fare prima di aprire l'overlay */
              if (ILLY.IS_IPAD || ILLY.IS_IPHONE_OR_IPOD) {
                $('video').each(function(i) {
                  if ($(this).attr('controls')) {
                    $(this).data('tempcontrols', '1');
                    $(this).removeAttr('controls');
                  }
                });
              }   
                          
                          
             
              ILLY.media_loader(this);
              
            },
            onLoad: function() {
              /* centro le finestre contenenti immagini molto grandi */
              /*
              ILLY.overlay_wrapper.parent().animate({
                'left': Math.ceil(((jQuery(window).width() - ILLY.overlay_wrapper.width()) / 2) - parseInt(ILLY.overlay_wrapper.css('borderLeftWidth'))) + 'px'
              });*/
              /* direttive specifiche per iOS */
              if (ILLY.IS_IPAD || ILLY.IS_IPHONE_OR_IPOD) {
                var overlay_offset_top = 40;
                ILLY.overlay_wrapper.parent().animate({
                  'top': (jQuery(window).scrollTop() + overlay_offset_top) + 'px'
                })
              }
              var myPlayer = window.VideoJS.setup("All");
              
            },
            onClose: function() {

              var media_type = cur_link.attr('data-rev');
              var _video_id = cur_link.attr('data-video-id');
              if(media_type == 'vid'){
                //console.log(_video_id);
                _gaq.push(['_trackEvent','video','close',_video_id]);
              }
			  			ILLY.overlay_wrapper.removeClass('bordered');
              ILLY.overlay_wrapper.empty();
							/* riprendo la riproduzione di eventuali video in pagina sospesi all'apertura dell'overlay */
							jQuery('.embedded_video_paused').each(function(){
			          if (jQuery.browser.msie) {
			            jQuery(this).get(0).playMovie();
			          }else{
  				        this.play();
			          }
				        jQuery(this).removeClass('embedded_video_paused');
				      });
                    
                /* cose da fare una volta chiuso l'overlay */
                if (ILLY.IS_IPAD || ILLY.IS_IPHONE_OR_IPOD) {
                  $('video').each(function(i) {
                    if (("string" === typeof($(this).data('tempcontrols')))
                        && $(this).data('tempcontrols') === '1') {
                      $(this).data('tempcontrols', '0');
                      $(this).attr('controls', 'controls');
                    }
                  });
                }

                /* reset window size on IE */
                if(jQuery.browser.msie){
                  jQuery('#overlay.overlay_wr').removeAttr('style');
                  jQuery('#overlay.overlay_wr div.content_wr').removeAttr('style');
                }

                            
            }
          });
        }
      });
   
  }
  
  
  
  
  /* leggo e restituisco il parametro in URL passato per argomento alla funzione. Se non è presente, restituisco 0 */
  ILLY.read_url_params = function(param_name) {
    /*      var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
     if (!results) { return 0; }
     return results[1] || 0;*/
    var map = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
      map[key] = value;
    });
    if (param_name) {
      if (map[param_name]) {
        return map[param_name];
      }
      else {
        return false;
      }
    }
    else {
      return map;
    }
  }

  ILLY.show_current_balloon = function(_l,_t,c_b,c_t){
    ILLY.is_thumb_clicked = true;
    c_b.css({ 'left':_l,'top': _t });
    c_b.fadeIn(function(){ILLY.is_thumb_clicked = false});
    c_b.addClass('balloon_active');
    c_t.addClass('current_vertical_thumb');
  }

   /* imposta i loop per i video HTML5 */
   ILLY.AUTOLOOP = function(video, bloop) {
     if (!!bloop) {
       video.currentTime = 0;
       setTimeout(function(){video.play()},250);
     }
     else {
       video.currentTime = video.duration - 0.1;
       video.pause();
       $(video).unbind('play.afternoloop').bind('play.afternoloop', function() {
         $(this).unbind('play.afternoloop');
         this.currentTime = 0;
         this.play();
       });
       $(video).removeAttr('poster');
       /*
       setTimeout(function() {
         video.currentTime = video.duration - 0.1;
         video.pause();
       }, 1);
       */
     }
   }

  /* listener sugli eventi del video player per invio dati Google Analytics */
 
  ILLY.video_listener = function(_video_id,_video_autoloop,_video_autoplay, _show_controls){
    var video_object = jQuery('#'+_video_id);
    var _player_tag = video_object.get(0);

    /* se non c'è controls, mostro il pulsante PLAY, ma nascondo i controlli */
    if(!_show_controls){
      video_object.parent('.video-js-box').addClass('simple_controls');
    }
    
    video_object.bind('loadstart', function() {
      //console.log(_video_id + ': loadstart');
    });

    video_object.bind('durationchange', function() {
      //console.log('durationchange');
    });

    var standby = false;

    video_object.bind('timeupdate', function() {
      var ct = parseInt(this.currentTime);

      if(!(ct % 10) && ct > 0 && !standby){
        standby = true;
        _gaq.push(['_trackEvent','video','view',_video_id,ct]);
        setTimeout(function(){standby = false}, 1000);
      }

      if(!_video_autoloop){
        if(this.currentTime >= (this.duration - 0.3 )){
          this.pause();
          video_object.unbind('play.afternoloop').bind('play.afternoloop', function() {
            video_object.unbind('play.afternoloop');
            this.currentTime = 0;
            this.play();
          });
        }
      }

    });

    video_object.bind('canplay', function() {
      //console.log('canplay');
    });

    video_object.bind('ended', function() {
       if (_video_autoloop) {
         ILLY.AUTOLOOP(this, true);
       }

      //console.log('ended');
      _gaq.push(['_trackEvent','video','end',_video_id]);
    });

    video_object.bind('playing', function() {
      //console.log('playing');
      _gaq.push(['_trackEvent','video','play',_video_id]);
    });
    
    if(_video_autoplay){
      /* refreshing controls bar */
      _player_tag.pause();
      _player_tag.play();
      /* /refreshing controls bar */
      _gaq.push(['_trackEvent','video','play',_video_id]);
    } else {
      /* se non c'è l'autoplay, mostro il pulsante PLAY */
      video_object.parent('.video-js-box').addClass('show_play_control');
    }

    video_object.bind('pause', function() {
      //console.log('pause');
    });

    video_object.bind('waiting', function() {
      //console.log('waiting');
    });

  };

   /* funzione per inviare il tracking a Google Analytics dal player Flash */
   ILLY.sendToGoogleFromFlash = function(google_pars){
     eval("_gaq.push(["+google_pars+"])");
   };


  /* video in overlay nei fragment HEAD-small_video_classic HEAD-medium_video_classic e HEAD-large_video_classic */
   ILLY.head_video_classic = function(){

	  jQuery('.visual_box_wr .head_video_thumbnail').each( function(){
	    jQuery(this).bind('click', function(){
        //jQuery('.corporate_footer_wr').hide();
		
	      var trigger = jQuery(this);
	      var video_id = trigger.attr('data-video-id');
	      var video_width = trigger.attr('data-videowidth');
	      var video_height = trigger.attr('data-videoheight');
	      var video_poster = trigger.attr('data-videoposter');
	      var video_poster_txt = trigger.attr('title');
	      var video_nome_mp4 = trigger.attr('data-videonome-mp4');
	      var video_nome_webm = trigger.attr('data-videonome-webm');
	      var video_nome_ogv = trigger.attr('data-videonome-ogv');
	      var video_wr = jQuery('#' + trigger.attr('data-video_wrapper'));
	      var video_autoplay = (trigger.attr('data-video-autoplay') == 'true')?'autoplay="autoplay"':'';
	      var video_autoplay_flash = trigger.attr('data-video-autoplay');
	      var video_autoloop = (trigger.attr('data-video-autoloop'))? 'loop="loop"' : '';
	      var video_autoloop_flash = trigger.attr('data-video-autoloop')? 'true' : 'false';
	      var video_controls = trigger.attr('data-video-controls');
	      var close_color = trigger.attr('data-close-color');
	      var full_page_mask = trigger.attr('full_page_mask')?eval(trigger.attr('full_page_mask')):false;
	
		  var qsflash = 'r='+ Math.random() +'&videoUrl='+video_nome_mp4+'&autoPlay='+video_autoplay_flash+'&loop='+video_autoloop_flash+'&videoID='+video_id+'&controlli='+video_controls;
		
	      var video_object_markup  = '\n<object id="'+video_id+'_object" class="vjs-flash-fallback" width="'+video_width+'" height="'+video_height+'" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" data="' + ILLY.SWF_PATH + 'player_video.swf?'+ qsflash +'">';
	          video_object_markup += '\n<param name="wmode" value="transparent" />';
	          video_object_markup += '\n<param name="movie" value="' + ILLY.SWF_PATH + 'player_video.swf?' + qsflash + '" />';
	          video_object_markup += '\n<param name="allowfullscreen" value="true" />';
	          video_object_markup += '\n<param name="allowScriptAccess" value="always" />';
	          video_object_markup += '\n<param name="flashVars" value="' + qsflash + '" />';
	          video_object_markup += '\n<img src="'+video_poster+'" width="'+video_width+'" height="'+video_height+'" alt="'+video_poster_txt+'" title="'+video_poster_txt+'" />';
			  video_object_markup += '<a href="http://get.adobe.com/it/flashplayer/" title="Get Adobe Flash Player"';
			  video_object_markup += 'target="_blank" border="0"><img src="http://www.adobe.com/macromedia/style_guide/images/160x41_Get_Flash_Player.jpg" /></a>';
	          
			  
			  video_object_markup += '\n</object>';
            
           // alert(video_object_markup);
         
	
	      var video_markup  = '<div class="video-js-box show-big-play">';
	          video_markup += '\n<video controls id="'+video_id+'_video" class="video-js" width="'+video_width+'" ' + video_autoloop + ' height="'+video_height+'" preload="auto" poster="'+video_poster+'" '+video_autoplay+' >';
	          video_markup += '\n<source src="'+video_nome_mp4+'" type=\'video/mp4; codecs="avc1.42E01E, mp4a.40.2"\' />';
	          video_markup += '\n<source src="'+video_nome_webm+'" type=\'video/webm; codecs="vp8, vorbis"\' />';
	          video_markup += '\n<source src="'+video_nome_ogv+'" type=\'video/ogg; codecs="theora, vorbis"\' />';
	          video_markup += video_object_markup;
	          video_markup += '\n</video>';
	          video_markup += '\n</div>';
            
           //console.log(video_markup);
	
	      var close_button_markup = '<a onclick="_gaq.push([\'_trackEvent\',\'video\',\'close\',\''+video_id+'\']);" href="javascript:void(0)" title="CLOSE" class="video_classic_close_button '+close_color+'"></a>';
	
	      video_wr.width(video_width);
	      video_wr.height(video_height);
	      var main_image = jQuery('.visual_image').eq(0);

        if(full_page_mask){
          video_wr.css({'position':'fixed' , 'top':parseInt((jQuery(window).height() - video_height)/2)});
          video_wr.css('right',parseInt((jQuery(window).width() - video_width)/2));
        } else {
          video_wr.css({'position':'absolute' , 'top':parseInt((main_image.height() - video_height)/2)});
          video_wr.css('right',parseInt((main_image.width() - video_width)/2));
        }
	      var video_mask = jQuery('.head_video_mask').eq(0);
	      video_mask.fadeIn();
	
	      video_wr.fadeIn();
	
	      var isIE = jQuery.browser.msie;
	
	      if (isIE) {
          //alert(video_object_markup);
	        video_wr.html(video_object_markup + close_button_markup);
	      } else {
	        video_wr.html(video_markup + close_button_markup);
          ILLY.video_listener(video_id+'_video',video_autoloop,eval(video_autoplay),video_controls);  /* params: _video_id,_video_autoloop,_video_autoplay, _show_controls */
	      }
	
	      if (!isIE) {
  	      //console.log(video_id + '_video');
	        var myPlayer = window.VideoJS.setup(video_id + '_video');
	      }
	
            /*
	      video_wr.find('a.video_classic_close_button').click(function(){
	        video_wr.fadeOut(function(){
	          video_wr.empty();
	          video_mask.fadeOut();
            
	        });
	      });
            */
            video_wr.find('a.video_classic_close_button').click(function(){
                video_wr.hide().empty();
	            video_mask.hide();
             });
            
	    });
	  });
	 }




  /* /video in overlay nei fragment HEAD-medium_video_classic e HEAD-large_video_classic */

  ILLY.set_player_in_page = function(video_id){
    var current_player = jQuery('#'+video_id);
    var _show_controls = current_player.attr('controls');
    var _video_autoplay = current_player.attr('autoplay');
    var _video_autoloop = current_player.attr('loop');
    if(jQuery.browser.mozilla){ _video_autoloop = current_player.attr('loop') != undefined }
    
    /* inserire la chiamata a videoJS *dopo* la definizione delle variabili e *prima* della chiamata a ILLY.video_listener */
    var myPlayer = VideoJS.setup(video_id);
    
    if (!jQuery.browser.msie) {
      ILLY.video_listener(video_id, _video_autoloop, _video_autoplay, _show_controls);
    }
    
    /* fix per garantire la visibilità della share bar su Internet Explorer 7 */
    if (jQuery.browser.msie) { jQuery('.share_bar_wr').css('zoom', 1) }
    
  }

/* overlay newsletter */

ILLY.set_newsletter_form = function(){
  /* attivo i controlli sui campi */
  $('#nl_email')
    .bind('focus', function() {
      if ($(this).val() == $(this).attr('placeholder')) {
        $(this).val('');
      }
    })
    .bind('blur', function() {
      if ($(this).val() == '') {
        $(this).val($(this).attr('placeholder'));
      }       
    })
  
    $('#nl_form').bind('submit', function(evt) {
      
    var errors = false, form = $('#nl_form');
    $('#nl_form').find('fieldset').removeClass('wrong');
             
    if (!/^^\w+([\.-]?\w+)*@\w+([\.-]?\w+)+(\.\w{2,4})+$/i.test($('#nl_email').val())) {
      $('#nl_email').closest('fieldset').addClass('wrong');
      errors = true;
    }
    
    /* per ogni blocco replicato qui va inserito il controllo se l'utente ha cliccato su agree
      se l'accettazione e' opzionale il controllo non e' necessario */         
    
    /* prima accettazione */
    if (!$('#nl_a1').is(':checked')) {
      $('#nl_a1').closest('fieldset').addClass('wrong');
      errors = true;
    }
  
    /* seconda accettazione */    
/*
    if (!$('#nl_a2').is(':checked')) {
      $('#nl_a2').closest('fieldset').addClass('wrong');
      errors = true;
    }
  */  
    if (!errors) {
/*
        $.get(form.attr('action'), form.serialize(), function() {
          form.closest('div').find('section').eq(0).hide();
          form.closest('div').find('section').eq(1).show();
        });
*/
var email = $("#nl_email").val();
            var url = "/ContactUs/newsletter/subscribe";
			var data = { "email" : email, "type" : "B00" };
			
			$.get(url, data, function(json) {
				if (json.success) {
					form.closest('div').find('section').eq(0).hide();
					form.closest('div').find('section').eq(1).show();
					_gaq.push(['_trackEvent', 'newsletter', 'subscribe']);
				} else if (json.error == "email") {
					$('#nl_email').closest('fieldset').addClass('wrong');
				}
			});

      }
      evt.preventDefault();
             
    });
}


/* /overlay newsletter */



/* Gallery in overlay */
  ILLY.layerManager = function(options) {
    
    var objlayer  = null,
      triggers  = options.triggers,
      
      open    = function(el, o) {
          
        var height    =  Math.max(document.documentElement.clientHeight, $('body').height()),
          layerHTML = '<div id="udclayer"><section class="overlayer"><div class="layercnt"><h2></h2></div></section></div>';
          
        if (objlayer) { close(); }
          
        if (0 === $('#udclayer').length) {
          $('body').append((typeof window.innerShiv === 'function')
            ? window.innerShiv(layerHTML, false)
            : layerHTML
          );
        }
          
        objlayer = $('#udclayer');
        $('#udclayer *').bind('click',function(evt){evt.stopPropagation()});
        objlayer.addClass(el.attr('class')).height(height);
          
        /**
         * Add close button
         */
        $('.layercnt').before($('<a href="#" class="closelayer">Close</a>'));
        $('.overlayer').css('marginTop', ($(window).scrollTop() + 30) + 'px');
        
        /**
         * Default title
         */
        $('.layercnt').find('h2').html(el.attr('title') || el.data('udctitle') || "");
          
        /**
         * Write something inside layer and pass the layer object
         */
        if ("function" === typeof o.preRender) {
          o.preRender(el, objlayer);
        };
          
          
        /**
         * set event to close layer after prerender (since it could be possible
         * inject into the layer others "close" button)
         */
        objlayer.find('.closelayer').bind('click.layer', function(evt) {
          evt.preventDefault();
          close();
        });
        
        
        
        /**
         * Finally show the layer
         */
        objlayer.show();

        /* close layer clicking on the objlayer */
        objlayer.bind('click',function(evt){
          evt.preventDefault();
          close(); 
        });
        
        /**
         * Esc button detection
         */
        $(document).bind('keyup.layer', function(evt) {
          if (evt.keyCode == 27) {
            evt.preventDefault();
            close();
          }    
        });
          
      },
      
      close = function() {
        /* abilito la navigazione del carousel tramite frecce <- e -> della tastiera al chiudersi dell'overlay */
        options.c_API.getConf().keyboard = true;

        $(document).unbind('.layer')
        objlayer.find('.closelayer').unbind('click.layer');
        objlayer.hide().remove();
        objlayer = null;
      };
      
    triggers.bind('click', function(evt) {
      evt.preventDefault();
      open($(this), options);
    }); 
  };



  /* Layer gallery */
  ILLY.appendSlideshow  = function(opt) {
    var carousel_API = opt.c_instance;
    var el = opt.trigger;
    var galleryHTML = '<section class="udcgallery layer">\
      <figure>\
        <img />\
      </figure>\
      <figcaption></figcaption>\
    </section>';
    
    $(opt.node).append((typeof window.innerShiv === 'function')
      ? window.innerShiv(galleryHTML, false)
      : galleryHTML
    );
    
    $(opt.node).find('.udcgallery').slideshowILLY({
      
      c_API           : carousel_API,
      
      trigger         : el,
              
      /**
       * URL to JSON resource
       * Check always your JSON validity with jsonlint (http://jsonlint.com/)
       */
      json            : el.data('udcslideshow-json'),
            
      /**
       * Title is already set on layer container
       */
      title           : opt.node.find('h2'),
      
      /**
       * Timeout in seconds.
       * If not defined, timeout is by default set to 5 seconds.
       */
      timeout         : el.data('udcslideshow-timeout') || 5,
      
      waitcnt         : $(opt.node),
      onInit          : opt.onInit,
      onTransition    : opt.onTransition
            
    });
      
    if ("function" === typeof opt.callback) { opt.callback(); }
    
  };

  /**
   * Asynchronous loader with deferred objects
   */
  ILLY.imageLoader = function(src, t) {
    
    var image   = $('<img />'),
      imageDFD  = $.Deferred(),
      timeout   = setTimeout(function() {
        image.trigger('error.imgloader')
      }, (t * 1000) || 5000),
      timeRequest;
        
      
    image
      .one('load.imgloader', function() {
        clearInterval(timeout);
        //console.log("loaded in %d seconds", ((new Date()).getTime() - timeRequest)/1000);
        imageDFD.resolve();
      })
      .bind('error.imgloader', function() {
        clearInterval(timeout);
        //console.log("failed");
        imageDFD.reject();
      })
      .attr('src', src);
      
    //timeRequest = (new Date()).getTime();
      
    if (image.get(0).complete) {
      setTimeout(function() {
        image.trigger('load.imgloader');
      }, 16);
    }
      
    return imageDFD.promise();  
  };

  /* photo slideshow */
  var Slideshow = function(s) {

    var _s = {
      url      : null,
      index    : 0,
      timeout    : 5,
      onInit     : null,
      onTransition : null,
        
      title : s.find('h2'),
      figure  : s.find('figure'),
      image : s.find('img'),
      caption : s.find('figcaption'),
      waitcnt : s,
        
      loader      : $('<div class="loadergallery"><span>Loading</span></div>'),
      triggerPrev   : $('<a href="#" class="prev disabled">Prev</a>'),
      triggerNext   : $('<a href="#" class="next">Next</a>')
    };
    
    var JSON    = { },
      JSONlength  = 0,
      busy    = false,
      hovered   = false;
      initCall  = false;
      loadercall  = null;
      
    
    var initTriggers  = function(index, c_API) {
      
      /* disabilito la navigazione del carousel tramite frecce <- e -> della tastiera all'aprirsi dell'overlay */
      c_API.getConf().keyboard = false;
      
      /* set gallery title */
      if (_s.title.length) {
        _s.title.html(JSON.title.toString())
      }
      
      $(_s.triggerPrev)
        .appendTo(_s.figure)
        .bind('click.udcgallery', function(evt) {
          $(this).blur();
          evt.preventDefault();
          if (!busy && _s.index > 1) {
            busy = true;
            showLoader(650);
            requestImage(-1);
          }           
        });
      
      $(_s.triggerNext)
        .appendTo(_s.figure)
        .bind('click.udcgallery', function(evt) {
          $(this).blur();
          evt.preventDefault();
          if (!busy && _s.index < JSONlength) {
            busy = true;
            showLoader(650);
            requestImage(1);
          }
        });


        /* touchwipe */
        $(_s.waitcnt).touchwipe({
          wipeLeft: function() { $(_s.triggerNext).trigger('click.udcgallery') },
          wipeRight: function() { $(_s.triggerPrev).trigger('click.udcgallery') },
          min_move_x: 20,
          min_move_y: 20,
          preventDefaultEvents: true
        });

      
      $(s).hover(
        function() {
          hovered = true;
          if (!busy) {
            if (ILLY.oldIE) {
              $(_s.figure).find('a:not(.disabled)').show();
            }
            else {
              $(_s.figure).find('a:not(.disabled)').fadeIn(300);
            }
          }
        },
        function() {
          if (ILLY.oldIE) {
            $(_s.figure).find('a').hide();
            hovered = false;
          }
          else {
            $(_s.figure).find('a').fadeOut(300, function() { hovered = false; })              
          }
        }
      );
      
      /* an image has been defined on a static gallery */
      if (_s.image.length && (_s.image.attr('src') || {}).length > 1) {
        hideLoaders();
        busy = false;
        _s.index = 1;
      }
      /* no fallback image or layer gallery */
      else {
        /* carico l'immagine puntata dal thumb cliccato */
        requestImage(index);
      }
      
    };
    
    var requestImage    = function(delta, extraTimeout) {
      
      var imageData, imageNode;

      imageData = JSON['images'][_s.index + delta - 1];
      imageNode = $('<img class="loading" />')
        .attr('src', imageData.url)
        .prependTo(_s.figure);
        
      
      /* waiting for image load, then fadeOut of old image */
      $.when(ILLY.imageLoader(imageData.url, _s.timeout + (extraTimeout || 0)))
        .done(function() {
          
          var clone;
          if (jQuery.browser.msie) {
                          clone = imageNode.clone();
                          clone.css({ position : "absolute", left: "-9999px", top: "-9999em", display : "block" }).appendTo($('body'));
                      }
          
          /* init call when gallery is called on a layer */
          if (!initCall) {
            initCall = true;
            if ("function" === typeof _s.onInit) { _s.onInit((clone || imageNode), JSON); }
          }
          else {
            if ("function" === typeof _s.onTransition) { _s.onTransition((clone || imageNode), JSON); }             
          }

          /* remove old image caption */
          if (_s.caption.length) { _s.caption.fadeOut().html(); };
          
          imageNode.fadeIn(300);
          _s.image.fadeOut(300, function() {
            _s.image.remove();
            imageNode.removeClass('loading');
            _s.image = imageNode;
            
            /* successfull load, increment index */
            _s.index += delta;
            
            _s.caption.empty();
            
            var caption_contents = '';

            /* set new optional image caption */
            if (_s.caption.length && imageData.caption.length) { caption_contents += imageData.caption};

            /* add optional MORE link */
            if(imageData.more_txt.length && imageData.more_url.length){
              caption_contents += '<span class="more_wr"><a href="' + imageData.more_url + '" class="red_button_link"';
              if(imageData.more_tgt.length){
                caption_contents += ' target="' + imageData.more_tgt + '"';
              }
              caption_contents += '>' + imageData.more_txt + '</a></span>';
            }

            if(caption_contents.length){
              _s.caption.html(caption_contents).fadeIn();
            }

            /* set new image alt */
            _s.image.attr('alt', imageData.alt || "");

            
            if (_s.index === 1) {
              _s.triggerPrev.addClass('disabled');
              if (hovered /* && s.hasClass('static')*/ ) {  _s.triggerPrev.hide(); }
            }
            else {
              _s.triggerPrev.removeClass('disabled');
              if (hovered /* && s.hasClass('static')*/) {  _s.triggerPrev.show(); }
            }
            
            if (_s.index === JSONlength) {
              _s.triggerNext.addClass('disabled');
              if (hovered /* && s.hasClass('static')*/) {  _s.triggerNext.hide(); }
            }
            else {
              _s.triggerNext.removeClass('disabled');
              if (hovered /* && s.hasClass('static')*/) { _s.triggerNext.show(); }
            }
            
            busy = false;
            hideLoader();
            
          })
        })
        .fail(function() {
          imageNode.remove();
          busy = false;         
          hideLoader();
          
        });
    };
      
      
    var showLoader    = function(time) {
      if (time) {
        loadercall = setTimeout(function() {
          clearInterval(loadercall);
          loadercall = null;
          if (ILLY.oldIE) { _s.loader.appendTo(_s.waitcnt).show(); }
          else { _s.loader.appendTo(_s.waitcnt).fadeIn(500); }
        }, time);
      }
      else {
        if (ILLY.oldIE) { _s.loader.appendTo(_s.waitcnt).show(); }
        else { _s.loader.appendTo(_s.waitcnt).fadeIn(500); }
      }
    };
    
    var hideLoader    = function() {
      if (!loadercall) {
        if (ILLY.oldIE) {
          _s.loader.hide().remove();
        }
        else {
          _s.loader.fadeOut(500, function() {
            _s.loader.remove();
          });         
        }
      }
      else {
        clearInterval(loadercall);
        loadercall = null;
      }
      
    };
    
    return {
      init    : function(el, options) {
        var ajaxObj;
        
        _s = $.extend(_s, options);
        
        showLoader();
        busy = true;
        
        if (!!_s.json ) {
          
          /* Call JSON Resource */
          var ajaxObj = new ILLY.ajax();
          ajaxObj.ajaxsend({
            url     : _s.json,
            dataType  : "json",
            timeout   : function() {
              hideLoader();
              busy = false;
              /* no JSON retrieved */             
            },
            
            success : function(data) {
              JSON = data;
              JSONlength = data.images.length;
              /* 
               * passo ad initTriggers l'indice della thumb cliccata per poter caricare nella slideshow il suo ingrandimento come immagine di partenza 
               * passo inoltre il riferimento all'API del carousel in modo da poterne disabilitare e riabilitare la navigazione tramite frecce mentre l'overlay è visibile
               */
              initTriggers(options.trigger.parent().index() + 1 , options.c_API);             
            }
          });
        }
        else {
          /* No JSON provided, we're asking for a single zoom image */
    
          JSON  = {
            "title"     : _s.trigger.attr('title'),
            "images"    : [
              {
                "url"       : _s.trigger.attr('href'),
                "alt"       : _s.trigger.find('img').attr('alt'),
                "caption"   : ""
              }
            ]
          };
          JSONlength = 1;
          _s.caption.addClass('empty')
          requestImage(1);
        }
        
        jQuery(document).bind('keyup', function(evt) {
          switch (evt.keyCode) {
            case 39: /* next */
              _s.triggerPrev.hide();
              _s.triggerNext.trigger('click').stop(true, true).fadeIn().fadeOut();
              break;
            case 37: /* prev */
              _s.triggerNext.hide();
              _s.triggerPrev.trigger('click').stop(true, true).fadeIn().fadeOut();
              break;
          }
        });

      }
      
    }
  
  }

  ILLY.ajax = function() {
    var timeout = null;
    
    var ajaxsend = function(opt) {

      ajaxstop(opt);
      ILLY.ajaxRequest = $.ajax({
        url     : opt.url,
        type    : opt.type || "GET",
        dataType  : opt.dataType || "html",
        data    : opt.data || null,
        success   : function(data, status) { (typeof opt.success === 'function')? opt.success(data, status) : $.noop() },
        error   : function(xhr, status, error) { (typeof opt.error === 'function')?  opt.error(xhr, status, error) : $.noop() },
        complete  : function() {
          ILLY.ajaxRequest = false;
          clearInterval(timeout);
        }
      });
      
      timeout = setTimeout(function() {
        ajaxstop();
        clearInterval(timeout);
        if (typeof opt.timeout === 'function') {
          opt.timeout();
        }
      }, (ILLY.ajaxTimeout * 1000));        
    };
    
    var ajaxstop = function() {
      if (!!ILLY.ajaxRequest) {
        ILLY.ajaxRequest.abort();
        ILLY.ajaxRequest = false;
      }
    }
    
    return {
      ajaxsend    : ajaxsend,
      ajaxstop    : ajaxstop
    }
  }

  $.fn.slideshowILLY = function(options) {
    if (this.length) {
      return this.each(function() {
        var obj = new Slideshow($(this));
        obj.init($(this), options);
        $.data(this, 'slideshow', obj);
      });
    }
    return this;
  };

/* /Gallery in overlay */
  
})(jQuery);






























jQuery(document).ready(function() {

  /* JAVASCRIPT FALLBACK
   * rimuovo la classe no_js dagli elementi a cui è associata
   * con la classe no_js definisco un namespace mediante il
   * quale gestire gli eventuali fallback per gli elementi che
   * debbano essere fruibili anche se javascript risultasse
   * disabilitato o non disponibile
   */
  jQuery('.no_js').removeClass('no_js');
  
  
  /* SUB MENU
   * mostro o nascondo i sub menù relativi alle varie sezioni
   * del sito evidenziando le voci del menù principale dinamicamente
   */
  /* i menù sono inizialmente tutti visibili e poi vengono nascosti via javascript */
  //jQuery('.sub_menu_list_wr').hide(); /* al momento lo sono da subito via css */
  
  /* creo l'attributo target="_blank" per tutti i link aventi classe 'external_link' e attributo href diverso dal neutro javascript:void(0) */
  jQuery('a.external_link').each(function() {
    var self = jQuery(this);
    if (self.attr('href') != 'javascript:void(0)') {
      self.attr('target', '_blank');
      return true;
    }
    else {
      return false;
    }
  });
  
  /* azioni associate ai links del menù principale */
  /* versione attivata al mouseover/mouseout */
 
  

 
  ILLY.OPEN_MAIN_MENU_EVENTS = (ILLY.IS_IPAD || ILLY.IS_IPHONE_OR_IPOD)?'touchstart':'mouseenter';
  ILLY.CLOSE_MAIN_MENU_EVENTS = (ILLY.IS_IPAD || ILLY.IS_IPHONE_OR_IPOD)?'touchend':'mouseleave';
  ILLY.TOUCH_CURRENT_VOICE = true;

  jQuery('.main_menu_list a').bind('click',function(evt){
    evt.preventDefault();
    evt.stopPropagation();
  });

 
  /* HOVER / ENTER */
  jQuery('.main_menu_list a').bind(ILLY.OPEN_MAIN_MENU_EVENTS,function(evt){
    
    /* blocco la scomparsa del menù corrente se passo dalla voce al submenù ad essa collegato */
    clearTimeout(ILLY.KEEP_THE_MENU_OPEN_HANDELR);
    
    /* wrapper li per la voce di menù */
    var my_wrapper = jQuery(this).parent();

    if(ILLY.IS_IPAD || ILLY.IS_IPHONE_OR_IPOD){
     if(my_wrapper.hasClass('main_menu_active_section')){
       ILLY.TOUCH_CURRENT_VOICE = true;
     } else {
       ILLY.TOUCH_CURRENT_VOICE = false;
     }
    }

    /* tolgo la classe che identifica l'hover su una voce di menù */
    jQuery('.main_menu_active_section').removeClass('main_menu_active_section');

    /* applico la classe che identifica l'hover sulla una voce di menù corrente */
    my_wrapper.addClass('main_menu_active_section');

    /* sub menù visibile al momento dell'hover sulla voce di menù */
    var old_sub_menu_current = jQuery('.sub_menu_current');

    /* se presente, chiudo il sottomenù aperto */
    if (old_sub_menu_current.size()) {
      old_sub_menu_current.removeClass('sub_menu_current').hide();
      jQuery('.sub_menu_band_wr_opened').removeClass('sub_menu_band_wr_opened');
    }

    /* apro il sottomenù relativo alla voce corrente */
    var new_sub_menu_current = jQuery('.' + jQuery(this).attr('rel'));
    if(new_sub_menu_current.length){
      new_sub_menu_current.addClass('sub_menu_current').show();
      jQuery('.sub_menu_band_wr').addClass('sub_menu_band_wr_opened');
    }
  });

  /* OUT / LEAVE */
  jQuery('.main_menu_list a').bind(ILLY.CLOSE_MAIN_MENU_EVENTS,function(){
    /* caching */
    var me = jQuery(this);

    /* wrapper li per la voce di menù */
    var my_wrapper = jQuery(this).parent();

    if(ILLY.IS_IPAD || ILLY.IS_IPHONE_OR_IPOD){
      if(ILLY.TOUCH_CURRENT_VOICE){
        my_wrapper.removeClass('main_menu_active_section');
      } else {
        return false;
      }
    }

    jQuery('.sub_menu_band_wr').removeClass('sub_menu_band_wr_opened');
    
    /* sub menù visibile al momento dell'hover sulla voce di menù */
    var old_sub_menu_current = jQuery('.sub_menu_current');

    /* attendo 0,1" prima di chiudere il menù relativo alla voce da cui sono uscito  */
    ILLY.KEEP_THE_MENU_OPEN_HANDELR = setTimeout(function() {
      my_wrapper.removeClass('main_menu_active_section');
      jQuery('.main_menu_active_section').removeClass('main_menu_active_section');
      if (old_sub_menu_current.size()) {
        old_sub_menu_current.removeClass('sub_menu_current').hide();
      }
    }, 100);
  });

  /* ENTER su SUBMENU' */
  jQuery('.sub_menu_band_wr').mouseenter(function(){
    clearTimeout(ILLY.KEEP_THE_MENU_OPEN_HANDELR);
    jQuery('.sub_menu_band_wr').addClass('sub_menu_band_wr_opened');
  });

  /* LEAVE su SUBMENU' */
  jQuery('.sub_menu_band_wr').mouseleave(function(){
    var old_sub_menu_current = jQuery('.sub_menu_current');
    ILLY.KEEP_THE_MENU_OPEN_HANDELR = setTimeout(function(){
      old_sub_menu_current.removeClass('sub_menu_current');
      jQuery('.sub_menu_band_wr').removeClass('sub_menu_band_wr_opened');
      jQuery('.main_menu_active_section').removeClass('main_menu_active_section');
      old_sub_menu_current.hide();
    },100);
  });



  /* versione attivata al click */
 /*
  jQuery('.main_menu_list a').click(function(event) {
    event.stopPropagation();

    // gestione dei link diretti privi di un sottomenù
    if (jQuery(this).hasClass('other_site_link')) {
      return;
    } // gestione dei link con sottomenù
    else {
      var my_wrapper = jQuery(this).parent();
      var old_sub_menu_current = jQuery('.sub_menu_current');
      var new_sub_menu_current = jQuery('.' + jQuery(this).attr('rel'));
      var is_already_current = new_sub_menu_current.hasClass('sub_menu_current');

      // se presente, chiudo il sottomenù aperto       
      if (old_sub_menu_current.size()) {
        old_sub_menu_current.removeClass('sub_menu_current');
        jQuery('.sub_menu_band_wr').removeClass('sub_menu_band_wr_opened');
        jQuery('.main_menu_active_section').removeClass('main_menu_active_section');
        old_sub_menu_current.hide();
      }

      // se non ho cliccato su una voce di menù già aperta, ne mostro il sottomenù
      if(!is_already_current){
        new_sub_menu_current.addClass('sub_menu_current');
        jQuery('.sub_menu_band_wr').addClass('sub_menu_band_wr_opened');
        my_wrapper.addClass('main_menu_active_section');
        new_sub_menu_current.show();
      }
    }
  });
*/

    /* old version with slide effect */
    /*
   jQuery('.main_menu_list a').click(function() {
    if (jQuery(this).attr('href') != 'javascript:void(0)') {
      return;
    }
    else 
      if (ILLY.IS_SUB_LOCKED) {
        return false;
      }
      else {
        ILLY.IS_SUB_LOCKED = true;
        var my_wrapper = jQuery(this).parents('li');
        var old_sub_menu_current = jQuery('.sub_menu_current');
        var new_sub_menu_current = jQuery('.' + jQuery(this).attr('rel'));
        var is_already_current = new_sub_menu_current.hasClass('sub_menu_current');
        
        if (old_sub_menu_current.size()) {
          old_sub_menu_current.slideToggle(ILLY.SLIDE_TIME, function() {
            old_sub_menu_current.toggleClass('sub_menu_current');
            jQuery('.sub_menu_band_wr').toggleClass('sub_menu_band_wr_opened');
            jQuery('.main_menu_active_section').removeClass('main_menu_active_section');
            if (is_already_current) {
              ILLY.IS_SUB_LOCKED = false;
              return false;
            }
            else {
              jQuery('.sub_menu_band_wr').toggleClass('sub_menu_band_wr_opened');
              my_wrapper.addClass('main_menu_active_section');
              new_sub_menu_current.slideToggle(ILLY.SLIDE_TIME, function() {
                new_sub_menu_current.toggleClass('sub_menu_current');
                ILLY.IS_SUB_LOCKED = false;
              });
            }
          });
        }
        else {
          jQuery('.sub_menu_band_wr').toggleClass('sub_menu_band_wr_opened');
          my_wrapper.addClass('main_menu_active_section');
          new_sub_menu_current.slideToggle(ILLY.SLIDE_TIME, function() {
            new_sub_menu_current.toggleClass('sub_menu_current');
            ILLY.IS_SUB_LOCKED = false;
          });
        }
      }
    });
  */
  
  /* chiudo il menù principale se si clicca al di fuori della sua area */
  jQuery('body').click(function() {
    if (!ILLY.IS_SUB_LOCKED && jQuery('.main_menu_active_section').size()) {
      jQuery('.main_menu_active_section a').click();
    }
  });
  
  /* chiudo il menù principale se si preme il pulsante esc */
  jQuery(document).keyup(function(e) {
    if (e.keyCode == '27' && jQuery('.main_menu_active_section').size()) {
      jQuery('.main_menu_active_section a').click();
    }
  });




    if ($('.homepage_overlay_wr').length) {
        var overlay_main_image = jQuery('#homepage_overlay_img')[0];
        if (ILLY.IS_IPAD || ILLY.IS_IPHONE_OR_IPOD) {
            
        }
    }
    else {
        ILLY.init_hp_carousel() /* se non vi è l'overlay, lancio direttamente l'inizializzazione dei carousel  */
    }
  
  /* apro in overlay il contenuto di un elemento in pagina il cui id è passato come valore per il parametro "overlayID" nella URL 
   * il parametro non deve essere necessariamente il primo
   */
  var overlay_content_id = ILLY.read_url_params(ILLY.OVERLAY_OBJECT_ID);
  
  /* verifico che sia valorizzato l'argomento passato a ILLY.read_url_params, che il suo valore corrisponda ad uno dei parametri presenti nell'URL della pagina ed infine che il valore ad esso associato coincida effettivamente con l'attributo ID di uno degli elementi in pagina */
  if (typeof(overlay_content_id) == 'string' && jQuery('#' + overlay_content_id).eq(0).size()) {
  
    var orig_object = jQuery('#' + overlay_content_id).eq(0);
    
    orig_object.clone().appendTo('.overlay_wr .content_wr').eq(0);
    
    orig_object.animate({
      opacity: 0.1
    }, 500, function() {
      // Animation complete.
    });
    
    jQuery('.overlay_wr').eq(0).overlay({
      mask: {
        color: '#000',
        loadSpeed: 200,
        opacity: 0.1
      },
      load: true,
      onBeforeLoad: function() {
		 alert('z')
        jQuery('.overlay_wr .content_wr').eq(0).addClass('mix');
      },
      onClose: function() {
        orig_object.animate({
          opacity: 1
        }, 500, function() {
          // Animation complete.
          if (jQuery.browser.msie) {
            this.style.removeAttribute('filter');
          }
        });
        jQuery('.overlay_wr .content_wr').eq(0).removeClass('mix').empty();
      }
    });
  }
  
  /* assegno a tutte le colonne (necessariamente di classe .same_height_column ) racchiuse in uno stesso contenitore di classe .same_height_columns_wr l'altezza della più alta */
  jQuery('.same_height_columns_wr').each(function() {
    var _max = 0;
    var cur_wr = jQuery(this);
    var _cur_h;
    cur_wr.find('.same_height_column').each(function() {
      _cur_h = jQuery(this).height();
      if (_cur_h > _max) {
        _max = _cur_h
      }
    });
    cur_wr.find('.same_height_column').height(_max);
  });
    
  /* funzionalità per iPad */
  if (ILLY.IS_IPAD || ILLY.IS_IPHONE_OR_IPOD) {
    jQuery('.language_selector_wr').click(function() {
      jQuery('.language_selector_list').slideToggle();
    });
  }
  
});



/* manage styled scrollbar */
(function($) {

    function init(el, s) {
        var hh;
        if (!!parseInt(s.extraHeight, 10)) {
            hh = el.height() + s.extraHeight;
        }
        else { 
            hh = el.height();
        }
        
        //alert(el.parent().height());
        //alert(hh);
        
        if (el.parent().height() < hh) {
            /* scrollbar */
            var scroller;
            
            scroller = (!!s.appendTo)
                    ? $('<ins class="scroller"><em></em></ins>').insertBefore(el)
                    : $('<ins class="scroller"><em></em></ins>').insertBefore(el.parent());
                    
            var dragger 	= scroller.find('em')
            var sh          = scroller.height();
            var ratio 		= hh / sh;
            
            //console.log(dragger)
            dragger
                .css({ height : (sh * sh / hh) + 'px' })
                .draggable({ 
                    axis 		: 'y',
                    containment	: 'parent',
                    drag		: function(evt, ui) {
                        var offsettop = ui.position.top;
                        el.css('top', -(offsettop * ratio)  +'px')
                    }
                });
                
            
            if (!!s.withHandlers) {
                tag = s.tagHandler || 'a href="#" ';
                
     
                $('<' + tag + ' class="scroller scrollup">&#9650;</'+ tag +'>')
                .insertBefore(scroller)
                .bind('mousenter, click', function(evt) {
                    var top = dragger.position().top, amount = top;

                    amount += (top >= 10)? -10 : -top;
                    dragger.css('top', amount + 'px');
                    el.css('top', -amount * ratio +'px')
                    evt.preventDefault()
                });
                
                $('<' + tag + ' class="scroller scrolldw">&#9660;</'+ tag +'>')
                .insertAfter(scroller)
                .bind('mouseenter, click', function(evt) {
                    var top = dragger.position().top, h = dragger.height(), amount = top;
                    
                    amount += (top + h <= scroller.height() - 10)? 10 : scroller.height() - (top + h);
                    dragger.css('top', amount + 'px');
                    el.css('top', -amount * ratio +'px')
                    evt.preventDefault()
                })
                
            }
        };
    }
    
    
    $.fn.customScroll = function(options) {
        var settings = $.extend({ }, options); 
        this.each(function(i, el) {
            setTimeout(function() { init($(el), settings); }, 30);
        });
        return this;
    }


}(jQuery));


$(document).ready(function() {
	
	/* fix video autoplay */
	var video = $('video');
    if (!$.browser.msie) {
        video.each(function() {
            if (!!this.autoplay) {           
                this.play();
            }
        });
    };
        
        
    /* flash detection */
    /*
    var v = parseInt($.flash.version.major, 10), ob, einst = "";
    if (v < 11 && !!$.browser.msie) {
        ob = $('object');
        ob.each(function() {
            $(this).attr('data', einst)
        })
    }
    */
        
        
    	
	/* open layer flash */
	$('.openflashlayer').bind('click', function(evt) {
		
		var h = Math.max(document.documentElement.clientHeight, $('body').height());		
    //console.log('xmlPath: ' + $(this).data('swf-xmlpath') + '; imagesPath: ' + $(this).data('swf-imgpath') + '; urlHome: ' + $(this).data('swf-urlHome'));
		var $this = $(this),
			fv = $.flash.create({
				swf		: $this.attr('href'),
				wmode	: "transparent",
				height	: $this.data('swf-height'),
				width	: $this.data('swf-width'),
				play	: true,
				flashvars	: {
					xmlPath  		: $this.data('swf-xmlpath') || "",
					imagesPath  : $this.data('swf-imgpath')	|| "",
					urlHome  	  : $this.data('swf-urlHome')	|| ""
				}
			});
		
		var w = parseInt($this.data('swf-width'), 10);

		
		if ($('#layerflashblack').length && $('#layerflash').length) {
			$('#layerflashblack').css('height', h).show();
			$('#layerflash').find('header').css('width', (w - 2) + 'px')
			
			$('#layerflash').find('.closelayer').bind('click', function(evt) {
				$('#layerflashblack').hide();
				$('#layerflash').hide();
				$('#layerflash div').empty();
				$(this).unbind('click');
				evt.preventDefault();
			})
			
			if (!!$.flash.available) {			
				$('#layerflash div').html(fv);
				$('#layerflash').css({
					height		: $this.data('swf-height') + 'px'
				});				
			};
			
			$('#layerflash').css({
				top			: ($(window).scrollTop() + 20) + 'px',
				width 		: $this.data('swf-width') + 'px',
				marginLeft 	: (w / -2) + 'px'
			}).show();
			
			
			
			
		}
		
		
		/*
		  var so = new SWFObject("/wps/wcm/resources/artcollection_swf/home.swf", "artcoll", "724", "580", "8", "#FFFFFF", true);
	    so.addVariable("allowResize", ""+e+"");
        so.addParam("wmode", "transparent");
	    so.addVariable("xmlPath", "/wps/wcm/resources/artcollection_swf/catalogo.xml");
	    so.addVariable("imagesPath", "/wps/wcm/resources/artcollection_swf/images");
	    so.setAttribute("useExpressInstall",false);
	    //so.setAttribute("redirectUrl","/wps/wcm/resources/artcollection_swf/updateFlash.php");
	    so.write("contenitore_ac");
		*/
		evt.preventDefault();
	})
});




(function($) {

$.fn.deferredImageLoader = function(imgCallback, to) {
        
  var dfd = $.Deferred(),
      imgLength = this.length,
      loaded = [],
      failed = [],
      timeout = to || 10000;
      
  if (imgLength) {
      
      this.each(function() {
          var i = this;
          
          /* single image load */
          $.when(
              (function asyncImageLoader() {
                  var
                  /**
				  * This interval bounds the maximum amount of time (e.g. network
				  * excessive latency or failure, 404) before triggering the error
				  * handler for a given image. The interval is then unset when
				  * the image has loaded or if error event has been triggered.
				  */
                  intv = setTimeout(function() { $(i).trigger('error.defimgloader') }, timeout),
                  imageDfd = $.Deferred();
                  
                  /* single image main events */
                  $(i).one('load.defimgloader', function() {
                          clearInterval(intv);
                          imageDfd.resolve();
                      })
                      .bind('error.defimgloader', function() {
                          clearInterval(intv);
                          imageDfd.reject();
                      }).attr('src', i.src);
                  
                  if (i.complete) {
                      setTimeout(function() {
                          $(i).trigger('load.defimgloader');
                      }, 10);
                  }
                  
                  return imageDfd.promise();
              }())
          )
          .done(function() {
              loaded.push(i.src);
              if (typeof imgCallback === 'function') { imgCallback($(i)); }
			  imgLength = imgLength - 1;
              if (imgLength === 0) {
                  if (failed.length) {
                      dfd.reject(failed);
                  }
                  else {
                      dfd.resolve();
                  }
              }
		  })
          .fail(function() {
              failed.push(i.src);
			  imgLength = imgLength - 1;
              if (imgLength === 0) {
                  if (failed.length) {
                      dfd.reject(failed);
                  }
                  else {
                      dfd.resolve();
                  }
              }
		  })
      })
  }
  return dfd.promise();
};

}(jQuery));



//var _ILLYCOMVIDEO;


$(document).ready(function(){

    /* clono i nomi delle tab all'interno dei div dei contenuti ad esse associati in modo che possano essere stampati */
    if (jQuery('.item_tabs').size()) {
      jQuery('.item_tabs').each(function() {
        var this_tab_voices_wr = jQuery(this);
        var this_tab_panels_wr = this_tab_voices_wr.next('.container_pannelli_tabs');
        this_tab_voices_wr.find('li').each(function() {
          var this_tab_voice = jQuery(this);
          var this_tab_panel = this_tab_panels_wr.find('div').eq(this_tab_voice.index()); 
          this_tab_panel.prepend('<h3 class="print_only">' + this_tab_voice.find('a').text() + '</h3>');
        });
      });
    }
    /* clono i nomi delle tab all'interno dei div dei contenuti ad esse associati in modo che possano essere stampati */
   
    /* clono il logo illy rendendolo disponibile per la versione stampabile */
    jQuery('body').prepend('<img class="print_only" src="'+ILLY.LOGO_IMAGE_TO_PRINT_PATH+'" />');
    /* /clono il logo illy rendendolo disponibile per la versione stampabile */


    /* video js */
    //_ILLYCOMVIDEO = VideoJS.setup("All");
   
    /* gestione sticky su Ipad */
    if (!ILLY.IS_IPAD) return false;
    

    var video = $('video');
    video.each(function() {
        $(this).attr('controls', 'true');
    });   
    
});


function autoResize(ifr){
    var innerDoc = (!!ifr['contentDocument']) ? ifr.contentDocument : ifr.contentWindow.document;
    var newheight = innerDoc.body.scrollHeight;
    ifr.style.height = newheight + "px";
    
}

