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

//limita i caratteri della textarea
limitChars = function(){
  $(".charcounter textarea").each(function(){
	var maxChar = $(this).siblings('p').find('.maxchar');
	var limit = parseInt(maxChar.text());
 	$(this).keyup(function(){
 		var charactersUsed = $(this).val().length;
		if(charactersUsed > limit){
			maxChar.text('0').css("color", "red");
			$(this)
			.val($(this).val().substr(0, limit))
			.scrollTop($(this)[0].scrollHeight);
		}
		else{
			maxChar.text(limit - charactersUsed).css("color", "#333");
			//se è ie
			if(!jQuery.support.opacity){
				$(this).scrollTop($(this)[0].scrollHeight);
			}
		}
 	});
  });
}
//date picker
datePicker = function(){
	$('input.datepicker').datePicker({
		clickInput:true,
		month:0,
		year: 1975,
		startDate: '01/01/1900',
		endDate: (new Date()).asString(),
		verticalOffset:30
	});
}
//mostra/nasconde i campi relativi alla scelta di inserire o meno il codice cliente
showHideFormFields = function(){
	//se è già selezionato un valore all'apertura della pagina
	if($("input[name='customer']:checked").length){
		var show = $("input[name='customer']:checked").attr('id');
		$('div.row.scelta').not('.'+show).hide();
		$('div.row.scelta.'+show).show();
	}
	//al cambio del radio
	$("input[name='customer']").click(function() {
		var show = $(this).attr('id');
        $('div.row.scelta').not('.'+show).hide();
        $('div.row.scelta.'+show).show();
    });
}
// recupera i dati del video BRIGHTCOVE (http://support.brightcove.com/en/docs/using-javascript-player-api#ref)
// called when template loads, this function stores a reference to the player and modules.
var player;
var videoPlayer;
var experience;
var content;
var idVideo;
onTemplateLoaded = function(experienceID) {
    player = brightcove.getExperience(experienceID);
    videoPlayer = player.getModule(APIModules.VIDEO_PLAYER);
    experience = player.getModule(APIModules.EXPERIENCE);
    content = player.getModule(APIModules.CONTENT);
	idVideo = experienceID;
}
stopVideo = function (){
	videoPlayer.stop();
}
//accordion
accordion = function(){
	// add new effect to the tabs
	$.tools.tabs.addEffect("slideAssistenza", function(i, done) {
		this.getPanes().slideUp().prev().css({backgroundColor: 'transparent'});
		this.getPanes().eq(i).slideDown(function() {done.call();}).prev().css({backgroundColor: '#FFFFFF'});
	});
	
	$(".visore-right").tabs(".visore-right div.accordion", {
		tabs: 'h2',
		effect: 'slideAssistenza'
	});
	$("#visore-right-promozioni").tabs("#visore-right-promozioni ul", {
		tabs: 'h2',
		effect: 'slide'
	});
}

//domande
domande = function(){
	$.tools.tabs.addEffect("slideDomande", function(i, done) {
		this.getPanes().slideUp(200);
		this.getPanes().eq(i).slideDown(function() {done.call();});
	});
	//accordion faq nell'overlay (pacchetti)
	$(".overlay.domande, .overlay-content.domande").each(function(i, tab) {
		$(tab).tabs(".overlay.domande:eq("+i+") dd, .overlay-content.domande:eq("+i+") dd", {
			tabs: 'dt',
			effect: 'slideDomande',
			onClick:(function(event, i) {
				//all'apertura della faq, reinizializza lo scroll
				var scrollPanel = this.getCurrentPane().parents(".scroll").jScrollPane({
					verticalGutter: 10
				})
				/*var scrollPanel = this.getCurrentPane().parents(".jspScrollable");
				if(scrollPanel.length){
					var api = $(scrollPanel).data('jsp');
					api.reinitialise();
				}*/
			})
		});
	});
	//accordion pagine istituzionali (es. assistenza)
	$("#right-column .accordion").tabs("#right-column .accordion ul", {
		tabs: 'h4',
		effect: 'slideDomande',
		initialIndex: null
	});
	/* AGGIUNTA 02/08/2011 */
	$(".full-page .main").tabs("..full-page .main dd", {
		tabs: 'dt',
		effect: 'slideDomande'
	});
	/* FINE AGGIUNTA 02/08/2011 */
	/* AGGIUNTA 05/08/2011 */
	$(".overlay.seriea").tabs(".overlay.seriea dd", {
		tabs: 'dt',
		effect: 'slideDomande',
		onClick:(function(event, i) {
			//all'apertura della faq, reinizializza lo scroll
			var scrollPanel = this.getCurrentPane().parents(".scroll").jScrollPane({
				verticalGutter: 10
			})
		})
	});
	/* FINE AGGIUNTA 05/08/2011 */
}

//aggiunge l'effetto 'none' (nessuna animazione) all'overlay
$.tools.overlay.addEffect("none", function(position, done) {
	  this.getOverlay().css(position).show(0, done);
   },
   function(done) {
	  this.getOverlay().hide(0, done);
   }
);
	
//overlay contenuti all'interno del visore
overlayVisore = function(){
	//$("#visore-top-clienti a, #visore-top-offerta a, #visore-top-pack a.open, #visore-bottom-pack .prezzi-combinazioni a, .visore-right .accordion li a, .switch a").each(function() {
	$('#visore-top-clienti a:not(.external), #visore-bottom-clienti a:not(.external), div[class|="visore"] a:not(.external), #visore-top-pack a.open, #visore-bottom-pack .prezzi-combinazioni a:not(.external), .visore-right .accordion li a, .switch a, .box-contatti a.open').each(function() {
		var target = $(this).attr("href");
		$(this).overlay({
			fixed: false, 
			closeOnClick: false,
			relativeToParent:true,//aggiunto a overlay per far sì che si posizioni relativamente al div che lo contiene
			top: 4,
			left: 4,
			target: target,
			effect: 'none',
			onBeforeLoad: function() {
				$('.with-tabs .overlay-supporto').hide();
			  this.getTrigger().addClass('active');
			  $('#visore-top-pack a[href="'+target+'"]').addClass('active');
		    },
			onLoad: function() {
				var scrollpanel = this.getOverlay().find('.scroll');
				if(scrollpanel){
					$(scrollpanel).jScrollPane({
						verticalGutter: 10,
						enableKeyboardNavigation: false,
						autoReinitialise: true
					})
				}
		    },
			onBeforeClose: function() {
			  //se c'è un object nell'overlay che si sta chiudendo ed è stato istanziato il videoPlayer
			  if ($('#'+idVideo,this.getOverlay()).length && videoPlayer){
			  	//metto il video in pausa
				stopVideo();
			  }
			  this.getTrigger().removeClass('active');
			  $('#visore-top-pack a.active').removeClass('active');
			  //se cufon è attivo per questo elemento
			  if (this.getTrigger().children("cufon").length){
			    Cufon.replace(this.getTrigger());
			  }
		    }
		});
	});
}
//overlay absolute lightbox
/* AGGIUNTA 05/08/2011 */
overlayAbsoluteLightbox = function(){
	$("a.lightboxabsolute").each(function() {
		var target = $(this).attr("href");
		$(this).overlay({ 
			closeOnClick: false,
			speed:	0,
			mask: {
				color: '#000',
				loadSpeed: 0,
				opacity: 0.4
			},
			fixed: false,
			target: target,
			oneInstance: false,
			onBeforeClose: function() {
			  //se c'è un object nell'overlay che si sta chiudendo ed è stato istanziato il videoPlayer
			  if ($('#'+idVideo,this.getOverlay()).length && videoPlayer){
			  	//metto il video in pausa
				stopVideo();
			  }
		    }
		});			
	});
}
/* FINE AGGIUNTA 05/08/2011 */
//overlay lightbox
overlayLightboxLogin = function(){
	$("a.lightbox-login").each(function() {
		$(this).overlay({ 
			closeOnClick: false,
			speed:	0,
			mask: {
				color: '#000',
				loadSpeed: 0,
				opacity: 0.4
			},
			target: "#overlay-login-box",
			top:'center',
			oneInstance: false
		});			
	});
}

//tabs
tabs = function(){
  $("ul.tabs").tabs("div.panel", {
		onBeforeClick: function(event, i) {
			//se c'è un object nel tab che si sta chiudendo ed è stato istanziato il videoPlayer
			if ($('#'+idVideo,this.getCurrentPane()).length && videoPlayer){
				//alert($('#'+idVideo).html());
				//metto il video in pausa
				stopVideo();
			}
		},
		onClick: function(event, i) {
			// get the pane to be opened
			var pane = this.getPanes().eq(i);
			pane.find('.scroll').jScrollPane({
					verticalGutter: 10,
					autoReinitialise: true
			})
		}
  });
  $(".overlay .tabs a").click(function(){
	Cufon.replace('.overlay .tabs a');
  }); 
}
//tabs supporto
tabsSupporto = function(){
  if($("ul.tabs-supporto").length){
	  var api = $("ul.tabs-supporto").tabs("div.panel-supporto", {
		initialIndex: 'null'
	  }).data("tabs");
	  
	  api.onBeforeClick(function(event, i) {
		//se c'è un object nel tab che si sta chiudendo ed è stato istanziato il videoPlayer
		if ($('#'+idVideo,this.getCurrentPane()).length && videoPlayer){
			//metto il video in pausa
			stopVideo();
		}
	  });
	  api.onClick(function(event, i) {

		$('.panel-supporto .overlay-supporto').hide();
		// get the pane to be opened
		var pane = this.getPanes().eq(i);
		pane.find('.scroll').jScrollPane({
				verticalGutter: 10,
				autoReinitialise: true
		})
	  });
	  //apre i tab dai link nei box
	  $('.box-supporto .richiedi a').bind('click', function(event) {
		 //api.click($(this).attr('href'));
		 var box_supporto = $(this).parents(".box-supporto");
		 var with_tabs = $(this).parents(".with-tabs");
		 var index = with_tabs.find(".box-supporto").index(box_supporto);
		 with_tabs.find(".tabs-supporto a:eq("+index+")").trigger("click");
		 event.preventDefault();
	  });
	  //chiude tutti i tab aperti cliccando sul titolo
	  $('.panel-supporto a.back').bind('click', function(event) {
		 $(this).parents(".panel-supporto").hide();
		 event.preventDefault();
	  });
	  
  }
}
//overlay nell'overlay
metaOverlay = function(){
	  $("a.meta-overlay").click(function(event) {
		var target = $(this).attr("href");
		$(target).siblings('.visible').hide(0);
		$(target).show(0, function() {
		  $(this)
		  .addClass('visible')
		  .find('.scroll').jScrollPane({
			verticalGutter: 10,
			autoReinitialise: true
		  })
		  .end().find('a.close-overlay').click( function(event) {
			  //se c'è un object nell'overlay che si sta chiudendo ed è stato istanziato il videoPlayer
			  if ($('#'+idVideo,target).length && videoPlayer){
				  //metto il video in pausa
				  stopVideo();
			  }
			  $(target).hide(0, function() {
				  $(this).removeClass('visible')
			  });
			  event.preventDefault();
		  });
		});
		 event.preventDefault();
	  });
}

//slider pack canali
sliderPack = function(){
  if($(".sliderPack").length){
	  $(".sliderPack ul").carouFredSel({
		width: 182,
		//height: 290,
		height: 265,
		items: {
			visible: 1,
			width: 182,
			//height: 290
			height: 265
		},
	    scroll: {
		    duration: 200,
		    easing: 'swing'
	    },
		auto: false,
		prev: ".prevPack",
		next: ".nextPack"
	  });
  }
}

//dettaglio canali
channelDetails = function(){
  if($(".channels-container").length){
	$(".channels-container").each(function(index) {
		//se ci sono più di 20 canali divide la lista in liste da 20
		if($("ul.channels li",this).length > 20){
			var $bigList = $("ul.channels",this).remove(),
				group    = $bigList.find('li:lt(20)').remove();
			
			while(group.length){
				$('<ul/>').append(group).appendTo(this).addClass('channels');
				group = $bigList.find('li:lt(20)').remove();
			}
			$(this).after('<div class="prevNext"><a class="prevChannel prev'+index+'">prev</a> <a class="nextChannel next'+index+'">next</a></div>').carouFredSel({
				direction: "up",
				circular: false,
				infinite: false,
				width: 680,
				height: 66,
				items: {
					visible: 1
				},
				auto: false,
				prev: ".prev"+index,
				next: ".next"+index
			});
		}
	});
	
	//mostra i dettagli dei canali
	showChannel = function(channel){
	  $('#channel-details div:visible')
	  .not(channel)
	  .stop(true, true)
	  .fadeOut(100);
	  
	  channel
	  .stop(true, true)
	  .fadeTo(400, 0.99);//0.99 disabilita il cleartype su explorer
	}
	
	$(".channels a")
    .each(function(index) {
	  if(index==0){
	    showChannel($($(this).attr('href')));//mostro il box del primo canale
		$(this).addClass('active');
	  }
	  $(this)
	  .css('cursor', 'default')
	  .click(function(event) {
	    event.preventDefault();
	  })
	  .hover(
	    function () {
		  showChannel($($(this).attr('href')));
		  $(this).addClass('active').parent().siblings('li').find('a.active').removeClass('active');
	    }
	  );
    });
	
	//tab canali
	$("ul.channel-tabs").tabs("div.panel-channel", {
		//al cambio di tab
		onClick:(function(event, i) {
			var prevTab = this.getCurrentPane();//il tab da cui arrivo
			if($(".caroufredsel_wrapper", prevTab).length){//se c'è un carousel nel tab
				$(".channels-container", prevTab).trigger("slideTo", 0);//porto il carousel del tab da cui arrivo al primo elemento
			}
			var nextTab = this.getPanes().eq(i);//il tab selezionato
			var firstLink = nextTab.find('a:first').addClass('active');
			firstLink.parent().siblings('li').find('a.active').removeClass('active');
			showChannel($(firstLink.attr('href')));//mostro il box del primo canale del tab selezionato
		})
	});
	
	var apiChannelTab = $("ul#channel-tabs").tabs("div.panel-channel", {
		  initialIndex: 0
	  }).data("tabs");
	$("ul.channel-tabs").tabs("div.panel-channel", {
		  onClick:(function(event, i) {
				$("ul#channel-tabs a").removeClass('current');
		  })
	});
	
  }
}
//dettaglio canali
/*channelDetails = function(){
  if($(".channels").length){
	showChannel = function(channel){
		  $(channel.attr('href'))
		  .stop(true, true)
		  .fadeTo(400, 0.99);//0.99 disabilita il cleartype su explorer
	}
	hideChannel = function(channel){
		  $(channel.attr('href'))
		  .stop(true, true)
		  .fadeOut(400);
	}
	$(".channels a")
    .each(function(index) {
	  $(this)
	  .css('cursor', 'default')
	  .click(function(event) {
	    event.preventDefault();
	  })
	  .hover(
	    function () {
		  showChannel($(this));
	    },
	    function () {
		  hideChannel($(this));
	    }
	  );
    });
  }
}
*/
//guida tv

guidaTvIE = function(){
	
	//risolve il bug per IE7
	 $(".box-middle .carousel li .description").each(function(){  
		$(this).stop().animate({"opacity": "0"}, 200);	 
	 });
	
}


guidaTv = function(){	
	
	
  if($("#guida-tv .sezione").length){
    //tabs+carousel
	if($("#guida-tv .sezione").length>1){
	  $("#guida-tv ul.tabs").tabs("div.sezione", {
	    onClick: function(event, index) {
	      var visibleTab = this.getPanes().eq(index);
	      var next = '#'+visibleTab.attr("id")+' .next';
	      var prev = '#'+visibleTab.attr("id")+' .prev';
	      if(!$("div.caroufredsel_wrapper",visibleTab).length){
	        $("ul.carousel",visibleTab).carouFredSel({
	  	      items: 4,
			  scroll: {
				  duration: 700,
				  easing: 'easeOutExpo'
			  },
		      width: 561,
		      auto: false,
		      prev: {
		   	    button: prev
		      },
		      next: {
			    button: next
		      }
	        });
	      }
	    }
       });
	}
	//solo carousel
	else{
	  $("#guida-tv ul.carousel").carouFredSel({
	    items: 4,
	    scroll: {
		  duration: 700,
		  easing: 'easeOutExpo'
	    },
	    width: 561,
	    auto: false,
	    prev: {
		  button: '.prev'
	    },
	    next: {
		  button: '.next'
	    }
	  });
	}
	//fade descrizione
    $(".box-middle .carousel li .description").hover(
	  function() {
	    $(this).stop().animate({"opacity": "1"}, 200);
	  },
	  function() {
	    $(this).stop().animate({"opacity": "0"}, 200);
    });
  }
}

//slider
slider = function(){
	if($(".box-middle .items").length){
	   fadePanel = function(element){
		$('.box-middle .scrollPanel')
		  .filter(':visible').fadeOut(700)
		  .end().filter($('a',element).attr('rel')).fadeIn(700);
		}
	   animatePanel = function(element,type){
		if(type=='in'){
		$($('a',element)).addClass('current').animate({
		  width:'185px',
		  height:'38px',
		  left:'-=16px',
		  top:'-=5px',
		  lineHeight:'38px',
		  borderWidth: '1px',
		  fontSize: '16px'
		  }, 200, function() {
			$(this).addClass('currentIE')
		});
		}
		else{
		$($('a',element)).removeClass('currentIE').animate({
		  width:'155px',
		  height:'31px',
		  left:'+=16px',
		  top:'+=5px',
		  lineHeight:'31px',
		  borderWidth: '0px',
		  fontSize: '14px'
		  }, 200, function() {
			$(this).removeClass('current')
		});
		}
	  }
	  //visualizzo il primo pannello aperto
	  fadePanel($(".box-middle .items li").eq(1));
	  animatePanel($(".box-middle .items li").eq(1),'in');
	  //carouFredSel
	  $(".box-middle .items").carouFredSel({
		width: 467,
		items: {
			visible: 3,
			minimum: 1
		},
		scroll: {
			items: 1
		},
		auto: false,
		prev: {
			button: ".prevItem",
			key: "left",
			onBefore: function( oldItems, newItems, newSizes ) {
				animatePanel(newItems.eq(2),'out');
				fadePanel(newItems.eq(1));
			},
			onAfter: function( oldItems, newItems, newSizes ) {
				animatePanel(newItems.eq(1),'in');
			}
		},
		next: {
			button: ".nextItem",
			key: "right",
			onBefore: function( oldItems, newItems, newSizes ) {
				animatePanel(newItems.eq(0),'out');
				fadePanel(newItems.eq(1));
			},
			onAfter: function( oldItems, newItems, newSizes ) {
				animatePanel(newItems.eq(1),'in');
			}
		}
	  });
	}
}

//menu a tendina
sfMenu = function(){
  $('#menu-section').superfish({ 
            delay:       300,
			speed:         0,
            animation:   {height:'show'},
            autoArrows:  false,
            dropShadows: false
  })
  .find("ul.child").siblings('a')
  .each(function() {
	  $(this)
	  .attr('href', '#')
	  .css('cursor', 'default')
	  .click(function(event) {
	    event.preventDefault();
	  })
  });
}

//intero box cliccabile
boxbottomLinks = function(){
	$(".box-bottom div").click(function() {
		if($('a',this).hasClass('lightbox')){
			var api = $('a',this).data('overlay');
			api.load();
		}
	});
	$('a[rel=#overlay-external]').overlay({
		mask: {
			color: '#000',
			loadSpeed: 0,
			opacity: 0.4
		},
		fixed: false,
		onBeforeLoad: function() {
			// grab wrapper element inside content
			var wrap = this.getOverlay().find(".contentWrap");
			// load the page specified in the trigger
			scroll(0,0);
			wrap.load(this.getTrigger().attr("href"));
		}
	});

}


function hashOpenOverlay(){
  // Bind an event to window.onhashchange
  $(window).hashchange( function(){
    var hash = location.hash;
	//se c'è un hash ed inizia per #/
	if(!hash == "" && hash.substring(0, 2)=="#/"){
		var hashes = hash.slice(hash.indexOf('#') + 2).split('/');
		//per ogni valore recuperato simulo il click sul link corrispondente
		for(var i = 0; i < hashes.length; i++){
	
			window.location = window.location.pathname + "#"; //resetto
	
			scroll(0,0);
			$('a[href="#'+hashes[i]+'"], h2[rel="'+hashes[i]+'"]').trigger('click');
		}
	}
  })
  $(window).hashchange();
}



//cufon
//per #menu site senza immagini e con cufon
//Cufon.replace('#menu-site a, .switch a, .overlay .tabs a', { hover: true, separate:'none' });

Cufon.replace('.switch a, .overlay .tabs a', { hover: true, separate:'none' });
Cufon.replace('.box-bottom h2:not(.iptv), #visore div:not(.concorsi) h2:not(.nocufon), .box-middle div:not(.magazine) h2', { separate:'none' });
Cufon.replace('.magazine h2');

jQuery(document).ready(function($){
	linkext();
	sfMenu();
	overlayVisore();
	metaOverlay();
	tabs();
	tabsSupporto();
	slider();
	boxbottomLinks();
	accordion();
	//guidaTv();
	sliderPack();
	domande();
	channelDetails();
	hashOpenOverlay();
	limitChars();
	datePicker();
	showHideFormFields();
	guidaTvIE();
	
	
	
	//apre il primo channel nell'elenco dei canali (footer del visore offerta sky)
	$(".channels a").each(function(index) {
	  if(index==0){
		showChannel($($(this).attr('href')));//mostro il box del primo canale
		$(this).addClass('active');
	  }});

  //risolve il problema dei link attivi al back di firefox
  if (window.addEventListener) {
        window.addEventListener('unload', function() {}, false);
     
    
  }
  
});




