//imposta target _blank ai link esterni
function linkext(){$("a.ext").each(function(){$(this).attr({target:"_blank",title:$(this).attr("title")+" (link esterno, si apre in una nuova finestra)"})});$("a.pdf").each(function(){$(this).attr({target:"_blank",title:$(this).attr("title")+"Scarica il pdf (link esterno, si apre in una nuova finestra)"})})};

//hoverIntent by Brian Cherne
(function(a){a.fn.hoverIntent=function(k,j){var l={sensitivity:7,interval:100,timeout:0};l=a.extend(l,j?{over:k,out:j}:k);var n,m,h,d;var e=function(f){n=f.pageX;m=f.pageY};var c=function(g,f){f.hoverIntent_t=clearTimeout(f.hoverIntent_t);if((Math.abs(h-n)+Math.abs(d-m))<l.sensitivity){a(f).unbind("mousemove",e);f.hoverIntent_s=1;return l.over.apply(f,[g])}else{h=n;d=m;f.hoverIntent_t=setTimeout(function(){c(g,f)},l.interval)}};var i=function(g,f){f.hoverIntent_t=clearTimeout(f.hoverIntent_t);f.hoverIntent_s=0;return l.out.apply(f,[g])};var b=function(q){var o=(q.type=="mouseover"?q.fromElement:q.toElement)||q.relatedTarget;while(o&&o!=this){try{o=o.parentNode}catch(q){o=this}}if(o==this){return false}var g=jQuery.extend({},q);var f=this;if(f.hoverIntent_t){f.hoverIntent_t=clearTimeout(f.hoverIntent_t)}if(q.type=="mouseover"){h=g.pageX;d=g.pageY;a(f).bind("mousemove",e);if(f.hoverIntent_s!=1){f.hoverIntent_t=setTimeout(function(){c(g,f)},l.interval)}}else{a(f).unbind("mousemove",e);if(f.hoverIntent_s==1){f.hoverIntent_t=setTimeout(function(){i(g,f)},l.timeout)}}};return this.mouseover(b).mouseout(b)}})(jQuery);

//Superfish v1.4.8 - jQuery menu widget Copyright (c) 2008 Joel Birch licensed under the MIT and GPL licenses
(function(b){b.fn.superfish=function(k){var g=b.fn.superfish,j=g.c,f=b(['<span class="',j.arrowClass,'"> &#187;</span>'].join("")),i=function(){var c=b(this),l=d(c);clearTimeout(l.sfTimer);c.showSuperfishUl().siblings().hideSuperfishUl()},e=function(){var c=b(this),m=d(c),l=g.op;clearTimeout(m.sfTimer);m.sfTimer=setTimeout(function(){l.retainPath=(b.inArray(c[0],l.$path)>-1);c.hideSuperfishUl();if(l.$path.length&&c.parents(["li.",l.hoverClass].join("")).length<1){i.call(l.$path)}},l.delay)},d=function(c){var l=c.parents(["ul.",j.menuClass,":first"].join(""))[0];g.op=g.o[l.serial];return l},h=function(c){c.addClass(j.anchorClass).append(f.clone())};return this.each(function(){var c=this.serial=g.o.length;var m=b.extend({},g.defaults,k);m.$path=b("li."+m.pathClass,this).slice(0,m.pathLevels).each(function(){b(this).addClass([m.hoverClass,j.bcClass].join(" ")).filter("li:has(ul)").removeClass(m.pathClass)});g.o[c]=g.op=m;b("li:has(ul)",this)[(b.fn.hoverIntent&&!m.disableHI)?"hoverIntent":"hover"](i,e).each(function(){if(m.autoArrows){h(b(">a:first-child",this))}}).not("."+j.bcClass).hideSuperfishUl();var l=b("a",this);l.each(function(n){var o=l.eq(n).parents("li");l.eq(n).focus(function(){i.call(o)}).blur(function(){e.call(o)})});m.onInit.call(this)}).each(function(){var c=[j.menuClass];if(g.op.dropShadows&&!(b.browser.msie&&b.browser.version<7)){c.push(j.shadowClass)}b(this).addClass(c.join(" "))})};var a=b.fn.superfish;a.o=[];a.op={};a.IE7fix=function(){var c=a.op;if(b.browser.msie&&b.browser.version>6&&c.dropShadows&&c.animation.opacity!=undefined){this.toggleClass(a.c.shadowClass+"-off")}};a.c={bcClass:"sf-breadcrumb",menuClass:"sf-js-enabled",anchorClass:"sf-with-ul",arrowClass:"sf-sub-indicator",shadowClass:"sf-shadow"};a.defaults={hoverClass:"sfHover",pathClass:"overideThisToUse",pathLevels:1,delay:800,animation:{opacity:"show"},speed:"normal",autoArrows:true,dropShadows:true,disableHI:false,onInit:function(){},onBeforeShow:function(){},onShow:function(){},onHide:function(){}};b.fn.extend({hideSuperfishUl:function(){var e=a.op,d=(e.retainPath===true)?e.$path:"";e.retainPath=false;var c=b(["li.",e.hoverClass].join(""),this).add(this).not(d).removeClass(e.hoverClass).find(">ul").hide().css("visibility","hidden");e.onHide.call(c);return this},showSuperfishUl:function(){var e=a.op,d=a.c.shadowClass+"-off",c=this.addClass(e.hoverClass).find(">ul:hidden").css("visibility","visible");a.IE7fix.call(c);e.onBeforeShow.call(c);c.animate(e.animation,e.speed,function(){a.IE7fix.call(c);e.onShow.call(c)});return this}})})(jQuery);

//jquery.paginator.js @author Gabriel Birke Modified by Carlo Tasca
function createCookie(c,d,e){if(e){var b=new Date();b.setTime(b.getTime()+(e*24*60*60*1000));var a="; expires="+b.toGMTString()}else{var a=""}document.cookie=c+"="+d+a+"; path=/"}function readCookie(b){var e=b+"=";var a=document.cookie.split(";");for(var d=0;d<a.length;d++){var f=a[d];while(f.charAt(0)==" "){f=f.substring(1,f.length)}if(f.indexOf(e)==0){return f.substring(e.length,f.length)}}return null}function eraseCookie(a){createCookie(a,"",-1)}jQuery.fn.pagination=function(a,b){b=jQuery.extend({items_per_page:10,num_display_entries:10,current_page:0,num_edge_entries:0,link_to:"#",prev_text:"Prev",next_text:"Next",ellipse_text:"...",prev_show_always:true,next_show_always:true,page_x_of_y:true,xofy_left:true,xofy_right:false,callback:function(){return false}},b||{});return this.each(function(){function f(){return Math.ceil(a/b.items_per_page)}function h(){var k=Math.ceil(b.num_display_entries/2);var l=f();var j=l-b.num_display_entries;var m=g>k?Math.max(Math.min(g-k,j),0):0;var i=g>k?Math.min(g+k,l):Math.min(b.num_display_entries,l);return[m,i]}function e(j,i){g=j;c();var k=b.callback(j,d);if(!k){if(i.stopPropagation){i.stopPropagation()}else{i.cancelBubble=true}}return k}function c(){var p=readCookie("px");if(!p){p=0}d.empty();var k=h();var o=f();var q=function(i){return function(r){return e(i,r)}};var n=function(i,r){i=i<0?0:(i<o?i:o-1);r=jQuery.extend({text:i+1,classes:""},r||{});if(i==g){var s=jQuery("<span class='current'>"+(r.text)+"</span>")}else{var s=jQuery("<a>"+(r.text)+"</a>").bind("click",q(i)).attr("href",b.link_to.replace(/__id__/,i))}if(r.classes){s.addClass(r.classes)}d.append(s)};if(b.page_x_of_y&&b.xofy_left&&!b.xofy_right){d.append('<div class="pxofy">page '+parseInt(g+1)+" of "+f()+"</div>")}if(b.prev_text&&(g>0||b.prev_show_always)){n(g-1,{text:b.prev_text,classes:"prev"})}if(k[0]>0&&b.num_edge_entries>0){var j=Math.min(b.num_edge_entries,k[0]);for(var l=0;l<j;l++){n(l)}if(b.num_edge_entries<k[0]&&b.ellipse_text){jQuery("<span>"+b.ellipse_text+"</span>").appendTo(d)}}for(var l=k[0];l<k[1];l++){n(l)}if(k[1]<o&&b.num_edge_entries>0){if(o-b.num_edge_entries>k[1]&&b.ellipse_text){jQuery("<span>"+b.ellipse_text+"</span>").appendTo(d)}var m=Math.max(o-b.num_edge_entries,k[1]);for(var l=m;l<o;l++){n(l)}}if(b.next_text&&(g<o-1||b.next_show_always)){n(g+1,{text:b.next_text,classes:"next"})}if(b.page_x_of_y&&b.xofy_right&&!b.xofy_left){d.append('<div class="pxofy">page '+parseInt(g+1)+" of "+a+"</div>")}}var g=b.current_page;a=(!a||a<0)?1:a;b.items_per_page=(!b.items_per_page||b.items_per_page<0)?1:b.items_per_page;var d=jQuery(this);this.selectPage=function(i){e(i)};this.prevPage=function(){if(g>0){e(g-1);return true}else{return false}};this.nextPage=function(){if(g<f()-1){e(g+1);return true}else{return false}};c();b.callback(g,this)})};jQuery.fn.paginator=function(settings){var current=this;settings=jQuery.extend({paginatorId:current,paginatorClass:"pagination",paginatorContentId:"paginator_content",itemsPerPage:1,totalEntries:10,currentPage:0,totalEdgeEntries:2,prevText:"PREV",nextText:"NEXT",ellipseText:"...",showPrev:true,showNext:true,showPageXofY:true,xofyLeft:true,xofyRight:false,elementModel:["<div><h1>{0}</h1></div>"],postUrl:"",fieldnames:["type","name"],modelFieldNames:{"modelFieldNames[]":settings.fieldnames}},settings||{});if(settings.xofyLeft&&settings.xofyRight){alert("Warning: xofyLeft and xofyRight are both true.")}function _jqueryPaginator(){function setPaginatorData(datatext){var natordata=eval(datatext);function getPaginatorOptions(){var opt={callback:selectedPageNumCallback,items_per_page:settings.itemsPerPage,num_display_entries:settings.totalEntries,current_page:settings.currentPage,num_edge_entries:settings.totalEdgeEntries,prev_text:settings.prevText,next_text:settings.nextText,ellipse_text:settings.ellipseText,prev_show_always:settings.showPrev,next_show_always:settings.showNext,page_x_of_y:settings.showPageXofY,xofy_left:settings.xofyLeft,xofy_right:settings.xofyRight};var htmlspecialchars={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"};jQuery.each(htmlspecialchars,function(k,v){opt.prev_text=opt.prev_text.replace(k,v);opt.next_text=opt.next_text.replace(k,v)});return opt}function selectedPageNumCallback(page_index,jq){createCookie("px",page_index,1);var items_per_page=settings.itemsPerPage;var max_elem=Math.min((page_index+1)*items_per_page,natordata[0].length);var newcontent="";for(var i=page_index*items_per_page;i<max_elem;i++){for(var ii=0;ii<settings.elementModel.length;ii++){element=settings.elementModel[ii].replace(/\{[0-9]{0,200}\}/g,natordata[0][i][settings.fieldnames[ii]]);element=element.replace(/<(script)>|<\/?(script)[^<>]*>/ig,"");newcontent+=element}}jQuery("#"+settings.paginatorContentId).html(newcontent);return false}jQuery(settings.paginatorId).attr("class",settings.paginatorClass);var optInit=getPaginatorOptions();jQuery(settings.paginatorId).pagination(natordata[0].length,optInit)}jQuery.post(settings.postUrl,settings.modelFieldNames,setPaginatorData)}return _jqueryPaginator()};

//tendina menu prodotti home (richiede superfish e hoverintent)
function menuHome(){
  if ($("#prodotti").length){
	$('#prodotti').superfish({ 
            delay:       200,
            animation:   {height:'show'},
            autoArrows:  false,
            dropShadows: false
    });
  }
}
//claim home page (richiede jquery.tools)
function claim(claim_on){
  if (claim_on){
	var api = $("#claim").overlay({
		top: 'center',
		expose: {
			color: '#000',
			opacity: 0.3
		},
		closeOnClick: false,
		api: true
	})
	api.load();
	setTimeout(function(){api.close();}, 9000);
  }
}
//inizializzazione jquery.pagination
var items_per_page = 6;
function initPagination() {
	//se esiste contenuto da paginare
	if ($('#hiddenresult').length){
		$("#hiddenresult").before("<ul id='searchresult'></ul>");
		var num_entries = $('#hiddenresult li').length;
		var cpn = parseInt(readCookie('px'));
		cpn = !cpn ? 0 : cpn;
		if(num_entries<=items_per_page){$("#pagination").hide()}
		$("#pagination").pagination(num_entries, {
			num_edge_entries: 0,
			num_display_entries: 4,
			items_per_page:items_per_page,
			callback: pageselectCallback,
			current_page: cpn,
			page_x_of_y : false
		});
	}
}
function pageselectCallback(page_index, jq){
	createCookie('px',page_index,1);
	var max_elem = Math.min((page_index+1) * items_per_page, $('#hiddenresult li').length);
	$('#searchresult').fadeOut('fast',function(){
		$('#searchresult').empty();
		for(var i=page_index*items_per_page;i<max_elem;i++){
			var new_content = $('#hiddenresult li:eq('+i+')').clone();
			$('#searchresult').append(new_content);
		}
		$('#searchresult').fadeIn("slow");
	});
	return false;
}
//gallery news (richiede jquery.tools)
function galleryNews(txt_show,txt_hide){
  if ($('p.gallery').length){	
	$("p.gallery").each(function(){
		var ancora = $("a",this);
		var target = $(ancora).attr("href");
		$(ancora).click(function() {
			if($(target).css("display") == "none"){
				$(target).animate({
					opacity: 1,
					height: 'toggle'
				}, 300, function() {
					var destination = $(target).offset().top;
					$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, 500);
					$(ancora).text(txt_hide);
				});
			}else{
				$(target).animate({
					opacity: 0,
					height: 'toggle'
				}, 10, function() {
					var destination = $(ancora).parents('.box-news').offset().top;
					$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, 300);
					$(ancora).text(txt_show);
				});
			}
			$(this).blur();
			return false;
		});
	});
  }
  if ($('div.gallery_news').length){	
	$("div.gallery_news").each(function(){
		$(".scrollable",this).wrap('<div class="navigazione" />');
		$(".navigazione",this).prepend('<a class="nextPage">next</a>').append('<a class="prevPage">prev</a>');
		$(".scrollable",this).scrollable({ 
			size: 4
		}).mousewheel();
		if ($('.scrollable ul li',this).length == 4){ // has to be the same value as defined in scrollable config 
			$('.nextPage',this).addClass('disabled'); 
		} 
		$(".image_wrap",this).append('<div class="loading">loading...</div>').append('<p class="caption"></p>');
		$(".scrollable ul a",this).click(function() {
			$(this).parent("li").click();
			return false;
		});
		$(".scrollable ul li",this).click(function() {
			var url = $("a",this).attr("href");
			var caption = $("img",this).attr("alt");
			var img = $('<img />').attr('src', url);
			var gallery_container = $(this).parents(".gallery_news");
			$(".image_wrap .caption",gallery_container).fadeTo('slow', 0);
			$(".image_wrap .loading",gallery_container).fadeTo('slow', 1, function() {
				$(".image_wrap img",gallery_container).attr({src:url, alt:caption});
				$(".image_wrap .caption",gallery_container).text(caption);
			});
			$(img).one('load',function() {
				$(".image_wrap .loading",gallery_container).fadeTo('slow', 0, function() {
					$(".image_wrap .caption",gallery_container).fadeTo('slow', 0.8);
				});
			}).each(function() {
				 if(this.complete) $(this).trigger('load');
			});
		}).filter(":first").click();
	});
  }
}
//gallery prodotti (richiede jquery.tools)
function galleryProdotti(txt_show,txt_hide){
  if ($('#gallery_prodotti p a.mostra').length){
	$("body").append('<div class="simple_overlay" id="gallery_overlay"> <a class="prev">prev</a> <a class="next">next</a><div class="info"></div></div>');
	  $("#gallery_prodotti .navigazione").prepend('<a class="prevPage">prev</a>').append('<a class="nextPage">next</a>');
		$("#gallery_prodotti .scrollable").scrollable({ 
			size: 5
		}).mousewheel().find("a").overlay({
			target: '#gallery_overlay',
			expose:({ 
			    color: '#000',
				opacity:0.3
			}),
			top: '20%'
		}).gallery({
			disabledClass: 'inactive',
			template: '<strong>${title}</strong> <span>Img ${index} / ${total}</span>'
		});
	  if ($('#gallery_prodotti .scrollable ul li').length == 5){ // has to be the same value as defined in scrollable config 
		$('#gallery_prodotti .nextPage').addClass('disabled'); 
	  } 
	$("#gallery_prodotti p a.mostra").click(function() {
			var target = $("#gallery_prodotti p").next();
			if($(target).css("display") == "none"){
				if(jQuery.support.opacity){
					$(target).fadeIn(300);
				}
				else{
					$(target).fadeIn(0);
				}
				$(this).text(txt_hide);
			}else{
				if(jQuery.support.opacity){
					$(target).fadeOut(300);
				}
				else{
					$(target).fadeOut(0);
				}
				$(this).text(txt_show);
			}
			$(this).blur();
			return false;
		});
  }
}
//tooltip e scroll cartelle colori (richiede jquery.tools)
function cartellaColori(){
  if ($('#cartella_colori').length){
	  $("#cartella_colori .scrollable").wrap('<div class="navigazione" />');
	  $("#cartella_colori .navigazione").prepend('<a class="prevPage">prev</a>').append('<a class="nextPage">next</a>');
	  $("#cartella_colori .scrollable").scrollable({ 
		absolute: false,
		size: 12
	  }).mousewheel();
	  if ($('#cartella_colori .scrollable ul li').length == 12){ // has to be the same value as defined in scrollable config 
		$('.nextPage',this).addClass('disabled'); 
	  } 
	  $("#cartella_colori h4").tooltip({
		effect: 'slide',
		relative: true,
		offset: [0, 0],
		onShow: function() { 
			var ancora = this.getTrigger().next('.tooltip').find('a');
			if ($(ancora).length){
				var percorso = $(ancora).attr('href');
				var img = $('<img />').attr('src', percorso);
				$(img).load(function(){
					$(ancora).replaceWith(img);
					$(img).fadeIn();
				});
			}
		} 
	  });
  }
}
//overlay privacy (richiede jquery.tools)
function overlay(){
	$("a.privacy, a.video, a.credits").overlay({
		top: 'center',
		expose: { 
			color: '#000', 
			loadSpeed: 200, 
			opacity: 0.3 
		}
	});
}
//mostra-nascondi faq
function faq(){
  if ($('dl.domande dt').length){
    $('dl.domande dt').click(function(){
	  $(this).next().slideToggle(200);					
    });
  }
}
//overlay video (richiede jquery.tools)
function video(){
  if ($('a.video').length){
	$("body").append('<div id="video" class="simple_overlay"><div class="player"><a href="'+$('a.video').attr('href')+'" class="cont_video"></a></div></div>');
	$("#video .player a").flowplayer({ 
    src: "../swf/flowplayer-3.1.5.swf", 
	expressInstall: "../swf/expressinstall.swf",
	wmode: 'transparent',  
    version: [10, 0]
    } , { 
		clip:{
			//autoPlay: false,
			scaling: 'fit'
			},
		canvas: { 
			backgroundGradient: 'none' 
		},
		plugins:  { 
			controls: {             
				// custom colors 
				bufferColor: '#dbe2f2', 
				progressColor: '#8185a0',             
				buttonColor: '#8E93AF', 
				buttonOverColor: '#AEB2CB', 
				backgroundColor: '#333333',
				timeColor: '#dbe2f2',
				tooltipColor: '#85889A',
				opacity:0.7,
				//scrubber
				scrubberHeightRatio: 0.6,
				scrubberBarHeightRatio: 0.6,
				volumeSliderHeightRatio: 0.6,
				volumeBarHeightRatio: 0.6,
				// setup auto hide 
				autoHide: 'always',
				//hideDelay: 2000,
				//tooltips
				tooltips:  { 
					// a shortcut for enabling tooltips for buttons (English) 
					buttons: true,
					play: null,
					pause: null
				},
				// a little more styling              
				width: '98%',  
				bottom: 5, 
				left: '50%', 
				borderRadius: 10
			} 
		} 
	});
  }
}
//flash embedding (richiede jquery.tools)
function flashEmbedding(lingua){
  $('#mondo').flashembed({
	src: '../swf/mondochegira.swf',  
	wmode: 'transparent',
	quality:'high'
  });
  if ($("#agenti").length){
    $('#agenti').flashembed({
	  src: '../swf/agenti_'+lingua+'.swf',  
	  wmode: 'transparent',  
	  expressInstall: "../swf/expressinstall.swf",
      version: [10, 0],
	  quality:'high'
    });
  }
  if ($("#punti_vendita").length){
    $('#punti_vendita').flashembed({
	  src: '../swf/punti_vendita_'+lingua+'.swf',  
	  wmode: 'transparent',  
	  expressInstall: "../swf/expressinstall.swf",
      version: [10, 0],
	  quality:'high'
    });
  }
}
	
//init
$("html").addClass('js');
$(document).ready(function(){
  //setto la variabile lingua
  var lingua = '';
  var txt_show = '';
  var txt_hide = '';
  if ($('body').hasClass('eng')) {
   lingua = 'eng';
   txt_show = 'View the gallery';
   txt_hide = 'Hide the gallery';
  }
  else if ($('body').hasClass('fra')) {
   lingua = 'fra';
   txt_show = 'View the gallery';
   txt_hide = 'Hide the gallery';
  }
  else if ($('body').hasClass('esp')) {
   lingua = 'esp';
   txt_show = 'View the gallery';
   txt_hide = 'Hide the gallery';
  }
  else {
   lingua = 'ita';
   txt_show = 'Mostra la gallery';
   txt_hide = 'Nascondi la gallery';
  }
  video();
  linkext();
  if ($("#claim").length){
  	claim(claim_on);
  }
  menuHome();
  cartellaColori();
  //per il gradiente sui titoli
  $("h2.fade").prepend("<span></span>");
  initPagination();
  galleryProdotti(txt_show,txt_hide);
  galleryNews(txt_show,txt_hide);
  faq();
  overlay();
  flashEmbedding(lingua);
});
