/*
	JavaScript Toolbar Intoscana
	@author = Andrea Bianchin	
*/

/* OPEN/CLOSE MyToscanaBox */
function readCookie(name){
	var cookieValue = "";
	var search = name + "=";
	if(document.cookie.length > 0){ 
		offset = document.cookie.indexOf(search);
		if (offset != -1){ 
      			offset += search.length;
			end = document.cookie.indexOf(";", offset);
			if (end == -1) end = document.cookie.length;
			cookieValue = unescape(document.cookie.substring(offset, end))
		}
	}
	return cookieValue;
}
/* OPEN/CLOSE MyToscanaBox */

$.noConflict();

jQuery(document).ready(function($) {


Toolbar = {
	init : function(){
		
		
		jQuery('input:checkbox').eachNew(function(){
			//jQuery(this).skin();
		});
		
		ajaxsearch = '';
		ajaxlast = '';
		ajaxcurl = '';
		ajaxsearch2 = '';
		ajaxlast2 = '';
		ajaxcurl2 = '';
		ajaxDigg = '';
		keyAPI = 'UN2uPVknmXsiB13tGrYsxg';
		jQuery.getScript('http://platform.twitter.com/anywhere.js?id='+keyAPI+'&v=1');

		
		jQuery(document).mousemove(function(e){
			posx = e.pageX;
			posy = e.pageY;
		});
		Toolbar.tabSchede();
if(jQuery('#lista_rss_9')){
	blogrssbar('/intoscana2/opencms/system/modules/it.inera.opencms.templates/intoscana/xml/feedreader.xml?rss=tuscanyarts', 'lista_rss_4');
	blogrssbar('/intoscana2/opencms/system/modules/it.inera.opencms.templates/intoscana/xml/feedreader.xml?rss=aroundtuscany', 'lista_rss_7');
	blogrssbar('/intoscana2/opencms/system/modules/it.inera.opencms.templates/intoscana/xml/feedreader.xml?rss=trends', 'lista_rss_8');
	blogrssbar('/intoscana2/opencms/system/modules/it.inera.opencms.templates/intoscana/xml/feedreader.xml?rss=tunes', 'lista_rss_6');
	blogrssbar('/intoscana2/opencms/system/modules/it.inera.opencms.templates/intoscana/xml/feedreader.xml?rss=tuscanycious', 'lista_rss_5');
	blogrssbar('/intoscana2/opencms/system/modules/it.inera.opencms.templates/intoscana/xml/feedreader.xml?rss=diari', 'lista_rss_9');
} 
	},

	selStep : function(n,step){
		if(step=='-'){
			valBefore = jQuery('#int_'+n).attr('value');
			if(valBefore!='0'){
				valAfter = valBefore-1;
				jQuery('#elem_'+n).attr('class','step'+valAfter);
				jQuery('#int_'+n).attr('value',valAfter);
			}
		}else{
			if(step=='+'){
				valBefore = jQuery('#int_'+n).attr('value');
				if(valBefore!='3'){
					valAfter = Number(valBefore)+1;
					jQuery('#elem_'+n).attr('class','step'+valAfter);
					jQuery('#int_'+n).attr('value',valAfter);
				}		
			}else{
				jQuery('#elem_'+n).attr('class','step'+step);
				jQuery('#int_'+n).attr('value',step);
			}
		}
	},

	checkStep : function(){	
		for(i=0;i<7;i++){
			valNow = jQuery('#int_'+i).attr('value');
			jQuery('#elem_'+i).attr('class','step'+valNow);
		}
	},

		createLayer: function () 

	{

		if(jQuery('.toolbar-layer').length==0){

            toolbarLayer = jQuery('<div class="toolbar-layer" style="display:none;"></div>');

            toolbarLayerImg = jQuery('<img src="/intoscana2/export/system/modules/it.inera.opencms.templates/intoscana/toolbar/i/toolbar-layer-img.png" class="png" />');

            toolbarLayerImgCloseLink = jQuery('<a href="javascript:;" class="close"></a>');

            toolbarLayerImgClose = jQuery('<img src="/intoscana2/export/system/modules/it.inera.opencms.templates/intoscana/toolbar/i/toolbar-layer-close.png" class="pngClose" />');

            toolbarLayerCont = jQuery('<div class="cont">&nbsp;</div>');        

            jQuery(toolbarLayer).append(toolbarLayerImg);

            jQuery(toolbarLayerImgCloseLink).append(toolbarLayerImgClose);

            jQuery(toolbarLayer).append(toolbarLayerImgCloseLink);

            jQuery(toolbarLayer).append(toolbarLayerCont);

            jQuery('body').append(toolbarLayer);

            jQuery('.toolbar-layer').fadeIn(600);

        }   

	},

	

	setLayerProperties: function (w, h, center, side)

	{



		if(jQuery('.toolbar-layer').length!=0){ 

            if(center){

                if(center=='blog'){                 

                    wtot = jQuery(document).width();

                    rgt = (wtot-w)/2;

                    jQuery('.toolbar-layer').css('right',rgt+'px');

                    jQuery('.toolbar-layer').css('left','auto');

                    jQuery('.toolbar-layer .png').css('left',posx-rgt+10+'px');

                    jQuery('.toolbar-layer .png').css('right','auto');

                }else if(center=='usrToolBar'){

                    posx = jQuery('#' + center).position().left + 130;

                    if(posx<jQuery(document).width()/2){

                        var posLft = posx-20;

                        if(posLft<6){ lft = 5; }else{ lft = posLft; }

                        jQuery('.toolbar-layer').css('left',lft+'px');

                        jQuery('.toolbar-layer').css('right','auto');

                        jQuery('.toolbar-layer .png').css('left','25px');

                        jQuery('.toolbar-layer .png').css('right','auto');

                    }else{

                        var posRgt = jQuery(document).width()-posx-20;

                        if(posRgt<6){ rgt = 5; }else{ rgt = posRgt; }       

                        jQuery('.toolbar-layer').css('right',rgt+'px');

                        jQuery('.toolbar-layer').css('left','auto');

                        jQuery('.toolbar-layer .png').css('right','25px');

                        jQuery('.toolbar-layer .png').css('left','auto');

                    }

                }

            }else{

            	if ( side ) posx -= 39; 

                if( posx < jQuery(document).width() / 2){

                    lft = (posx - 20) < 6 ? 5 : (posx-20);

                    jQuery('.toolbar-layer')

	                    .css({ left: lft+'px', right: "auto" })

	                    .find ( ".png" )

	                    	.css ({ left: "25px", right: "auto"	});

                } else {

                    var posRgt = jQuery(document).width()-posx-20;

                    if(posRgt<6){ rgt = 5; }else{ rgt = posRgt; }       

                    jQuery('.toolbar-layer').css('right',rgt+'px');

                    jQuery('.toolbar-layer').css('left','auto');

                    jQuery('.toolbar-layer .png').css('right','25px');

                    jQuery('.toolbar-layer .png').css('left','auto');

                }

            }

            if(h=='auto'){

                realH = 'auto';

                realHIframe = '100%';

            }else{

                realH = h+'px'; 

                realHIframe = h;    

            }   

            

            if(w=='auto'){

                realW = 'auto';

                realWIframe = '100%';

            }else{

                realW = w+'px'; 

                realWIframe = w;    

            }       

            

            jQuery('.toolbar-layer > .cont').css({

                'width' : realW,

                'height' : realH

            });     

            jQuery('.toolbar-layer > .cont').html('<img style="margin:20px;" src="/intoscana2/export/system/modules/it.inera.opencms.templates/intoscana/toolbar/i/loader-tw.gif" alt="Caricamento..." />');

            

            


                
     jQuery('.toolbar-layer > .close').click(function(){

                jQuery('.toolbar-layer').fadeOut(500, function() {

                    jQuery('.toolbar-layer').remove();

                    if(ajaxsearch){ajaxsearch.abort()}

                    if(ajaxlast){ajaxlast.abort()}

                    if(ajaxcurl){ajaxcurl.abort()}

                    if(ajaxsearch2){ajaxsearch2.abort()}

                    if(ajaxlast2){ajaxlast2.abort()}

                    if(ajaxcurl2){ajaxcurl2.abort()}

                    if(ajaxDigg){ajaxDigg.abort()}

                                /* OPEN/CLOSE MyToscanaBox */

                    document.cookie='open'+ "=" +escape('false') + ";path=/";

                                        /* OPEN/CLOSE MyToscanaBox */

					jQuery ("[collision_hided=1]").removeAttr("collision_hided").show();

                });

            });     

            jQuery(document).click(function(e) {

				if ( e.target.parentNode.name != "social-toolbar-opener") {

	                if(e.target.nodeName=='A'){

	                    if(jQuery('.toolbar-layer').length>0){

	                        document.cookie='open'+ "=" +escape('true') + ";path=/";

	                        return;

	                    }else{

	                        document.cookie='open'+ "=" +escape('false') + ";path=/";

	                        return;

	                    }

	                } 

	                jQuery('.toolbar-layer').fadeOut(500, function() {

	                    jQuery('.toolbar-layer').remove();                  

	                    if(ajaxsearch){ajaxsearch.abort()}

	                    if(ajaxlast){ajaxlast.abort()}

	                    if(ajaxcurl){ajaxcurl.abort()}

	                    if(ajaxsearch2){ajaxsearch2.abort()}

	                    if(ajaxlast2){ajaxlast2.abort()}

	                    if(ajaxcurl2){ajaxcurl2.abort()}

	                    if(ajaxDigg){ajaxDigg.abort()}

	                    document.cookie='open'+ "=" +escape('false') + ";path=/";

	                });

	                   jQuery('.tag-layer').fadeOut(500, function() {

	                    jQuery('.tag-layer').remove();  

	                 });

	                 jQuery ("[collision_hided=1]").removeAttr("collision_hided").show();

				}



            });

            jQuery('#toolbar').click(function(e){ 

                e.stopPropagation(); 

            });

            jQuery('.toolbar-layer').click(function(e){

                e.stopPropagation();                 

            });

        } 

	},
	

    showLayer: function(w,h,url,center,side){



        this.createLayer ();

        this.setLayerProperties ( w, h, center, side);

        if ( url )

	        jQuery('.toolbar-layer > .cont').load(url,function(data){

	            Toolbar.init();

	            Toolbar.checkSchede();

	            /* OPEN/CLOSE MyToscanaBox */

	            document.cookie='open'+ "=" +escape('true') + ";path=/";

	        });

        

        setTimeout(function(){

            if(jQuery("#sortable").length!=0){

                jQuery("#sortable").sortable({ 

                    opacity: 0.6, 

                    update: function(event, ui) {

                        /*                  

                            Di seguito la chiamata ajax in POST per l'ordinamento delle schede.

                            

                            jQuery.post("http://www.intoscana.it/script-da-richiamare-per-ordinare-le-schede.jsp", 

                                {

                                    valore: "da-passare",

                                    altro: "valore-da-passare"

                                }

                            );

                        */

                    } 

                });

                jQuery("#sortable").disableSelection();

            }

        },1000);
		
	 setTimeout (function() {

        	var dangerElements = jQuery ("iframe").not (".toolbar-layer iframe");

			for ( var i=0; i<jQuery (dangerElements).size(); i++) {

				var target = jQuery (dangerElements).filter (":eq("+i+")"); 

				if ( Collision.test ( jQuery(target), jQuery(".toolbar-layer"), true ) ) {

					jQuery (target).hide().attr ("collision_hided", "1");

				}

			}

		}, 200);

        

    },

    
	
	checkSchede : function(){
		var h = 0;
		jQuery('#schede > .tabs > .content > #scrollerMTB > ul > li').eachNew(function(i,el){
			h += jQuery(el).height();						
		});
		hEl = jQuery('#schede > form > .tabs > .content').height()-50;
		if(h > hEl){
			jQuery('.navSchede').css("visibility","visible");
		}else{		
			jQuery('.navSchede').css("visibility","hidden");
		}
	},
	
	tabSchede : function(){
		jQuery('div#schede > div.head > ul.tab > li').eachNew(function(i,el){		
			jQuery(el).click(function(){			
				jQueryquesto = jQuery(this);			
				jQuery('.tabs').eachNew(function(j,elem){
					if(j==i){
						jQuery(elem).show();
					}else{
						jQuery(elem).hide();
					}
				});				
				jQuery('div#schede > div.head > ul.tab > li').eachNew(function(h,elmnt){
					if(h==i){
						jQuery(elmnt).removeClass("off");
					}else{
						jQuery(elmnt).addClass("off");
					}
				});				
			});			
		});
	},
	
	schede : function(dove){
		posAtt = jQuery('#schede > form > .tabs > .content > ul').css('top').split('px')[0];
		if(posAtt=='auto'){ /* for chrome & safari */
			posAtt = 0;
		}
		moveBy = jQuery('#schede > form > .tabs > .content').height()-50;
		hEl = jQuery('#schede > form > .tabs > .content > ul').css('height').split('px')[0];
		hCont = jQuery('#schede > form > .tabs > .content').css('height').split('px')[0];						
		maxMove = hEl-hCont;
		if(dove=='prev'){
			if(posAtt<0){
				jQuery('#schede > form > .tabs > .content > ul').animate({
					top: '+='+moveBy
					}, 500
				);						
			}
		};	
		if(dove=='next'){
			if(posAtt>-maxMove){
				jQuery('#schede > form > .tabs > .content > ul').animate({
					top: '-='+moveBy
					}, 500
				);							
			}	
		};
		
	},
	
	selAll : function(){					
		jQuery('#schede > form > .tabs > .content > ul > li > div.r > img.checkbox').eachNew(function(i,el){
			if(jQuery(el).attr("src").indexOf('_off')!=-1){
				jQuery(el).attr("src",jQuery(el).attr("src").split('_off')[0]+'_on'+jQuery(el).attr("src").split('_off')[1]);
			}
		})				
		jQuery('#schede > form > .tabs > .content > ul > li > div.r > input').eachNew(function(i,el){
			jQuery(el).attr("value","true");
		})				
	},
	
	delSel : function(){		
		jQuery('#schede > form > .tabs > .content > ul > li > div.r > input').eachNew(function(i,el){
			if(jQuery(el).attr("value")=="true"){							
				jQuery(el).parents('li').fadeOut(300, function() {
					jQuery(el).parents('li').remove();
					Toolbar.checkSchede();
					/*					
						Di seguito la chiamata ajax in POST per eliminare le schede selezionate.
						
						jQuery.post("http://www.intoscana.it/script-da-richiamare-per-eliminare-le-schede.jsp", 
							{
								valore: "da-passare",
								altro: "valore-da-passare"
							}
						);
					*/					
					idSelect = 'categoriaTAG';
					var optionz = new Array();				
					jQuery('#sortable > li > .tag > a').eachNew(function(e,i){
						optionz.push(jQuery(i).html())
					});				
					var newArray = Toolbar.uniq(optionz);				
					jQuery('#'+idSelect).html('<option value="all">Tutti i tag</option>');
					jQuery(newArray).eachNew(function(h,j){
						if(j!='aggiungi Tag'){
							tags = jQuery('<option value="'+j+'">'+j+'</option>')
							jQuery('#'+idSelect).append(tags);
						}
					});					
				});
			}		
		});
		jQuery('#schede > form > .tabs > .content > ul').animate({top:0},500);
	},
	
	addTag : function(e){
		testo = e.innerHTML;
		if(testo == 'aggiungi Tag'){
			testo = '';
		}
		jQuery('.tag-layer').remove();
		posLayer = jQuery('.toolbar-layer').position();
		ttop = posy-posLayer.top-100;
		lleft = posx-posLayer.left-60;		
		tagLayer = jQuery('<div class="tag-layer" style="top:'+ttop+'px; left:'+lleft+'px;"></div>');
		tagClose = jQuery('<a href="javascript:;" class="cls">X</a>');
		tagTitle = jQuery('<span>TAG</span>');
		tagClear = jQuery('<div class="cl"></div>');
		tagTextarea = jQuery('<textarea id="addTag">'+testo+'</textarea>');
		tagBtn = jQuery('<div class="btnThin"><div class="rgt"><div class="cent"><a href="javascript:;" title="OK">OK</a></div></div></div>');			
		jQuery(tagLayer).append(tagTitle);
		jQuery(tagLayer).append(tagClose);
		jQuery(tagLayer).append(tagClear);
		jQuery(tagLayer).append(tagTextarea);
		jQuery(tagLayer).append(tagBtn);
		jQuery(tagLayer).append(tagClear);
		jQuery('.toolbar-layer').append(tagLayer);
		jQuery('.tag-layer').fadeIn(600);
		idSelect = 'categoriaTAG';
		jQuery('#addTag').focus();
		jQuery(tagBtn).click(function(){			
			txt = jQuery('#addTag').val();
			reg = /\s/g;
			newtxt = txt.replace(reg,"");
			if(newtxt!=''){
				jQuery(e).html(jQuery('#addTag').val());				
			}else{
				jQuery(e).html("aggiungi Tag");
			}			
			var optionz = new Array();				
			jQuery('#sortable > li > .tag > a').eachNew(function(e,i){
				optionz.push(jQuery(i).html())
			});				
			var newArray = Toolbar.uniq(optionz);				
			jQuery('#'+idSelect).html('<option value="all">Tutti i tag</option>');
			jQuery(newArray).eachNew(function(h,j){
				if(j!='aggiungi Tag'){
					tags = jQuery('<option value="'+j+'">'+j+'</option>')
					jQuery('#'+idSelect).append(tags);
				}
			});			
			jQuery('.tag-layer').fadeOut(400,function(){
				jQuery('.tag-layer').remove();
					/*					
						Di seguito la chiamata ajax in POST per salvare tag.						
						jQuery.post("http://www.intoscana.it/script-da-richiamare-per-salvare-tag.jsp", 
							{
								valore: "da-passare",
								altro: "valore-da-passare"
							}
						);
					*/
			});			
		});
		jQuery(tagClose).click(function(){
			jQuery('.tag-layer').fadeOut(400,function(){
				jQuery('.tag-layer').remove();
			});	
		});
		
		
	},
	
	filterTag :function(){
		idSelect = 'categoriaTAG';		
		jQuery('#sortable > li > .tag > a').eachNew(function(e,i){
			if(jQuery('#'+idSelect).val()=='all'){
				jQuery(i).parent('.tag').parent('li').fadeIn(400);
			}else{
				if(jQuery(i).html()!=jQuery('#'+idSelect).val()){		
					jQuery(i).parent('.tag').parent('li').fadeOut(400);
				}else{
					jQuery(i).parent('.tag').parent('li').fadeIn(400);
				}
			}
						
		});		
	},
	
	uniq : function(a){
	   var r = new Array();
	   o:for(var i = 0, n = a.length; i < n; i++) {
		  for(var x = i + 1 ; x < n; x++)
		  {
			 if(a[x]==a[i]) continue o;
		  }
		  r[r.length] = a[i];
	   }
	   return r;
	},
	
	lightbox : function(title,url,wCont,hCont){
	
		hB = jQuery('body').height();
		wB = jQuery('body').width();
		topB = jQuery("html").scrollTop();		
		lCont = (wB-wCont)/2;
		tCont = topB+50;
		hInclude = hCont-55;
		
		bg = jQuery('<div id="lightbox-bg" style="filter:alpha(opacity=0); opacity: 0; background:#000; position:absolute; top:0; left:0; z-index:3000; height:'+hB+'px; width:'+wB+'px;"></div>');		
		cont = jQuery('<div id="lightbox-cont" style="filter:alpha(opacity=0); opacity: 0; background:#8e8d90; position:absolute; top:'+tCont+'px; left:'+lCont+'px; z-index:3001; height:'+hCont+'px; width:'+wCont+'px; padding:10px;"></div>');
 		inner = jQuery('<div class="lightbox-inner" style="background:#FFF; height:'+hCont+'px; width:'+wCont+'px;"></div>');
			head = jQuery('<div class="head"></div>');
				tit = jQuery('<h2>'+title+'</h2>');
				closeLightbox = jQuery('<a href="javascript:;" title="chiudi"><img src="/intoscana2/export/system/modules/it.inera.opencms.templates/intoscana/toolbar/i/toolbar-layer-close.png" class="png" alt="chiudi" /></a>');
				hr = jQuery('<div class="hr"></div>');
			include = jQuery('<div class="include" id="idLightbox" style="height:'+hInclude+'px; width:'+wCont+'px;"></div>');
	
		jQuery('body').append(bg);
 		jQuery(head).append(tit);
		jQuery(head).append(closeLightbox);
		jQuery(head).append(hr);
		jQuery(inner).append(head);
		jQuery(inner).append(include);
		jQuery(cont).append(inner);
 		jQuery('body').append(cont);
		
		jQuery('#idLightbox').html('<img style="margin:20px;" src="/intoscana2/export/system/modules/it.inera.opencms.templates/intoscana/toolbar/i/loader-tw.gif" alt="Caricamento..." />');
		jQuery('#lightbox-bg').animate({opacity: 0.6}, 500, function() {/*Animation complete*/ });
		jQuery('#lightbox-cont').animate({opacity: 1}, 500, function() {/*Animation complete*/ });	

		if(url.indexOf('.swf')!=-1){
			ww = wCont-0; 
			hh = hCont-55; 
			jQuery('.include').html('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="' + ww + '" height="' + hh + '" id="Slideshow" align="middle"><param name="FlashVars" value="" /><param name="allowScriptAccess" value="sameDomain" /><param name="allowFullScreen" value="true" /><param name="movie" value="' + url + '" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" /><embed src="' + url + '" quality="high" bgcolor="#ffffff" width="' + ww + '" height="' + hh + '" name="Slideshow" align="middle" FlashVars="" allowScriptAccess="sameDomain" allowFullScreen="true" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>');			
		}else{
			jQuery('.include').load(url,function(){Toolbar.init();});
		}

		jQuery('#lightbox-cont > .lightbox-inner > .head > a').click(function(){
			jQuery('#lightbox-bg').animate({opacity: 0}, 500, function() {jQuery('#lightbox-bg').remove();});
			jQuery('#lightbox-cont').animate({opacity: 0}, 500, function() {jQuery('#lightbox-cont').remove();});			
		})
		
		jQuery('#lightbox-bg').click(function(){
			jQuery('#lightbox-bg').animate({opacity: 0}, 500, function() {jQuery('#lightbox-bg').remove();});
			jQuery('#lightbox-cont').animate({opacity: 0}, 500, function() {jQuery('#lightbox-cont').remove();});			
		})
		
		jQuery(window).resize(function() {
			hB = jQuery('body').height();
			wB = jQuery('body').width();	
			topB = jQuery("html").scrollTop();		
			lCont = (wB-wCont)/2;
			tCont = topB+50;
			jQuery('#lightbox-bg').css({ 'height' : hB+'px', 'width' : wB+'px' });
			jQuery('#lightbox-cont').css({ 'left' : lCont+'px', 'top' : tCont+'px' });
		});
		
	},
	
	thisMovie :  function(movieName) {
        if (navigator.appName.indexOf("Microsoft") != -1) {
            return window[movieName];
        } else {
            return document[movieName];
        }
    },
	
	setFlashMapState : function(value) {
		if(value == "open"){
			flashMapOpened = true;
		}else{
			flashMapOpened = false;
		}
	},
	
	wheel : function(event){
		/* se il mouse si trova nell'oggetto flash disabilito lo scroll e mando l'evento al flash */
		if( mouseIsOverFlash  && flashMapOpened) {
			/* mando evento di mouse wheel al flash */
			
			if (event.wheelDelta) {
				delta2 = event.wheelDelta/120; 
				if (window.opera){
					delta2 = -delta2
				};
			}else{
				if (event.detail){
					delta2 = -event.detail/3;
				}
			}
			
			var o = {
						x: event.clientX, 
						y: event.clientY,
						delta: -delta2,
						ctrlKey: event.ctrlKey, 
						altKey: event.altKey,
						shiftKey: event.shiftKey
					}
			Toolbar.thisMovie("Slideshow").handleWheel(o);

			/* inibisco lo scroll */
			var delta = 0;
			if (!event) event = window.event;
			if (event.wheelDelta) {
				delta = event.wheelDelta/120; 
				if (window.opera) delta = -delta;
			} else if (event.detail) {
				delta = -event.detail/3;
			}
			if (delta)
				if (event.preventDefault)
						event.preventDefault();
				event.returnValue = false;
			
		}
	},

	flashControl : function(){
		flashMapOpened = false;
		flashMapIsOpen = false;
		if (window.addEventListener)
		window.addEventListener('DOMMouseScroll', Toolbar.wheel, false);
		window.onmousewheel = document.onmousewheel = Toolbar.wheel;

		/* Controllo se il mouse è sopra l'oggetto flash */
		mouseIsOverFlash = false;		
		//var obj = Toolbar.thisMovie("Slideshow");	

		jQuery("#emotional").mouseover(function(){
			mouseIsOverFlash = true;
		});
		jQuery("#emotional").mouseout(function(){
			mouseIsOverFlash = false;
		});
		
/* 		obj.onmouseover = function(){
			mouseIsOverFlash = true;			
		};
		obj.onmouseout = function(){
			mouseIsOverFlash = false;			
		}
 */	},
	
	register :	function(val){		
		jQuery('#'+val).submit();
	},
	
	share :	function(share){		
		urlP = document.location.href;
		
		if(urlP.indexOf('localhost')!=-1){
			urlPage = "http://www.google.it";
		}else{
			urlPage = urlP;
		}
		
		titlePage = document.title;
		
		if(share=='mail'){
			location.href = "mailto:?subject="+titlePage+"&body="+titlePage+"%0A"+urlPage+"%0A%0A%0A";
		}
		if(share=='facebook'){		
			myUrl = "http://www.facebook.com/share.php?u="+urlPage+"&t="+titlePage;
		}
		if(share=='twitter'){
			login = 'fondazionesistematoscana';
			apiKey = 'R_5b727b96fc7e923cc6f4dc568081a9b4';	
			daurl = "http://api.bit.ly/shorten?version=2.0.1&longUrl="+urlPage+"&login="+login+"&apiKey="+apiKey+"&format=json&callback=?";
			jQuery.getJSON(daurl, function(json){
				myUrl = "http://twitter.com/home?status="+titlePage+" : "+json.results[urlPage].shortUrl;
				window.open(myUrl,'popShare','width=800, height=600, toolbar=no, location=no, status=no, menubar=no, scrollbars=yes, resizable=yes');			});		
		}
		if(share=='delicious'){		
			myUrl = "http://delicious.com/save?v=5&noui&jump=close&url="+urlPage+"&title="+titlePage;
		}
		if(share=='stumbleupon'){		
			myUrl = "http://www.stumbleupon.com/submit?url="+urlPage+"&title="+titlePage;
		}
		if(share=='digg'){		
			myUrl = "http://digg.com/submit?phase=2&url="+urlPage+"&title="+titlePage;
		}
		if(share=='buzz'){		
			myUrl = "http://buzz.yahoo.com/buzz?targetUrl="+urlPage;
		}
		if(share=='myspace'){		
			myUrl = "http://www.myspace.com/Modules/PostTo/Pages/?u="+urlPage+"&t="+titlePage;
		}
		if(share=='friendfeed'){		
			myUrl = "http://friendfeed.com?title="+titlePage+"&url="+urlPage;
		}
		if(share=='technorati'){		
			myUrl = "http://www.technorati.com/faves?add="+urlPage;
		}
		if(share=='bookmarks'){		
			myUrl = "http://www.google.com/bookmarks/mark?op=edit&bkmk="+urlPage+"&title="+titlePage;
		}
		if(share=='live'){		
			myUrl = "https://favorites.live.com/quickadd.aspx?marklet=1&mkt=en-us&url="+urlPage+"&title="+titlePage;
		}
		
		if(share!='mail'){
			if(share!='twitter'){
				setTimeout(function(){window.open(myUrl,'popShare','width=800, height=600, toolbar=no, location=no, status=no, menubar=no, scrollbars=yes, resizable=yes');},1000);
			}
		}
		
	},
	
	loader: function(){		
		wCont = 500;
		hCont = 150;		
		hB = jQuery('body').height();
		wB = jQuery('body').width();
		topB = jQuery("html").scrollTop();		
		lCont = (wB-wCont)/2;
		tCont = topB+100;
		hInclude = hCont-55;		
		bg = jQuery('<div id="lightbox-bg" style="filter:alpha(opacity=0); opacity: 0; background:#000; position:absolute; top:0; left:0; z-index:3000; height:'+hB+'px; width:'+wB+'px;"></div>');		
		cont = jQuery('<div id="lightbox-cont" style="filter:alpha(opacity=0); opacity: 0; position:absolute; top:'+tCont+'px; left:'+lCont+'px; z-index:3001; height:'+hCont+'px; width:'+wCont+'px; padding:10px; text-align:center; color:#fff; font-size:12px;">Caricamento...<br /><img src="i/loader.gif" alt="" /></div>');
		jQuery('body').append(bg);
 		jQuery('body').append(cont);		
		jQuery('#lightbox-bg').animate({opacity: 0.6}, 500, function() {/*Animation complete*/ });
		jQuery('#lightbox-cont').animate({opacity: 1}, 500, function() {/*Animation complete*/ });		
		jQuery(window).resize(function() {
			hB = jQuery('body').height();
			wB = jQuery('body').width();	
			topB = jQuery("html").scrollTop();		
			lCont = (wB-wCont)/2;
			tCont = topB+50;
			jQuery('#lightbox-bg').css({ 'height' : hB+'px', 'width' : wB+'px' });
			jQuery('#lightbox-cont').css({ 'left' : lCont+'px', 'top' : tCont+'px' });
		});	
	},
	
	getResult : function(){	
		myParam = jQuery('#searchDove').serialize();
		myParam = myParam.replace('Nome%3F','');
		myParam = myParam.replace('Dove%3F','');
		var tipoList = '';
		firstParam = myParam.split('&tipo_')[0];			
		for(i=0; i<myParam.split('&').length; i++){			
			if(myParam.split('&')[i].indexOf('tipo_')!=-1){				
				locale = myParam.split('&')[i].split('tipo_')[1].split('=');					
				if(locale[1]=='true'){					
					tipoList += locale[0]+',';					
				}				
			}			
		}			
		param = tipoList.substring(0,tipoList.length-1);
		Toolbar.loader();
		jQuery.ajax({
			type: "GET",
			url: urlRicerca,
			data: firstParam+'&tipo='+param,
			dataType: "xml",
			success: Toolbar.parseXml
		});
	},
	
	parseXml : function(xml){
		
		if(jQuery(xml).find("items").length>0){				
			
			jQuery(xml).find("items").eachNew(function(i,j){		
				tot = jQuery(j).attr("totaleElementi");
				pagina = jQuery(j).attr("pagina");
				if(jQuery(j).attr("tipologia")==' '){
					tipologia='';
				}else{
					if(jQuery(j).attr("tipologia")){
						tipologia = jQuery(j).attr("tipologia");
					}else{
						tipologia = '';
					}
				}
				if(jQuery(j).attr("nome")==' '){
					nome='';
				}else{
					if(jQuery(j).attr("nome")){
						nome = jQuery(j).attr("nome");
					}else{
						nome = '';
					}
				}
			});
			
			myQuery = "&nome="+nome+"&tipologia="+tipologia;

			jQuery("#contResult").html("");

			jQuery("#contResult").html('<div class="result"></div>');		
			head = jQuery('<div class="head"></div>');
			upDown = jQuery('<div class="upNdown up"></div>');
			down = jQuery('<a title="down" href="javascript:;">&nbsp;</a>');
			up = jQuery('<a title="up" href="javascript:;">&nbsp;</a>');
			text = jQuery('<div class="text"></div>');
			visualizza = jQuery('<span class="title">VISUALIZZA PER:</span>');		
			nome = jQuery('<a href="javascript:;" id="btnNome" rel="'+nome+'">NOME</a>');
			sep = jQuery('<span>|</span>');
			tipo = jQuery('<a href="javascript:;" rel="'+tipologia+'">TIPOLOGIA</a>');
			clear = jQuery('<div class="cl"></div>');
			
			jQuery(nome).click(function(){			
				Toolbar.loader();			
				if(ordNome==''){
					var ordDest = 'asc';
					ordNome = 'asc';
					jQuery('.upNdown').attr("class","upNdown up");
				}else{
					if(ordNome=='desc'){
						var ordDest = 'asc';
						ordNome = 'asc';
						jQuery('.upNdown').attr("class","upNdown up");
					}else{
						var ordDest = 'desc';
						ordNome = 'desc';
						jQuery('.upNdown').attr("class","upNdown down");
					}
				}
				myParam = jQuery('#searchDove').serialize();
				myParam = myParam.replace('Nome%3F','');
				myParam = myParam.replace('Dove%3F','');
				
				var tipoList = '';
				firstParam = myParam.split('&tipo_')[0];			
				for(i=0; i<myParam.split('&').length; i++){			
					if(myParam.split('&')[i].indexOf('tipo_')!=-1){				
						locale = myParam.split('&')[i].split('tipo_')[1].split('=');					
						if(locale[1]=='true'){					
							tipoList += locale[0]+',';					
						}				
					}			
				}			
				param = tipoList.substring(0,tipoList.length-1);	
				jQuery.ajax({
					type: "GET",
					url: urlRicerca,
					data: firstParam+'&tipo='+param+'&nome='+ordDest,
					dataType: "xml",
					success: Toolbar.parseXml
				});
				ind = 0;			
			});
			
			jQuery(tipo).click(function(){
				Toolbar.loader();
				if(ordTipologia==''){
					var ordDestT = 'asc';
					ordTipologia = 'asc';
					jQuery('.upNdown').attr("class","upNdown up");
				}else{
					if(ordTipologia=='desc'){
						var ordDestT = 'asc';
						ordTipologia = 'asc';
						jQuery('.upNdown').attr("class","upNdown up");
					}else{
						var ordDestT = 'desc';
						ordTipologia = 'desc';
						jQuery('.upNdown').attr("class","upNdown down");
					}
				}
				myParam = jQuery('#searchDove').serialize();
				myParam = myParam.replace('Nome%3F','');
				myParam = myParam.replace('Dove%3F','');

				var tipoList = '';			
				firstParam = myParam.split('&tipo_')[0];			
				for(i=0; i<myParam.split('&').length; i++){			
					if(myParam.split('&')[i].indexOf('tipo_')!=-1){				
						locale = myParam.split('&')[i].split('tipo_')[1].split('=');					
						if(locale[1]=='true'){					
							tipoList += locale[0]+',';					
						}				
					}			
				}			
				param = tipoList.substring(0,tipoList.length-1);			
				jQuery.ajax({
					type: "GET",
					url: urlRicerca,
					data: firstParam+'&tipo='+param+'&tipologia='+ordDestT,
					dataType: "xml",
					success: Toolbar.parseXml
				});
				ind = 0;
			});
			
			jQuery(text).append(visualizza);
			jQuery(text).append(nome);
			jQuery(text).append(sep);
			jQuery(text).append(tipo);
			jQuery(head).append(upDown);
			jQuery(head).append(text);
			jQuery(head).append(clear);
			
			jQuery("#contResult > .result").append(head);
			
			pager = jQuery('<div class="pager"></div>');
			span = jQuery('<span>Search results : '+tot+'</span>');
			jQuery(pager).append(span);		
			pages = Math.ceil(tot/5);
			newInd = ind+5;
			newPrevInd = ind-+5;
			maxInd = pages-5;		
			maxind = Math.floor(pages/5);
			maxPageInd = maxind*5;		
			if(ind<maxPageInd){
				jQuery(pager).append("<a href=\"javascript:;\" onclick=\"Toolbar.gotoNextPage("+newInd+",'"+myQuery+"');\">&raquo;</a>");
			}
			for(i=5+ind; i>ind; i--){
				if(i<=pages){
					if(i==pagina){
						jQuery(pager).append("<a href=\"javascript:;\" onclick=\"Toolbar.gotoPageResult("+i+",'"+myQuery+"')\" class=\"on\">"+i+"</a>");
					}else{
						jQuery(pager).append("<a href=\"javascript:;\" onclick=\"Toolbar.gotoPageResult("+i+",'"+myQuery+"')\">"+i+"</a>");
					}
				}

			}
			if(ind>=5){
				jQuery(pager).append("<a href=\"javascript:;\" onclick=\"Toolbar.gotoPrevPage("+newPrevInd+",'"+myQuery+"');\">&laquo;</a>");
			}
			
			
			clear2 = jQuery('<div class="cl"></div>');		
			jQuery(pager).append(clear2);
			jQuery("#contResult > .result").append(pager);
			
			jQuery(xml).find("item").eachNew(function(i,j){
				tipo = jQuery(this).find("tipo").text();
				titolo = jQuery(this).find("titolo").text();
				srcImg = jQuery(this).find("img").text();
				desc = jQuery(this).find("desc").text();
				via = jQuery(this).find("via").text();
				cap = jQuery(this).find("cap").text()+'<br />';
				citta = jQuery(this).find("citta").text();
				prov = jQuery(this).find("prov").text();
				tel = '<br />Tel: '+jQuery(this).find("tel").text();
				fax = '<br />Fax: '+jQuery(this).find("fax").text();			
				sito = jQuery(this).find("sito").text();			
				mail = jQuery(this).find("mail").text();
				jQuery("#contResult > .result").append('<div class="element"><div class="l"><h4>' + tipo + '</h4><h3>' + titolo + '</h3><p>' + via + '' + cap + ' ' + citta + '' + tel + '' + fax + '</p></div><div class="r"><p><a href="' + sito + '">' + sito + '</a></p><p><a href="mailto:' + mail + '">' + mail + '</a></p></div><div class="cl"></div></div>');
			});
			
			pagerFoot = jQuery('<div class="pager"></div>');
			br = jQuery('<br />');
			jQuery(pagerFoot).append(br);
			
			if(ind<maxPageInd){
				jQuery(pagerFoot).append("<a href=\"javascript:;\" onclick=\"Toolbar.gotoNextPage("+newInd+",'"+myQuery+"');\">&raquo;</a>");
			}
			for(i=5+ind; i>ind; i--){
				if(i<=pages){
					if(i==pagina){
						jQuery(pagerFoot).append("<a href=\"javascript:;\" onclick=\"Toolbar.gotoPageResult("+i+",'"+myQuery+"')\" class=\"on\">"+i+"</a>");
					}else{
						jQuery(pagerFoot).append("<a href=\"javascript:;\" onclick=\"Toolbar.gotoPageResult("+i+",'"+myQuery+"')\">"+i+"</a>");
					}
				}
			}
			if(ind>=5){
				jQuery(pagerFoot).append("<a href=\"javascript:;\" onclick=\"Toolbar.gotoPrevPage("+newPrevInd+",'"+myQuery+"');\">&laquo;</a>");
			}
			
			
			clear2 = jQuery('<div class="cl"></div>');		
			jQuery(pagerFoot).append(clear2);		
			jQuery("#contResult > .result").append(pagerFoot);

			if (window.ActiveXObject){
				xmlString = xml.xml;
			}else{
				xmlString = (new XMLSerializer()).serializeToString(xml);
			}		
			
			if(jQuery('#emotional').css('display')=='none'){
				jQuery('.contImgHead').fadeOut(300, function() {
					jQuery('.contImgHead').hide();
					jQuery('#emotional').fadeIn(300,function(){					
						intervallo = setInterval("Toolbar.checkVar();",500);					
					});				
				});				
			}else{				
				intervallo = setInterval("Toolbar.checkVar();",500);
			}

			jQuery('#lightbox-bg').animate({opacity: 0}, 500, function() {jQuery('#lightbox-bg').remove();});
			jQuery('#lightbox-cont').animate({opacity: 0}, 500, function() {jQuery('#lightbox-cont').remove();});	
			
		}else{		
			
			jQuery("#contResult").html('<p class="notfound">'+notFound+'</p>');
			jQuery('#lightbox-bg').animate({opacity: 0}, 500, function() {jQuery('#lightbox-bg').remove();});
			jQuery('#lightbox-cont').animate({opacity: 0}, 500, function() {jQuery('#lightbox-cont').remove();});	

		}
		
	},
	
	checkVar : function(){

			if(mapReady == true){
				setMarkerIntoFlashMap(xmlString);
				clearInterval(intervallo);
			}

	},
	
	gotoNextPage : function(n,myQuery){
		ind = n;
		npage = ind+1;
		Toolbar.gotoPageResult(npage,"'"+myQuery+"'");		
	},
	
	gotoPrevPage : function(n,myQuery){
		ind = n;
		npage = ind+1;
		Toolbar.gotoPageResult(npage,"'"+myQuery+"'");		
	},

	gotoPageResult : function(n,myQuery){	
		Toolbar.loader();
		var pagePos = '&pag='+n;
		myParam = jQuery('#searchDove').serialize();
		myParam = myParam.replace('Nome%3F','');
		myParam = myParam.replace('Dove%3F','');
		
		var tipoList = '';			
		firstParam = myParam.split('&tipo_')[0];			
		for(i=0; i<myParam.split('&').length; i++){			
			if(myParam.split('&')[i].indexOf('tipo_')!=-1){				
				locale = myParam.split('&')[i].split('tipo_')[1].split('=');					
				if(locale[1]=='true'){					
					tipoList += locale[0]+',';					
				}				
			}			
		}			
		param = tipoList.substring(0,tipoList.length-1);			
		jQuery.ajax({
			type: "GET",
			url: urlRicerca,			
			data: firstParam+'&tipo='+param+myQuery+pagePos,
			dataType: "xml",
			success: Toolbar.parseXml
		});
	},
	
	mapIsReady :function(){	
		mapReady = true;	
	},
  
  showhideCheckbox : function(){
    jQuery('.search-where ul.l').eachNew(function(i,el){
      jQuery('li',el).eachNew(function(j,ts){if(j>4){jQuery(ts).addClass('sh hide');}});
      if (jQuery('.sh',el).length>0){
        jQuery(el).append('<li class="showhideCheckbox">show more</li>');
        jQuery('.showhideCheckbox',el).click(function(){
          if(jQuery(this).text()=='show more'){jQuery(this).text('show less');jQuery('li.sh',el).removeClass('hide');}
          else{jQuery(this).text('show more');jQuery('li.sh',el).addClass('hide');}
        })
      }
    });
  },
  
  initSlider : function(where){
    jQuery('.slider-bar',where).eachNew(function(t,el){
      var vls = {v1:0,v2:0,step:0}
      var ca = jQuery(el).prev('table').find('td');
      vls.step = ca.length-1;
      var test = 0;
      ca.eachNew(function(i){
        if (jQuery(ca[i]).hasClass('evid') && test==0){vls.v1=i;test=1;}
        else if (jQuery(ca[i]).hasClass('evid') && test==1){vls.v2=i;test=2;}
      });
      jQuery(el).slider({
        min       : 0,
        max       : vls.step,
        animate   : true,
        values    : [vls.v1,vls.v2],
        range     : true,
        change    : function(event,ui) {
          jQuery(this).prev('table').find('td').removeClass('evid evon');
          for(var i in ui.values)
            jQuery(this).prev('table').find('td').eq(ui.values[i]).addClass('evid');
          jQuery(this).prev('table').find('td').eachNew(function(m,el){
            if (m>ui.values[0]&&m<ui.values[1])jQuery(el).addClass('evon');
          });
          jQuery(this).next('h4').find('span:eq(0)').text(jQuery(this).prev('table').find('td.evid:eq(0)').text());
          jQuery(this).next('h4').find('span:eq(1)').text(jQuery(this).prev('table').find('td.evid:eq(1)').text());
          jQuery('#fromTo').attr('value',jQuery(this).prev('table').find('td.evid:eq(0)').text()+'|'+jQuery(this).prev('table').find('td.evid:eq(1)').text())
          //lancia funzione
        }
      });
    });
  },
  
  initThisSlider : function(id,cat){
    id='#'+id;
    var refClass = jQuery(id).find('.slider-values');
    var classes = jQuery(refClass)[0].className.toString().split(' ');
    jQuery(refClass)[0].className="";
    for(var i=0; i<classes.length; i++){
      if (classes[i].indexOf('light_')!=-1)
        classes[i]='light_'+cat.split('light_')[1]+' ';
      jQuery(refClass)[0].className+=classes[i]+' ';
    }
    if (jQuery(refClass)[0].className.indexOf('light_')!=-1)
      jQuery(refClass)[0].className+='light_'+cat.split('light_')[1];
    if(cat.split('light_')[1]=='spiga')
      jQuery(refClass).html('<tr><td class="evid">1</td><td class="evon">2</td><td class="evid">3</td></tr>');
    else
      jQuery(refClass).html('<tr><td class="evid">1</td><td class="evon">2</td><td class="evon">3</td><td class="evon">4</td><td class="evid">5</td></tr>');
    this.initSlider(jQuery(id));
  }
}


	
	function setMarkerIntoFlashMap(value) {
        Toolbar.thisMovie("Slideshow").setMarkerIntoFlashMap(value);
    }


	Toolbar.init();	
	/* OPEN/CLOSE MyToscanaBox */
	if(readCookie('open')=='true')
		Toolbar.showLayer('310','auto',userlogged,'usrToolBar');
        /* OPEN/CLOSE MyToscanaBox */	
});


var Collision = {
    /*
     * Test if obj is in the shape of target
     */
    test: function ( obj, target )
    {
        return (
            (
                ( jQuery (obj).offset().left > jQuery (target).offset().left &&    jQuery (obj).offset().left < jQuery (target).offset().left + jQuery (target).width()) ||
                ( jQuery (obj).offset().left < jQuery (target).offset().left && (jQuery (target).offset().left + jQuery (target).width()) > jQuery (target).offset().left )
            ) && (
                ( jQuery (obj).offset().top > jQuery (target).offset().top && jQuery (obj).offset().top < jQuery (target).offset().top + jQuery (target).height()) ||
                ( jQuery (obj).offset().top < jQuery (target).offset().top && (jQuery (obj).offset().top + jQuery (obj).height()) > jQuery (obj).offset().top)
        )) ? true : false
    },
    hideMatches: function ( elem, targets )
    {
        jQuery (targets).filter (":visible").eachNew( function() {
            if ( Collision.test (elem, jQuery (this)) )
                jQuery (this).attr ("collision_hided", "1").hide ();
        });
    },
    unloadHides: function ( selector )
    {
        jQuery ("[collision_hided=1]").show();
    }
}

