var special2html=function(s){
	var regX = /\r?\n/g;
	return s.replace(regX, "<br />\n");
}

function html2text(html) { return $('<div>' + html + '</div>').text(); }

var getVideoData=function(vid){
	var url = "http://gdata.youtube.com/feeds/api/videos/"+vid+"?v=2&alt=jsonc";
	//alert(url);
	var ret=new Object();
	var title;
	var description;
	var viewcount;
	var views;
	var author;
	$.getJSON(url,function(data){
  	     ret.title = data.title;
   	     ret.description = data.description;
   	     //ret.viewcount = data.entry.yt$statistics.viewCount;
	});
	return ret;
}
jQuery.fn.extend({
	xtooltip: function (name){
        $(this).each(function(i){
            if($(this).attr('title') && $(this).attr('title')!==undefined){
                var my_tooltip=$("<div class='"+name+"' id='"+name+i+"'><div>"+$(this).attr('title')+"</div></div>").hide().appendTo($("body"));
                var topmarg=my_tooltip.css('margin-top');
                $(this).removeAttr("title").mouseover(function(kmouse){
                    my_tooltip.css({
                        'margin-top':parseInt(topmarg)-100+"px", 
                        left:$(this).offset().left+$(this).width()/2,
                        top:$(this).offset().top,
                        opacity:0, 
                        display:"block"
                    }).animate({
                        opacity:0.8,
                        'margin-top':topmarg
                    },400);
                }).mouseout(function(){
                    my_tooltip.fadeOut(200);
                });
            }
        });
        return $(this);
    },
	tooltip: function (name){
		$(this).each(function(i){
			if($(this).attr('title')){
				var my_tooltip=$("<div class='"+name+"' id='"+name+i+"'><div>"+$(this).attr('title')+"</div></div>").appendTo($("body"));
				$(this).removeAttr("title").mouseover(function(kmouse){
					my_tooltip.css({"margin-left":"-110px","margin-top":"-300px", left:kmouse.pageX, top:kmouse.pageY, opacity:0, display:"block"}).animate({
						opacity:0.8,
						"margin-top":"-180"
					},400);
					}).mousemove(function(kmouse){
						my_tooltip.css({left:kmouse.pageX, top:kmouse.pageY});
					}).mouseout(function(){
						my_tooltip.fadeOut(200);
					});
				}
			});
		},
	youThumb: function( size ){
		$this=this;
		if($this.attr('href')){
		var yurl=$this.attr('href');
		size = (size === null) ? "small" : size;
		var vid;
		var results;

//    if(yurl.indexOf('youtube')>-1){
		results = yurl.match("[\\?&]v=([^&#]*)");
		vid = results[1];
		if(size == "small"){
			thumburl="http://img.youtube.com/vi/"+vid+"/1.jpg";
		}
		else
		{
				thumburl="http://img.youtube.com/vi/"+vid+"/0.jpg";
		}
		$this.click(function(ev){
			ev.preventDefault();
			overlay({url:$this.attr('href'),type:'youtube',w:480,h:360});
			}).addClass('youThumb').html('');
		var vthumb=$('<div><div class="youThumbPlay"></div></div>').appendTo($this);
		vthumb.css({background:'url('+thumburl+') no-repeat center center'});
		$.getJSON("http://gdata.youtube.com/feeds/api/videos/"+vid+"?v=2&alt=jsonc",function(vdata){
			$('<div style="position:absolute;font-size:16px">'+vdata.data.title+'</div>').addClass('vdata').css({ opacity: 0.75 }).appendTo(vthumb);
			$this.attr('title',vdata.data.title);
		});
}
//	}
	return $this;
  },
	antispam : function()
	{
		$this=this;
		var eml=$this.text().replace("[AT]", "@");
		eml=eml.replace("[DOT]", ".");
		$this.text(eml).attr('href','mailto:'+eml);
		return $this;
	}
	,
	disableSelection: function()
	{
		return this.each(function()
		{
			this.onselectstart = function()
			{
				return false;
			}
			;
			this.unselectable = "on";
			jQuery(this).css('user-select', 'none');
			jQuery(this).css('-o-user-select', 'none');
			jQuery(this).css('-moz-user-select', 'none');
			jQuery(this).css('-khtml-user-select', 'none');
			jQuery(this).css('-webkit-user-select', 'none');
		}
		);
	}
	,
	center : function()
	{
		this.css("position", "fixed");
		this.css("top", ($(window).height() - this.outerHeight()) / 2 + $(window).scrollTop() + "px");
		this.css("left", ($(window).width() - this.outerWidth()) / 2 + $(window).scrollLeft() + "px");
		return this;
	}
	});
var mainmenu = function()
{
	$(" #nav ul ").css({
		display: "none"
		}); // Opera Fix
	$(" #nav li").hover(function()
	{
		$(this).find('ul:first').css({
			visibility: "visible",
			display: "none"
			}).show(300);
	}
	, function()
	{
		$(this).find('ul:first').css({
			visibility: "hidden"
			});
	}
	);
}

/*

function loadGmap(address,div)
{
	if (GBrowserIsCompatible())
	{
		var mapOptions = {
			zoom: 4,
			scaleControl: true,
			navigationControl: true
		}
		var map = new GMap2(document.getElementById(div),mapOptions);
		map.setMapType(G_PHYSICAL_MAP);
		map.disableInfoWindow();
		map.enableContinuousZoom();
		var geocoder = new GClientGeocoder();
		geocoder.getLatLng(
		address, function(point)
		{
			if (!point)
			{
				alert(address + " not found");
			}
			else {
				map.setCenter(point, 13);
				var marker = new GMarker(point);
				map.addOverlay(marker);
				marker.openInfoWindowHtml(address);
				map.setUIToDefault();
			}
		}
		);
	}
	$('#overlay').css('position','fixed').show(600);
}
*/

function $_GET(name)
{
	name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
	var regexS = "[\\?&]" + name + "=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(window.location.href);
	if (results == null) 
	return "";
	else 
	return decodeURIComponent(results[1].replace(/\+/g, " "));
}

var preloadImmagini = function(par)
{
	var defaults = {
		callback: function()
		{
			return false
			},
		testo: null,
		url: null,
		timeout:15000
	}
	par = jQuery.extend(defaults, par);
	var preloadTimer=setTimeout(function()
	{
		finePreload();
	}
	,par.timeout);
	var ovl = $('<div class="preloaderCSS"></div>').appendTo('BODY');
	var loadtxt = $('<div class="loadtxt"></div>').appendTo(ovl);
	var loadbar=$('<div class="loadbar"></div>').appendTo(ovl);
	var loaded=$('<div class="loaded"></div>').appendTo(loadbar);
	var urls = [];
	var allimages = [];
	var imgloaded = 0;
	var aggiorna = function()
	{
		var perc = ''+parseInt(imgloaded / urls.length * 100+1) + '%';
		loaded.stop().animate({width:perc},50);
		if (imgloaded++ >= urls.length - 1)
		{
			finePreload();
		}
	}
	var finePreload=function()
	{
		clearTimeout(preloadTimer);
		ovl.delay(200).fadeOut();
		par.callback();
	}
	var csstxt = '';
	var s = document.styleSheets.length;
	while (s--)
	{
		var mySheet = document.styleSheets[s];
		var rules = mySheet.cssRules ? mySheet.cssRules : mySheet.rules;
		var r = rules.length;
		while (r--)
		{
			if (rules[r].style && rules[r].style.cssText.toLowerCase().indexOf('url') != -1)
			{
				csstxt += ' ' + rules[r].style.cssText + ';';
			}
		}
	}
	var cssarr = csstxt.split(';');
	var i = cssarr.length;
	while (i--)
	{
		if (cssarr[i].toLowerCase().indexOf('url') > -1)
		{
			//urls.push(cssarr[i].toLowerCase().substr(cssarr[i].indexOf('(') + 1).replace(')', ''));
			urls.push(cssarr[i].substr(cssarr[i].indexOf('(') + 1).replace(')', ''));
		}
	}
	$('BODY *').each(function()
	{
		url = $(this).css('background-image').replace('url(', '').replace(')', '').replace(/"/g, '');
		if (url != 'none')
		{
			urls.push(url);
		}
		});
	$('BODY img').each(function()
	{
		if (url = $(this).attr('src'))
		{
			urls.push(url);
		}
		});
	var nimg = urls.length + 1;
	while (nimg--)
	{
		allimages[nimg] = new Image();
		$(allimages[nimg]).load(function(nimg)
		{
			aggiorna();
		}
		);
		$(allimages[nimg]).error(function()
		{
			aggiorna();
		}
		);
		$(allimages[nimg]).attr('src',urls[nimg]);
	}
}


var overlay = function(par)
{
	var defaults = {
		callback: function()
		{
			return false
			},
		color: '#000',
		opacity: .5,
		type: 'img',
		url: null,
		w: 300,
		h: 120
	}
	par = jQuery.extend(defaults, par);
	var close = function()
	{
		cont.fadeOut(function()
		{
			cont.remove();
			overlay.fadeOut(function()
			{
				overlay.remove();
			}
			);
		}
		);
	}
	var overlay = $('<div></div>').css({
		'padding': '0 auto 0 auto',
		'width': '100%',
		'height': '100%',
		'position': 'fixed',
		'z-index': 10000,
		'top': 0,
		'left': 0,
		'display': 'none'
		}).appendTo($('BODY'));
	var bg = $('<div></div>').css({
		'background-color': par.color,
		'width': '100%',
		'height': '100%',
		'position': 'absolute',
		'z-index': 1,
		'top': 0,
		'left': 0,
		'opacity': par.opacity
		}).click(function()
	{
		close();
	}
	).appendTo(overlay);
	var cont = $('<div></div>').css({
		'width': par.w + 'px',
		'height': par.h + 'px',
		'margin-left': '-' + (par.w / 2) + 'px',
		'position': 'absolute',
		'z-index': 2,
		'background-color': '#fff',
		'border-radius': '5px',
		'padding': '10px',
		'border': '1px solid #333',
		'top': '10%',
		'left': '50%',
		display:'none'
		}).appendTo(overlay);
	var loader = $('<div></div>').css({background:'url(images/loader.gif) no-repeat center center',width:'100%',height:'100%'}).appendTo(cont);
	var closebutt = $('<div></div>').css({
		'cursor': 'pointer',
		'position': 'absolute',
		'z-index': 2,
		'background': 'url(images/button-overlay_close.png)',
		'width': '42px',
		'height': '42px',
		'top': 0,
		'right': 0,
		'margin': '-24px -24px 0 0'
		}).appendTo(cont).click(function()
	{
		close();
	}
	);
	var load = function()
	{
		cont.show();
		loader.show();
		if (par.type == 'img')
		{
			img = $('<img>').css({
				'display': 'none'
				}).appendTo(cont);
			img.load(function()
			{
				loader.hide();
				cont.animate({
					'width': img.width() + 'px',
					'height': img.height() + 'px',
					'margin-left': '-' + (img.width() / 2) + 'px'
					}, function()
				{
					img.fadeIn();
				}
				);
			}
			);
			img.error(function()
			{
				loader.hide();
				cont.html('Errore di caricamento');
			}
			);
			img.attr('src', par.url);
		}
		if (par.type == 'youtube')
		{
			var video_id = par.url.split('v=')[1];
			var ampersandPosition = video_id.indexOf('&');
			if (ampersandPosition != -1)
			{
				video_id = video_id.substring(0, ampersandPosition);
			}
			loader.hide();
			var emb = $('<embed src="http://www.youtube.com/v/' + video_id + '&autoplay=1&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" play="true" width="' + par.w + '" height="' + par.h + '">').appendTo(cont);
		}
	}
	overlay.fadeIn(load());
	$('BODY').keyup(function(e)
	{
		if (!e) 
		e = window.event;
		if (e.keyCode == 27)
		{
			close();
		}
		});
}
$(document).ready(function()
{
	$('#checkJS').remove();
	$('a.email').antispam();
	$("#tabsRicerca").tabs();
	mainmenu();
	$('#nav').disableSelection();
	FLIR.init({
		path: 'facelift/'
		});
	$("h1,h2,#nav a,label,.flir").each(function()
	{
		FLIR.replace(this);
	}
	);
	$('.thumb').each(function()
	{
		var imgurl = $(this).attr('href');
		$(this).click(function(e)
		{
			e.preventDefault();
			overlay({url: imgurl});
		});
	});
	preloadImmagini();
	$("a,img,input,div").tooltip("tooltip");
	$('a[href^="http://www.youtube.com/watch"]').youThumb();
	//$.getScript('http://static.ak.fbcdn.net/connect.php/js/FB.Share');
	//$.getScript('http://platform.twitter.com/widgets.js');
	/*$.youtubin({
        swfWidth : 550,
        swfHeight : 400
    });*/
}
);

