

$(document).ready(function(){

	$('.fancybox').fancybox();
	$('.fancybox_web').addClass('iframe').fancybox({frameWidth:800, frameHeight:600});
	$('#searchfield')
		.focus(function(){if ($(this).val() == 'Cerca') $(this).val('')})
		.blur(function(){if ($(this).val() == '') $(this).val('Cerca')});


	if ($('#topbar .news_line').length > 0){
		newsline($('#topbar .news_line'));
	}

	// Corner in IE
	if($.browser.msie){
		$('.home-title, .widgettitle').corner().css({marginBottom:10});

		//$(' #menu ul li:first + li ~ li, #menu ul li:eq(0), #menu ul li:eq(1)').corner();

		// Png fix
		if(parseInt($.browser.version) == 6){
			$('#head-content').fixPNG();
		}
	}


	var timeScroll = 5000;
	$('.scroll').each(function(){
		$scroll = $(this);
		$scroll.click(function(){
			document.location = $(this).parent().parent().find('.bottom a').attr('href');
		}).find('li').hover(
			function(){$(this).addClass('hover')},
			function(){$(this).removeClass('hover')}
		);
		setInterval(function(){rotate($scroll,timeScroll/2)},timeScroll);
	});



	// **************************************************************************
	// Gestione dei form
	// **************************************************************************

	$('form').each(function(){
		$form = $(this);
		$form.submit(function(){
			var ok = true;
			var $input;
			$('input[type=text][lang*=required], textarea[lang*=required]', this).each(function(){
				if (!ok) return;
				$input = $(this);
				if ($input.val() == ''){
					ok = false;
					alert('Devi compilare il campo "'+ $input.attr('title')+'"' );
					$input.focus();
					return;
				}
			});
			$('input[type=checkbox][lang*=required]').each(function(){
				if (!ok) return;
				$input = $(this);
				if ($input.attr('checked')==false){
					ok = false;
					alert('Devi '+ $input.attr('title') );
					$input.focus();
					return;
				}
			});

			$('input[lang*=email]', this).each(function(){
				if (!ok) return;
				ok = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/.test($(this).val());
				if (!ok){
					$input = $(this);
					alert('Il campo "'+$input.attr('title')+'" deve contenere una email valida!');
					$input.focus();
					return;
				}

			})

			return ok;
		});

		//

	});



	// **************************************************************************
	// Tabs
	// **************************************************************************

	var $tabbox = $('#side-tabs');
	var $menu = $tabbox.find('.tabs li');

	$menu.each(function(ntab){
		$(this).click(function(){
			$menu.find('a').removeClass('on');
			$(this).find('a').addClass('on');
			$tabbox.find('.cat_content').slideUp().eq(ntab).slideDown();
			return false;
		});

	});

	// **************************************************************************
	// Sondaggio
	// **************************************************************************
	$(".pollform").each(function(){
		var $this = $(this);
		var idpol = $('input.idpol', $this).val();

		$(".show", $this).click(function(){
			show_poll_result(null, $this);
			return false;
		});

		$this.submit(function(event){

			event.preventDefault();
			var answer = $("input:checked", $this).attr("value");

			if(answer==undefined) {
				alert('Devi selezionare una risposta');
				return;
			}



			$.ajax({
				url:'/sondaggi/send',
				type:'POST',
				data:'answer='+answer+'&poll='+idpol+'&ajax=true',
				success:function(msg){
					alert(msg);
					$.cookie('rp_poll_'+idpol, answer, {expires: 365});
					show_poll_result(answer, $this);
				}
			});
		}); // setup the submit handler
		var yourvote = $.cookie('rp_poll_'+idpol);

		if (yourvote || ($('.show', $this).length == 0)){
			//Già votato o sondaggio chiuso, mostro i risultati
			show_poll_result(yourvote, $this);
		}
	});


   var $acc = $('h3.collapsible');

   if ($acc.length == 0) return;

   $acc.click(function(){
      $(this).toggleClass('collapsible_selected').next().slideToggle();
   }).hover(
      function(){$(this).addClass('collapsible_over')},
      function(){$(this).removeClass('collapsible_over')}
   );

});


function show_poll_result(yourvote, $form){

	var idpol = $('input.idpol', $form).val();
	$('.show', $form).remove();

	$.getJSON("/sondaggi/json_poll/"+idpol, function(poll){

		var results_html = "";

		$.each(poll.answers, function(k, answer){
			var percent = Math.round(answer.votes / poll.votes *100);
			if (answer.id !== yourvote) {
			  results_html+= "<dt class='bar-title'>"+answer.title+"</dt><dd class='bar-container'><div id='bar"+answer.id+"'style='width:0%;'>&nbsp;</div><strong>"+percent+"%</strong></dd>\n";
			} else {
			  results_html+="<dt class='bar-title'>"+answer.title+"</dt><dd class='bar-container'><div id='bar"+answer.id+"'style='width:0%;background-color:#0066cc;'>&nbsp;</div><strong>"+percent+"%</strong></dd>\n";
			}
		});

		 results_html = results_html+"";

		$form.find('.graph').html(results_html).fadeIn("slow",function(){
			animateResults($form);
		});

	});


}

function animateResults($form){

  $(".poll-results div", $form).each(function(){
      var percentage = $(this).next().text();
      $(this).css({width: "0%"}).animate({width: percentage}, 'slow');
  });
}


// **************************************************************************
// Funzioni Varie
// **************************************************************************
	function popup(url, name, w, h){
		window.open(url, name, "scrollbars=0,resizable=0,menubar=0,toolbar=0,status=0,width="+w+",height="+h)
	}

	function rotate($elements, time){
	//alert($(':first', $elements).html());
		$el = $(':first', $elements);
		var marginTop = $el.css('margin-top');
		var height = $el.height()+intpx($el.css('padding-top'))+intpx($el.css('margin-top'))+intpx($el.css('padding-bottom'))+intpx($el.css('margin-bottom'));
		$el.animate({marginTop:-height},time, 'linear', function(){$el.appendTo($elements).css('margin-top', marginTop)});
	}

	function intpx(val){
		return parseInt(new String(val).replace('px', ''));
	}

	function newsline($line){

		$line.css({textIndent:750});
		var width = 0;
		$('li', $line).each(function(){width+= $(this).width()});
		animateNewsline($line, width)
	}
	function animateNewsline($line, width){
		$line.stop();
		//alert('nuovo giro! :)')
		$line.animate({
			textIndent:-width-600},
			width*50, // Velocità
			'linear',
			function(){
				newsline($line);
			}
		)/*.hover(
			function(){$(this).stop()},
			function(){setTimeout(function(){animateNewsline($line, width)}, 1000)}
		);*/
	}

// **************************************************************************
// MP3 Player
// **************************************************************************
var approximate_time = [];
var approximate_time_n = [];

function update_mp3(el, id, show_time){

	var isPlaying = (el.isPlaying == "true");
	if (isPlaying){
		$('#play_'+id).hide();
		$('#pause_'+id).show();
	}
	else{
		$('#play_'+id).show();
		$('#pause_'+id).hide();
	}
	// Se non mostra il tempo esce. di default show_time è true
	if((new String(show_time) != 'undefined') || show_time){
		return;
	}

	if(approximate_time[id] == undefined){
		approximate_time[id] = 0;
		approximate_time_n[id] = 0;
	}

	var total = '';
	if (!isNaN(el.bytesPercent) && (el.bytesPercent>0) && (approximate_time_n[id] <10)){
		approximate_time[id] += Math.round( el.duration / (10*el.bytesPercent));
		approximate_time_n[id] ++;
		total = " / -:--";
	}


	if ((el.bytesTotal == el.bytesLoaded) || (approximate_time_n[id] == 10)){

		if (el.bytesTotal == el.bytesLoaded){
			var total_s = Math.round(el.duration / 1000);
		}
		else{
			var total_s = Math.round(approximate_time[id] / 10);
		}

		var total_m = Math.floor(total_s/60);
		var total_h = '';
		total_s = total_s % 60;

		if (total_m > 60){
			total_h = Math.floor(total_m/60)+':';
			total_m = total_m %60;
			total_m = total_m < 10 ? '0'+total_m : total_m;
		}
		total = " / "+total_h+total_m+":"+total_s;
	}

	var pos_s = Math.round(el.position /1000);
	var pos_m = Math.floor(pos_s/60);
	var pos_h = '';
	if (pos_m > 60){
		pos_h = Math.floor(pos_m/60)+':';
		pos_m = pos_m %60;
		pos_m = pos_m < 10 ? '0'+pos_m :pos_m;
	}
	pos_s = pos_s % 60;



	$('#pause_'+id).html(pos_h+pos_m+":"+(pos_s<10 ? '0'+pos_s : pos_s)+total);

}

function play(id){

	var fo = document.getElementById("prog_"+id);
	if (('list_'+id).position == 0) {
		fo.SetVariable("method:setUrl", "/medias/another_world.mp3");
	}
	fo.SetVariable("method:play", "");
	fo.SetVariable("enabled", "true");
}
function pause(id){
	document.getElementById("prog_"+id).SetVariable("method:pause", "");
}


function addShow(id, control){
	$.ajax({type: "GET", url: "/banner/add_show/"+id+'/'+control})
}
