

/* home
-------------------------------------------------------------- */
function homepage() {
	$(document).ready(function() {
		global(); // richiede global.js
		equalHeight($(".border"));
		equalHeight($("ul.blogger li"));
	});
}

/* global
-------------------------------------------------------------- */
function global() {
	$(document).ready(function() {
        tab('tabber-annunci','random',4);
        sitesearch();
		collapse();	
		overlay();
		equalHeight($("ul.superfooter li.comuni,ul.superfooter li.edizioni,ul.superfooter li.quotidiani"));
		$('body').supersleight();
		trovaindirizzi(".trovaindirizzi form","#cosa");
		trovaindirizzi(".trovaindirizzi form","#dove");
		trovaindirizzi(".trovaindirizzi form","#vicino");
		$('a[rel*=facebox]').facebox(); 
		$('#alphabet').listnav({ 
		includeAll: false,
		includeNums: false 
		}); // listnav alphabetic order
	});
}

function detail() {
	$(document).ready(function() {
        global();
		tools();
		fontsize();
		mediaicon();
		mediagallery();
		check();
	});
}

function sportdetail() {
	$(document).ready(function() {
        global();
		tools();
		tablesorter();
	});
}

function infografica() {
	$(document).ready(function() {
        collapse();
		tools();
	});
}

function motori() {
	$(document).ready(function() {
        tab('tabber-annunci',2);
		sitesearch();
		collapse();	
		equalHeight($("ul.superfooter li.comuni,ul.superfooter li.edizioni,ul.superfooter li.quotidiani"));
		tools();
		fontsize();
		$('a[rel*=facebox]').facebox(); 
	});
}

function favourites() {
	$(document).ready(function() {
        global();
		tools();
		uniform();
	});
}

function meteo() {
	$(document).ready(function() {
        meteotab('tabber-meteo', 1);
		if($('#facebox .footer .credits_meteo').length == 0){
        	$('#facebox .footer').append("<a href=\"http://www.3bmeteo.com/\" class=\"credits_meteo\" target=\"_blank\">Dati a cura di 3BMETEO</a>")
        }
	});
}


/*----------------------------------------------------------------------
  OVERLAY
----------------------------------------------------------------------*/
function overlay() {
	return false;
}

/* fadetoggle */
jQuery.fn.fadeToggle = function(speed, easing, callback) { 
   return this.animate({opacity: 'toggle'}, speed, easing, callback); 
};


function overlay_click() {

	//click persone
	$("a.overlay-button:eq(0)").click(function () {
		$(".overlay:eq(0)").fadeToggle();
		$(".overlay:eq(1)").fadeOut("fast");
	});
	//click luoghi
	$("a.overlay-button:eq(1)").click(function () {
            
                // caricamento ritardato della mappa
                if($('#apertoiframe').attr("value")=='0') {
                   $('#apertoiframe').attr("value","1");
                   $('#mappa-luoghi').html("<iframe width=\"620\" height=\"400\"  frameborder=\"0\" scrolling=\"no\"  src=\""+$('#sorgente_overlay').attr("value")+"\" marginheight=\"0\" marginwidth=\"0\"></iframe>");
                }
                // fine
		$(".overlay:eq(0)").fadeOut("fast");
		$(".overlay:eq(1)").fadeToggle();
	});
	//click mostra la mappa
	$("a.btn-slide").click(function () {
		$(".overlay:eq(2)").slideToggle("slow");
		$(this).toggleClass("active");
	});


	// tasto Esc
	 $(document).keydown( function( e ) {
	 	if( e.which == 27) {  // escape, close box
	 		overlay_click_close();
	 	} 
	  });

	// tasto chiudi
	$(".overlay-hide").click(function () {
		overlay_click_close();
		});
	
	function overlay_click_close() {
		$(".overlay").fadeOut(500, function () {
		});
	}
}

$(document).ready(function() {
	overlay_click();
});

//overlay


function getQuerystring(key) {
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs != null) return qs[1];
}

function check(){
	if(getQuerystring("mappaaperta") == "true") {
		$(".overlay:eq(2)").slideToggle("slow");
		$("a.btn-slide").toggleClass("active");
	}
}


debugmode = false;
$.browser.msie6 = $.browser.msie && ($.browser.version && $.browser.version < 7 || /6.0/.test(navigator.userAgent));
var ievs = (/MSIE (\d+\.\d+);/.test(navigator.userAgent));if(ievs) var iev= new Number(RegExp.$1);


// pngfix per explorer 6
function pngfix(div){
	/* Example usage:
	* DD_belatedPNG.fix('.png_bg'); // argument is a CSS selector
	* DD_belatedPNG.fixPng( someNode ); // argument is an HTMLDomElement */
	//DD_belatedPNG.fix(div);
	if(iev == 6) {
		//debug("pngfix su IE6 per: "+div);
		DD_belatedPNG.fix(div);
	}
}



// collapse della pubblicita
function collapse(delay) {
	typeof delay == "undefined" ? delay = 1000 : delay;
	window.setTimeout(function() {
		advminheight = "19";
		$("div[id^='adv-']").not("div[id^='adv-ext']").each(function () {
			//debug("altezza di " + $(this).attr("id") + ": " +$(this).height());
			if($(this).height() < advminheight) {
				//debug("spengo: <strong>"+ $(this).attr("id") + "</strong> perche la sua altezza &egrave; <strong>" +$(this).height() + "</strong> e il check &egrave; <strong>" + advminheight + "</strong>")
				$(this).hide();
			}
		});
	}, delay );
};


/*----------------------------------------------------------------------
  TOOLS 
----------------------------------------------------------------------*/
function tools(checkbreadcrumb,checkfontsize,checktoolsemail,checktoolsshare) {
	typeof checkbreadcrumb == "undefined" ? checkbreadcrumb = true : false;
	typeof checktoolsemail == "undefined" ? checktoolsemail = true : false;
	typeof checktoolsshare == "undefined" ? checktoolsshare = true : false;

	if(checkbreadcrumb) {breadcrumb();}		// breadcrumb /
	if(checktoolsemail) {toolsemail();}		// segnala via email
	if(checktoolsshare) {toolsshare();}			// condividi socialnetwork
}


/*-----------------------------------
  TOOLS: Font Size  
  -----------------------------------*/
function fontsize(selector,range,units,sizemin,sizemax,selectorincrease,selectordecrease,fix) {

	typeof selector == "undefined" ? selector = ".fontsize" : selector;
	typeof range == "undefined" ? range = 1 : range;
	typeof units == "undefined" ? units = "px" : units;
	typeof sizemin == "undefined" ? sizemin = 13 : sizemin;
	typeof sizemax == "undefined" ? sizemax = 24 : sizemax;
	typeof selectorincrease == "undefined" ? selectorincrease = ".tools-fontincrease" : selectorincrease;
	typeof selectordecrease == "undefined" ? selectordecrease = ".tools-fontdecrease" : selectordecrease;
	typeof fix == "undefined" ? fix = false : fix;
         /*alert(sizemin+" --- "+sizemax);
         alert(parseFloat($(selector).css('font-size'),10));
	*/
	/* genero elementi T+ T- */
	listitem = '<li class="tools-fontincrease"><a href="javascript:void(0)" title="Aumenta la dimensione del testo" rel="nofollow">+</a></li>';
	listitem += '<li class="tools-fontdecrease"><a href="javascript:void(0)" title="Riduci la dimensione del testo" rel="nofollow">-</a></li>';
	$('.fonts').prepend(listitem);

  	//	Aumenta Testo
  	$(selectorincrease).click(function(){
  		if(parseFloat($(selector).css('font-size'),10) <= sizemax ) {
 	  		$(selector).css('font-size',parseFloat($(selector).css('font-size'),10)+range+units);
	  		$(selector + ','+ selector + ' p').css('line-height',parseFloat($(selector).css('line-height'),10)+range+units);
			$.cookie('rep_fontsize',Number(parseFloat($(selector).css('font-size'),10)+range)+'px|'+Number(parseFloat($(selector).css('line-height'),10)+range)+'px');
  		};
  		fixelement(fix);
  	});
  	
  	//	Riduci Testo
  	$(selectordecrease).click(function(){
  		if(parseFloat($(selector).css('font-size'),10) >= sizemin ) {
   			$(selector).css('font-size',parseFloat($(selector).css('font-size'),10)-range+units);
  			$(selector + ','+ selector + ' p').css('line-height',parseFloat($(selector).css('line-height'),10)-range+units);
			$.cookie('rep_fontsize',Number(parseFloat($(selector).css('font-size'),10)-range)+'px|'+Number(parseFloat($(selector).css('line-height'),10)-range)+'px');
  		};
  		fixelement(fix);
  	});
}

/* -- TOOLS: Font Size fix ---------------- */
	function fixelement(fix){
		if(fix) {
			$('.related-content ul').css('font-size', '13px');
			}
	}

/*-----------------------------------
  TOOLS: SHARE (Social Network) 
  -----------------------------------*/
function toolsshare() {
	this.siti = {
		'delicious':	{display: 'Delicious',		url: 'http://del.icio.us/post?url={u}&amp;title={t}'},	
		'facebook':		{display: 'Facebook',		url: 'http://www.facebook.com/sharer.php?u={u}&amp;t={t}'},
		'oknotizie':	{display: 'OKNOtizie',		url: 'http://oknotizie.alice.it/post?url={u}&amp;title={t}'},
		'newscontrol':	{display: 'NewsControl',	url: 'http://news.kataweb.it/login'},
		'technorati':	{display: 'Technorati', 	url: 'http://www.technorati.com/faves?add={u}'},
		'twitter':		{display: 'Twitter',	 	url: 'http://twitthis.com/twit?url={u}'}
	};

	var url = encodeURIComponent(window.location.href);
	var title = encodeURIComponent(document.title);

	listitem = '<ul>';
	for(var item in siti) {
		var value = siti[item];
		listitem += "<li class=\"share-"+item+"\"><a href=\""+value['url'].replace(/{u}/, url).replace(/{t}/, title)+"\" title=\"Segnala su "+value['display']+"\">"+value['display']+"</a></li>\n";
	}
	listitem += "</ul>"
	//$("#debug").html("<pre>"+dump(siti)+"</pre><br /><br />");

	$(".tools-share a").after(listitem);
	
	
	// fix hover per ie6
	if(iev == 6) {
		$('ul.tools li.tools-share').hover(function() {
			$('ul.tools li.tools-share ul').css('display','block');
				$('ul.tools li.tools-share a').addClass('tools-share-fixie6');
			}, function() {
	  		$('ul.tools li.tools-share ul').css('display','none');
			$('ul.tools li.tools-share a').removeClass('tools-share-fixie6');
		});
	}
}

/*-----------------------------------
  TOOLS: EMAIL 
  -----------------------------------*/

function toolsemail(selector,subject) {
	typeof selector == "undefined" ? selector = ".tools-email a" : selector;
	typeof subject == "undefined" ? subject = "Articolo da segnalare" : subject;
	
	$(selector).click(function(){ 
		var link = 'mailto:?subject='+escape(subject)+'&body='+escape(subject + '\n' + parent.location.href);
		$(this).attr({href: link});
	});
}




/*-----------------------------------
  TOOLS: Breadcrumb 
  -----------------------------------*/
function breadcrumb(divider) {
	typeof divider == "undefined" ? divider = " / " : divider;
	// breadcrumb
	$("ul.breadcrumb li:has(a)").append(divider);
}


/*-----------------------------------
  TOOLS: SMOOTH SCROLL 
// http://www.learningjquery.com/2007/10/improved-animated-scrolling-script-for-same-page-links
// major changes by Paul Armstrong and Zachary Johnson
  -----------------------------------*/
function enable_smooth_scroll() {
    function filterPath(string) {
        return string
                .replace(/^\//,'')
                .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
                .replace(/\/$/,'');
    }

    var locationPath = filterPath(location.pathname);

    var scrollElement = 'html, body';
    $('html, body').each(function () {
        var initScrollTop = $(this).attr('scrollTop');
        $(this).attr('scrollTop', initScrollTop + 1);
        if ($(this).attr('scrollTop') == initScrollTop + 1) {
            scrollElement = this.nodeName.toLowerCase();
            $(this).attr('scrollTop', initScrollTop);
            return false;
        }    
    });

	$('a[href*=#]').each(function() {
        var thisPath = filterPath(this.pathname) || locationPath;
        if  (   locationPath == thisPath
                && (location.hostname == this.hostname || !this.hostname)
                && this.hash.replace(/#/, '')
            ) {
                if ($(this.hash).length) {
                    $(this).click(function(event) {
                        var targetOffset = $(this.hash).offset().top;
                        var target = this.hash;
                        event.preventDefault();
                        $(scrollElement).animate({scrollTop: targetOffset}, 500, function() {
                            location.hash = target;
                        });
                    });
                }
        }
    });
}


/*----------------------------------------------------------------------
  FINE TOOLS 
----------------------------------------------------------------------*/



function formToggle(p1, p2){
    $('input'+'#'+p1).focus(function () {
        if (this.value == p2) {this.value = '';}
    });
    $('input'+'#'+p1).blur(function () {
        if (this.value == '') {this.value = p2;}
    });
}

 
function checkform(form,input,searchtermdefault,msg) {
$(form).submit(function() {
	if(typeof msg == 'undefined') msg = "Inserire almeno una parola per la ricerca";
	if($(input).val() == searchtermdefault || $(input).val() == '' ) {
		alert(msg);
		return false;
		}
	});
}


/* Icone media*/
function mediaicon() {      
	$('.media-foto dt a').append('<span class="media-icon media-icon-foto">Foto</span>');
	$('.media-video dt a').append('<span class="media-icon media-icon-video">Video</span>');
	$('.media-audio dt a').append('<span class="media-icon media-icon-audio">Audio</span>');
	$('.media-interattivo dt a').append('<span class="media-icon media-icon-interattivo">Interattivo</span>');
	//pngfix('.media-icon');
	//DD_belatedPNG.fix('.media-icon');
};

function tab(div,tabattivo,rnum) {
   if(typeof tabattivo == 'undefined') tabattivo = 1;
if(tabattivo == 'random') tabattivo = (Math.floor(Math.random()*rnum))+1;
   if($("#"+div+"-nav").length == 1) {
       new Yetii({id: div, active: tabattivo});
   } else {
       $("#"+div).hide();
   }
}

function meteotab(div,tabattivo) {
	if(typeof tabattivo == 'undefined') tabattivo = 1;
	if($("#"+div+"-nav").length == 1) {
		new Yetii({id: div, active: tabattivo});
	} else {
		$("#"+div).hide();
	}
}


function equalHeight(group) {
	tallest = 0;
	group.each(function() {
		thisHeight = $(this).height();
		if(thisHeight > tallest) {
			tallest = thisHeight;
		}
	});
	group.height(tallest);
}


/* -- POPUP WINDOW -- */
jQuery.fn.popupwindow=function(p)
{var profiles=p||{};return this.each(function(index){var settings,parameters,mysettings,b,a;mysettings=(jQuery(this).attr("rel")||"").split(",");settings={height:600,width:600,toolbar:0,scrollbars:0,status:0,resizable:1,left:0,top:0,center:0,createnew:1,location:0,menubar:0};if(mysettings.length==1&&mysettings[0].split(":").length==1)
{a=mysettings[0];if(typeof profiles[a]!="undefined")
{settings=jQuery.extend(settings,profiles[a]);}}
else
{for(var i=0;i<mysettings.length;i++)
{b=mysettings[i].split(":");if(typeof settings[b[0]]!="undefined"&&b.length==2)
{settings[b[0]]=b[1];}}}
if(settings.center==1)
{settings.top=(screen.height-(settings.height+110))/2;settings.left=(screen.width-settings.width)/2;}
parameters="location="+settings.location+",menubar="+settings.menubar+",height="+settings.height+",width="+settings.width+",toolbar="+settings.toolbar+",scrollbars="+settings.scrollbars+",status="+settings.status+",resizable="+settings.resizable+",left="+settings.left+",screenX="+settings.left+",top="+settings.top+",screenY="+settings.top;jQuery(this).bind("click",function(){var name=settings.createnew?"PopUpWindow"+index:"PopUpWindow";window.open(this.href,name,parameters).focus();return false;});});};

var profiles={infografica:{height:800,width:1040,status:1,scrollbars:1},window200:{height:200,width:200,status:1,resizable:0},windowCenter:{height:500,width:600,center:1},windowNotNew:{height:650,width:800,center:1,createnew:0,scrollbars:1}};$(function()
{$(".popupwindow").popupwindow(profiles);});



function tablesorter() {
	$('.table td:first-child').css('border-left', 'none');
	if($("#table-1").length == 1) {		
		$('#table-1').tablesorter({widgets: ['zebra']});
	}
    if($("#table-2").length == 1) {	
		$('#table-2').tablesorter({widgets: ['zebra']});
	}
    
	$('.trigger-link').click(function () {
	  var rel = $(this).attr('rel');
	  var relate = rel.split('-');
	  var sorting = [[relate[0],relate[1]],[relate[2],relate[3]]]; // set sorting column and direction, this will sort on the first and third column the column index starts at zero  
	  $('#table-1').trigger('sorton',[sorting]); // sort on the first column   
	  return false; // return false to stop default link action 
	 });
}

function uniform() {
	$("select.uniform").uniform();
	$(":radio.uniform").uniform();
	$(":checkbox.uniform").uniform();
}


/* -- ticker con i titoli repubblica.it -- */
$(document).ready(function(){
	
	var speed = 700;
	var pause = 5000;
	
	function newsticker()
	{
	    last = $('ul#listticker li:last').hide().remove();
	    $('ul#listticker').prepend(last);
        $('ul#listticker li:first').slideDown("slow");
	}
	
	interval = setInterval(newsticker, pause);
});

/* trovaindirizzi form */
function trovaindirizzi(form,p1,light,dark){
	typeof light == "undefined" ? light = "#999" : light;
	typeof dark == "undefined" ? dark = "#222" : dark;
	var p2 = $('input'+p1).val();
	
	// focus
    $('input'+p1).focus(function () {
        if (this.value ==  p2) {
        	this.value = '';
        	$('input'+p1).css({"color":dark});
        }
    });

    $('input'+p1).blur(function () {
        if (this.value == '') {
        	this.value =  p2;
        	$('input'+p1).css({"color":light});
        }
    });

    //submit
	$(form).submit(function() {	
	//if($('input'+p1).val() ==  p2 || $('input'+p1).val() == '' ) {
		//alert("Inserire almeno una parola per la ricerca");
		//return false;//}/**/
		if ($('#cosa').val()=='Cosa vuoi cercare?') {
			$('#cosa').val('');
		}
		
		if ($('#vicino').val()=='Vicino a') {
			$('#vicino').val('');
		}				
	})   
}



function mediagallery(){
  
$('ul#list').each(function()
{
   var select=$(document.createElement('select')).insertBefore($(this).hide());
   $('>li a', this).each(function()
   { 
 option=$(document.createElement('option')).appendTo(select).val(this.href).html($(this).html());
   });
   select.change(function(){
    window.location.href = this.value;
  })
});

 
}


// Finestre sendmail
function sendmail(to1,to2) {
var string="mailto:"+to1+"@"+to2;
document.location=string;
}


// bottone facebook
function likebutton() {
	$(document).ready(function() {
		if($('#fb-root').length!=0) {
	        window.fbAsyncInit = function() {
	           FB.init({appId: '124998494210426', status: true, cookie: true,
	                   xfbml: true});
			try{
				$('#fb-like-head').html('<fb:like name="platform" layout="button_count" show_faces="true" width="100" action="recommend" colorscheme="light" height="21" id=""></fb:like>');
				$('#fb-like-foot').html('<fb:like name="platform" layout="standard" show_faces="false" width="450" action="recommend" font="arial" colorscheme="light" height="35" ></fb:like>');
			}  catch(e){}

	        };
	        (function() {
	          var e = document.createElement('script'); e.async = true;
	          e.src = document.location.protocol +
	            '//connect.facebook.net/it_IT/all.js';
	          document.getElementById('fb-root').appendChild(e);
	        }());
		}
	});
}

/*negozi*/
$(document).ready(function() { 
   $('#s3slider').s3Slider({ 
      timeOut: 4000 
   });
});
