// JavaScript Document
var Zanolli = {

  DOMready: function () {

    // suffissi usati per gestire lo ZOOM delle immagini
    imgSuffixZoom = '_detailZ';
    imgSuffixBig = '_detailB';

    if ($('img').length > 0) { Zanolli.lazy() }
    if ($('.popup').length > 0) { Zanolli.popup() }
    if ($('.popup-prenota').length > 0) { Zanolli.popupPrenota() }
    if ($('#slider').length > 0) { Zanolli.slider() }
    if ($('#contenuto-carrello').length > 0) { Zanolli.showCarrello() }
    if ($('.tabella-numero').length > 0) { Zanolli.tabellaNumero() }
    if ($('.scroll').length > 0) { Zanolli.scrollPane() }
    if ($('#player').length > 0) { Zanolli.videoPlayer('player', '../../swf/flowplayer-3.2.0.swf') }
    if ($('.open').length > 0) { Zanolli.createBtnOpen('.open') }
    if ($('ul.gallery').length > 0) { Zanolli.createGallery() }
    if ($('.slide').length > 0) { Zanolli.slideCatalogo() }
    if ($('.carrello-loader').length > 0) { Zanolli.carrelloLoader() }
    if ($('.tip').length > 0) { Zanolli.toolTip() };
    if ($('#prod-cont .paginazione').length > 0) { Zanolli.Ajax() };
    if ($('#prod-cont').length > 0) { Zanolli.imgCatalogoLoad() };
    if ($("p[rel*='traccia-contatti']").length > 0) { Zanolli.TracciamentoAnalytics('inviata-contatti-' + lingua + '.html') }
    if ($("p[rel*='traccia-prenotazione']").length > 0) { Zanolli.TracciamentoAnalytics('inviata-prenotazione-' + lingua + '.html') }

  }, // fine DOMReady

  lazy: function () {
    $('img').lazyload();
  }, // fine lazyLoad

  Ajax: function () {
    $('.paginazione .indietro .btn').click(function () { Zanolli.GetHtmlCode($('.paginazione .indietro .btn').attr("rel")); return false; });
    $('.paginazione .avanti .btn').click(function () { Zanolli.GetHtmlCode($('.paginazione .avanti .btn').attr("rel")); return false; });
  }, // fine Ajax

  GetHtmlCode: function (urlRequest) {
    Zanolli.DoAjaxCall(urlRequest);
  }, // fine GetHtmlCode

  DoAjaxCall: function (the_request) {
    var request = null;
    if (window.XMLHttpRequest)
      request = new XMLHttpRequest();
    else if (window.ActiveXObject)
      request = new ActiveObject("Microsoft.XMLHTTP");
    if (request) {
      request.open("GET", the_request);
      request.onreadystatechange = function () {
        if (request.readyState == 4) {
          document.getElementById('prod-cont').innerHTML = request.responseText;
          Zanolli.scrollPane();
          Zanolli.slideCatalogo();
          Zanolli.Ajax();
          Zanolli.imgCatalogoLoad();
          if ($('#briciole .last-briciola').length > 0 && $('h1.cat-title').length > 0 && $('#titolo-cat2').length > 0) {
            $('#briciole .last-briciola').text($('#titolo-cat2').attr('value'));
            $('h1.cat-title').text($('#titolo-cat2').attr('value'));
          }
        }
      }
      request.send(null);
    }
  }, // fine DoAjaxCall

  slider: function () {
    $('#slider').nivoSlider({
      effect: 'fade',
      slices: 15,
      animSpeed: 500,
      pauseTime: 5000,
      directionNav: false, //Next & Prev
      directionNavHide: true, //Only show on hover
      controlNav: true, //1,2,3...
      keyboardNav: true, //Use left & right arrows
      pauseOnHover: true, //Stop animation while hovering
      manualAdvance: false, //Force manual transitions
      captionOpacity: 0.8, //Universal caption opacity
      beforeChange: function () { },
      afterChange: function () { },
      slideshowEnd: function () { } //Triggers after all slides have been shown
    });
  }, // fine slider

  showCarrello: function () {

    $('#contenuto-carrello').hide();

    $("#dati-carrello").hover(
			function () {
			  $('#contenuto-carrello').show();
			},
			function () {
			  $('#contenuto-carrello').hide();
			}
		);

  },

  scrollPane: function () {
    $('.scroll').jScrollPane({ scrollbarWidth: 5, scrollbarMargin: 8 })
  }, // fine ScrollPane


  flashInclude: function (obj, swfFile) {
    $(obj).flash(
		{
		  // test.swf is the flash document 
		  swf: swfFile,
		  id: "movie",
		  name: "movie",
		  width: 800,
		  height: 450,
		  wmode: 'transparent',
		  expressInstaller: 'swf/expressInstall.swf', // optional and temporary	
		  flashvars:
				{
				// VARS
		}
		})

  }, // fine flashInclude

  videoPlayer: function (obj, swfFile) {
    flowplayer(
			obj, { src: swfFile, wmode: 'transparent' },
			{
			  play: { replayLabel: '', replayButton: 'none' },

			  clip: {
			    onStart: function () {
			      if ($('#testo').css('right') > "-325px")
			        Zanolli.showHideText()
			    },
			    onFinish: function () {
			      this.getPlugin("play").hide();
			    }
			  },
			  plugins: {
			    // change default skin to "tube"
			    controls: {
			      url: 'flowplayer.controls.swf',

			      backgroundColor: "transparent",
			      backgroundGradient: "none",
			      sliderColor: '#FFFFFF',
			      sliderBorder: '1px solid rgba(160,160,160,0.7)',
			      volumeSliderColor: '#FFFFFF',
			      volumeBorder: '1px solid rgba(160,160,160,0.7)',

			      timeColor: '#ffffff',
			      durationColor: '#333333',

			      tooltipColor: 'rgba(255, 255, 255, 0.7)',
			      tooltipTextColor: '#333333'
			    }
			  }
			});
  }, // fine videoPlayer

  createBtnOpen: function (obj) {
    var el = $(obj);
    var btnOpen = '<a id=\"btnScroll\" class=\"apri\" title=\"Apri/Chiudi\">Apri/Chiudi</a>';
    // inietto il BTN nel div TESTO e gli asocio
    $(el).append(btnOpen);
    // Posiziono il pulsante Apri/Chiudi se ho la barra di scroll o meno
    var x = ($('.jScrollPaneTrack').length == 0) ? '0' : '-5px'
    $('#btnScroll').css('left', x)

    $('#btnScroll').click(function () {
      Zanolli.showHideText();
    });

  }, // fine createBtnOpen

  showHideText: function () {
    var testo = $('#testo');
    var scrollBar = $('.jScrollPaneTrack');
    var position = testo.css('right') == "0px" ? "-325px" : "0px"; // controllo se il div #testo è a right=0 o -321px

    $(testo).animate({
      right: position
    },
			800,
			function () {
			  // Animation complete.
			  $('#btnScroll').toggleClass("apri");
			  if (position == "0px")
			    $(scrollBar).show();
			  else
			    $(scrollBar).hide();
			}
		)

  }, // fine showObj

  createGallery: function () {
    //Get our elements for faster access and set overlay width
    var div = $('div.gallery');
    ul = $('ul.gallery');
    ulPadding = 0;
    //Get menu width
    var divWidth = div.width();
    //Remove scrollbars	
    div.css({ overflow: 'hidden' });
    //Find last image container
    var lastLi = ul.find('li:last-child');
    //When user move mouse over menu
    div.mousemove(function (e) {
      //As images are loaded ul width increases, so we recalculate it each time
      var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;
      var left = (e.pageX - div.offset().left) * (ulWidth - divWidth) / divWidth;
      div.scrollLeft(left);
    });

    // thumbnails
    Zanolli.thumb();

    // Zoom img
    Zanolli.zoom();
  },

  zoom: function () {
    //$('#set-immagini').nivoZoom();

    var zoom = $('.zoom'); // tag A contenente l'immagine da ingrandire
    var state = false;
    var loader = '<img id="loader" src="http://www.zanolli.com/img/loader.gif" alt="Caricamento Immagine" width="24" height="24" />' // immagine che inietto nel DOM durante il carcamento dell'IMG ZOOM

    zoom[0].onclick = function () {
      href = this.getAttribute('href');

      if (!state) {
        w = 800;
        h = 536;
        href = href;
        title = 'Clicca per chiudere';
        state = true;
        $('#fotografie').css('display', 'none');
      }
      else {
        w = 400;
        h = 268;
        href = href.replace(imgSuffixZoom, imgSuffixBig);
        title = 'Clicca per ingrandire';
        state = false;
        $('#fotografie').css('display', 'block');
      }

      // cambio le dimensioni dell'IMG e cambio l'attributo SRC se faccio ZOOM o rimpicciolisco
      $('.zoom img.immagine').animate(
			{
			  width: w,
			  height: h
			}, 1000, function () {
			  var imgZoom = $('.zoom img');

			  $('.zoom').append(loader); // inserisco nel DOM nell'elemento .zoom un immagine che fa da loader
			  $('.zoom').attr('title', title);

			  imgZoom.attr('src', href);

			  imgZoom.load(function () {
			    $('#loader').remove();
			  });
			});

      return false;
    }

  },

  thumb: function () {
    var anchors = $('.thumb');
    for (var i = 0; i < anchors.length; i++) {

      var anchorObj = anchors[i];
      anchorObj.onclick = function () {

        var href = this.getAttribute('href');
        $('.immagine').attr('src', href);
        $('.zoom').attr('href', href.replace(imgSuffixBig, imgSuffixZoom));

        return false;
      }
    }
  },

  slideCatalogo: function () {
    var img = $('img.media');
    var testo = $('.jScrollPaneContainer');
    var stopScroll;
    //
    var imgWidth = img.width();
    var testoWidth = testo.width();
    //
    Zanolli.createBtnOpen('.slide');

    /*img.ready(function ()
    {
    Zanolli.showHideText();
						
    $('#testo').mouseenter(function(e) {stopScroll=true})
    $('#testo').mouseleave(function(e) {stopScroll=false})

    $('.cols-6').mousemove(function(e) {
					
    left = -(e.pageX - img.offset().left);//(testoWidth - imgWidth) / imgWidth;
    //if (!stopScroll)
    $('.jScrollPaneContainer').css('right', -left);
					
    });
			
    });
    */
    //When user move mouse over DIV.cols-6

  },

  imgCatalogoLoad: function () {
    $('.media').load(function () { Zanolli.showHideText(); })
  },

  carrelloLoader: function () {
    var altezza = $('table.carrello-elenco').height();
    $('.carrello-loader').css('height', altezza)
    $('.carrello-loader').css('opacity', 0.5)
  }, // fine popup

  toolTip: function () {
    $('.tip').aToolTip({ xOffset: -115 });
  },

  popup: function () {
    $('.popup').colorbox({ iframe: true, innerWidth: 650, innerHeight: 450 })
  }, // fine popup

  popupPrenota: function () {
    $('.popup-prenota').colorbox({ iframe: true, innerWidth: 650, innerHeight: 450 })
  }, // fine popupPrenota

  controlForm: function () {
    if ($(".errore").length > 0) {
      $(".errore").click(function () {
        $(this).slideUp();
      });
    }
  },

  tabellaNumero: function () {
    $('table.tabella-numero tbody tr:even td').addClass('even');
    $('table.tabella-numero tbody tr:even th').addClass('even');
  }, // fine tabellaNumero

  TracciamentoAnalytics: function (pagina) {
    try {
      var pageTracker = _gat._getTracker('UA-20283935-1');
      pageTracker._trackPageview(pagina);
    }
    catch (err) { }
  }

} // fine var Zanolli

$(document).ready(function() { Zanolli.DOMready() });


