var last=-1,section=new Array(),link=new Array(),ntab=0, mDiv=null,lt,lg,ml=false,zlev;
var urlPopup='http://local.virgilio.it/html/common_local/popup_invia.html?linkdainviare=';
var urlLog='http://adimg.virgilio.it/tracks/bi/images/bi_clk.gif';
var codi=null, pl=null;
var context=null;
var srcurl=null;
var ie =(navigator.appName.indexOf("Microsoft") != -1);
var downloadingMapScript = false;
var downloadedMapScript = false;
var nTentativiShowmapRimanenti = 20;

function init(num, tab, map, lat, lng, zoom){
	ntab=num;
	if(ntab>0 && typeof(map)!='undefined' && document.getElementById(map)!=null){
		mDiv=map;lt=lat;lg=lng;zlev=zoom;
	}

	pl=thisMovie('comandi_video');
	ph = document.getElementById("photo");

	tt=0;phidx=-1;
	for(i=0;i<ntab;i++){
		section[i]=document.getElementById("sezione"+i);
		link[i]=document.getElementById("link"+i);
		if(tab != "" && link[i].innerHTML.toLowerCase().indexOf(tab.toLowerCase()) > -1)
			tt=i;
		if(link[i].innerHTML.toLowerCase().indexOf("foto") > -1)
			phidx=i;
	}
	if(ntab>1)
		getAjaxObj();
	goSection(tt);
}

function getAjaxObj() {
	aReq = null;
	if(window.XMLHttpRequest) {
		aReq = new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		try {
			aReq = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				aReq = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {aReq = null;}
		}
	}
}

function goSection(idx){
	try {
		if(ie && last>-1 && link[last].innerHTML.toLowerCase() == "video") {
			pl.doStop();
		}
	}catch(e){}

	posid=null;
	if(link[idx].innerHTML.toLowerCase() == "mappa" /*&& !ml && mDiv!=null*/) {
		posid="100";
		if (ph)
			ph.style.display='block';
	}
	else if(link[idx].innerHTML.toLowerCase() == "video") {
		posid="106";
		if (ph)
			ph.style.display='block';
	}
	else if(link[idx].innerHTML.toLowerCase() == "foto") {
		posid="104";
		ph.style.display='none';
	}
	else if(link[idx].innerHTML.toLowerCase() == "scheda") {
		posid="103";
		if (ph)
			ph.style.display='block';
	}
	else if(link[idx].innerHTML.toLowerCase() == "altre info") {
		posid="105";
		if (ph)
			ph.style.display='block';
	}

	if(ntab < 1 || idx < 0 || idx > ntab - 1 || last == idx)
		return;

	if(last>-1){
		section[last].style.display = "none";
		link[last].className = "tab";
		actionClick='';
		logClick("POSID="+posid+"&ACTION=NAV&CONTEXT="+context+"&ISTAT="+cistat+"&CODI="+codi+"&SRCURL="+srcurl);
	}
	section[idx].style.display = "inline";
	link[idx].className = "tabAttivo";

	try{
		if(link[idx].innerHTML.toLowerCase() == "mappa" && mDiv!=null) {
		//alert("si tratta della mappa");
			if (downloadedMapScript) {
			//alert("gli script sono stati scaricati");
				if (!ml) {
				//alert("la mappa non è stata caricata, quindi forzo il caricamento");
					initMap("force");
				}
			}
			else
			if ( typeof(mapScript) != "undefined" ) {
			//alert("gli script non sono stati scaricati e c'è definita la url degli script per scaricarli");
				if ( !downloadingMapScript ) {
				//alert("non sto scaricando gli script, quindi inizio a scaricarli");
					downloadingMapScript = true;
					$.getScript(
							mapScript,
							function(){
								//alert("scaricati gli script");
								downloadingMapScript = false;
								downloadedMapScript = true;
								initMap();
							}
					);
				}
			}
		}
		else if(ie && last>-1 && link[idx].innerHTML.toLowerCase() == "video")
			pl.doPlay();
	}catch(e){}

	last = idx;
}

function initMap(force) {
	if (typeof(force)!="undefined" || (link[last].innerHTML.toLowerCase() == "mappa" && mDiv!=null)) {
	//alert("inizializzo la mappa: si tratta della mappa");
		setTimeout("showMap()", 200);
		setTimeout("checkBird()", 400);
		setTimeout("actionsOnMapLoad()", 600);
	} else {
		//alert("inizializzo la mappa: NON si tratta della mappa... aspetto");
	}
}

function hClick(){}

function showMap(){
	//alert("show map!");
	try{
		latLong = new VELatLong(lt, lg);
		map = new VEMap(mDiv);
		preventPanAndZoom();
		map.AttachEvent('ontokenerror', hError);
		map.SetClientToken(document.mstoken);
		map.HideDashboard();
		if(map!=null && typeof(map)!='undefined'){
			map.LoadMap(latLong,zlev,undefined,undefined,undefined,false);		
			map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);

			marker = new VEShape(VEShapeType.Pushpin, latLong);
			if (typeof(titlePinPoint) != "undefined") {
				marker.SetTitle(titlePinPoint);
			}
			if (typeof(descPinPoint) != "undefined") {
				marker.SetDescription(descPinPoint);
			}
			map.AddShape(marker);



			if (context=="local") {
				marker.SetCustomIcon("/schede/virgilio/1_0/images/push_pin.gif");
			} else if (context=="rcs") {
				marker.SetCustomIcon("/schede/rcs/1_0/images/push_pin.gif");
			} else if (context=="repubblica") {
				marker.SetCustomIcon("/schede/repubblica/1_0/images/push_pin.gif");
			} else if (context=="gelocal") {
				marker.SetCustomIcon("/schede/gelocal/1_0/images/push_pin.gif");
			} else {
				marker.SetCustomIcon("/schede/virgilio/1_0/images/push_pin.gif");
			}
			//map.AddPushpin(new VEPushpin(1, map.GetCenter()));
			ml = true;
		}	
	} catch(e) {
		nTentativiShowmapRimanenti--;
		if ( nTentativiShowmapRimanenti > 0 ) {
			setTimeout("showMap()", 200);
		}
	}
}

function hError(){
}

function videoPlayerObj(mserver,dynpath){
	var swffile = '/schede/swf/comandi_video.swf';
	var videoxml = dynpath+"video.xml";
	document.write(
			'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="comandi_video" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="380" height="400" align="middle">\n'+
			'<param name="allowScriptAccess" value="always" />\n'+
			'<param name="allowFullScreen" value="true" />\n'+
			'<param name="movie" value="'+swffile+'" />\n'+
			'<param name="quality" value="high" />\n'+
			'<param name="bgcolor" value="#ffffff" />\n'+	
			'<param name="FlashVars" value="mediaServer='+mserver+'&xmlVideo='+videoxml+'&imgPath='+dynpath+'" />\n'+	
			'<embed src="'+swffile+'" quality="high" bgcolor="#ffffff" width="380" height="400" name="comandi_video" align="middle" allowScriptAccess="always" allowFullScreen="true" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" FlashVars="mediaServer='+mserver+'&xmlVideo='+videoxml+'&imgPath='+dynpath+'" />\n'+
			'</object>'
	);
}

function photoScroller( dynpath, w, h,notransp){
	var movie = '/schede/swf/gallery.swf';
	var transp = "transparent";
	var qs = 'pathXML='+dynpath+'photo.xml';
	if(typeof(notransp) != 'undefined'){
		transp = "opaque";
	}
	document.write(
			'<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"\n'+
			'  id="photoSelection"\n' +
			' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0"\n'+
			' WIDTH="' + w + '" HEIGHT="' + h + '">\n'+
			' <PARAM NAME=movie VALUE="' + movie + '">\n'+
			' <PARAM NAME=FlashVars VALUE="'+qs+'">\n'+
			' <PARAM NAME=quality VALUE=high>\n'+
			' <PARAM NAME=menu VALUE=false>\n'+
			' <PARAM name="wmode" VALUE="'+transp+'">\n'+
			' <EMBED src="' + movie +'"\n'+
			'  FlashVars="'+qs+'"\n'+
			'  name="photoSelection"\n' +
			'  wmode="'+transp+'" ' +
			'  quality=high menu="false" WIDTH="' + w + '" HEIGHT="' + h +
			'  TYPE="application/x-shockwave-flash"\n'+
			'  PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"></EMBED>\n'+
	'</OBJECT>');
}

function bookmarksite(title,url){
	actionClick = "";
	logClick("POSID=109&ACTION=NAV&CONTEXT="+context+"&ISTAT="+cistat+"&CODI="+codi+"&SRCURL="+srcurl);
	if (window.sidebar) // firefox
		window.sidebar.addPanel(title, url, "");
	else if(window.opera && window.print){ // opera
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',title);
		elem.setAttribute('rel','sidebar');
		elem.click();
	} 
	else if(document.all)// ie
		window.external.AddFavorite(url, title);
}

function goUrl(nurl){
	document.location.href = nurl;
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
	window.open(theURL,winName,features);
}

function mailPopup(tmp){
	actionClick = "";
	logClick("POSID=110&ACTION=NAV&CONTEXT="+context+"&ISTAT="+cistat+"&CODI="+codi+"&SRCURL="+srcurl);
	urlPopup+=escape(tmp);
	window.open(urlPopup,'mailpost','toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=300,height=350');
}

function linkFacebook(){
	actionClick = "";
	logClick("POSID=1502&ACTION=NAV&CONTEXT="+context+"&ISTAT="+cistat+"&CODI="+codi+"&SRCURL="+srcurl);
}

function linkMyspace(){
	actionClick = "";
	logClick("POSID=1503&ACTION=NAV&CONTEXT="+context+"&ISTAT="+cistat+"&CODI="+codi+"&SRCURL="+srcurl);
}

function viewPhoto(numPhoto) {
	if(last>-1){
		section[last].style.display = "none";
		link[last].className = "tab";
	}
	section[phidx].style.display = "inline";
	link[phidx].className = "tabAttivo";
	last = phidx;
	ph.style.display='none';

	setTimeout("thisMovie('photoSelection').eventoEsterno("+numPhoto+")", 200);

	actionClick = "";
	logClick("POSID=113&ACTION=NAV&CONTEXT="+context+"&ISTAT="+cistat+"&CODI="+codi+"&SRCURL="+srcurl);
}

function thisMovie(movieName) 
{
	if (ie) 
		return window[movieName];
	else 
		return document[movieName];
} 

function clickCat(destination) {
	urlDestination = destination;
	actionClick = "location.href = urlDestination";
	logClick("POSID=108&ACTION=NAV&CONTEXT="+context+"&ISTAT="+cistat+"&CODI="+codi+"&SRCURL="+srcurl+"&TRGURL="+escape(urlDestination));
}
function clickLogo(destination) {
	actionClick = "";
	logClick("POSID=112&ACTION=NAV&CONTEXT="+context+"&ISTAT="+cistat+"&CODI="+codi+"&SRCURL="+srcurl+"&GEENA="+coe+"&TRGURL="+escape(destination));
}
function clickVaiAlSito(destination) {
	actionClick = "";
	logClick("POSID=114&ACTION=NAV&CONTEXT="+context+"&ISTAT="+cistat+"&CODI="+codi+"&SRCURL="+srcurl+"&TRGURL="+escape(destination));
}
function clickVaiARecensione(destination) {
	actionClick = "";
	logClick("POSID=115&ACTION=NAV&CONTEXT="+context+"&ISTAT="+cistat+"&CODI="+codi+"&SRCURL="+srcurl+"&TRGURL="+escape(destination));
}

function gotoLink(link,target) {
	if (typeof(target)!="undefined" && target=="_blank") {
		window.open(link);
		return
	}
	location.href = link;
}

function openLinkInNewWin(link,winname,pars) {
	window.open(link,winname,pars);
}

function logClick(call) {
	eleImgBI = document.getElementById('imgBI');
	if ( typeof(eleImgBI) != "undefined" ) {
		var addedPars = '';
		if ( typeof(vlocal_searchid) != "undefined" && vlocal_searchid!="" ) {
			addedPars = addedPars + '&SEARCH_ID=' + vlocal_searchid;
		}
		if ( typeof(acr_sigla_p) != "undefined" && acr_sigla_p!="" ) {
			addedPars = addedPars + '&ACR_SIGLA_P=' + acr_sigla_p;
		}
		if ( typeof(fonte) != "undefined" && fonte!="" ) {
			addedPars = addedPars + '&FONTE=' + fonte;
		}
		call = urlLog + '?' + call + addedPars + '&RND='+Math.floor(Math.random()*1000000);
		eleImgBI.src = call;
	}
}

//comandi mappa

function changeMapStyle(style) {
	if (style == VEMapStyle.Road) {
		map.SetMapStyle(style);
		return true;
	}
	if (style == VEMapStyle.Aerial) {
		map.SetMapStyle(style);
		return true;
	}
	if (style == VEMapStyle.Hybrid) {
		map.SetMapStyle(style);
		return true;
	}
	if (style == VEMapStyle.Birdseye) {
		if (map.IsBirdseyeAvailable()) {
			map.SetMapStyle(style);
			return true;
		} else {
			return false;
		}
	}
	return false;
}

function zoomIn(zoomLevel)
{
	map.ZoomIn();
	checkBird();
}

function zoomOut(zoomLevel)
{
	map.ZoomOut();
	checkBird();
}



function activateTab(style) {
	id_last_active.className = '';
	if (style == VEMapStyle.Aerial) {
		id_last_active = id_aerial;
		label_last_active = label_aerial;
	}
	if (style == VEMapStyle.Birdseye) {
		id_last_active = id_birdseye2;
		label_last_active = label_birdseye2;
	}
	if (style == VEMapStyle.Hybrid) {
		id_last_active = id_hybrid;
		label_last_active = label_hybrid;
	}
	if (style == VEMapStyle.Road) {
		id_last_active = id_road;
		label_last_active = label_road;
	}
	id_last_active.className = nomeClasseAttiva;
}

//sincronizzazione visualizzazione mappa con dashboard

function activateAndChangeStyle(style) {
	if (style == VEMapStyle.Aerial) {
		if (changeMapStyle(VEMapStyle.Aerial)) {
			activateTab(style);
		} 
	}

	if (style == VEMapStyle.Birdseye) {
		if (changeMapStyle(VEMapStyle.Birdseye)) {
			activateTab(style);
		}
	}

	if (style == VEMapStyle.Hybrid) {
		if (changeMapStyle(VEMapStyle.Hybrid)) {
			activateTab(style);
		} 
	}

	if (style == VEMapStyle.Road) {
		if (changeMapStyle(VEMapStyle.Road)) {
			activateTab(style);
		} 
	}
}


//eventi mappa

function preventPanAndZoom(){
	map.AttachEvent("onmouseup", checkBird);
	map.AttachEvent("onmousewheel", checkBird);
	map.AttachEvent("onkeyup", checkBird);
}

function checkBird() {
}

function actionsOnMapLoad() {
}

function resizeFrame(f) {
	if (f!=null) {
		f.style.height = f.contentWindow.document.body.scrollHeight + "px";
	}
}


// voting

nTentativiOnPageLoadXrecs = 5;
toutPageLoadXrecs = 500;
global_url = "/recs/voti/";
timeout_saz_recs = 60000;
recsLabelDefault = new Array();
recsIstatCodes = new Array();

starDivNamePrefix = "idDivRecsAllAndOnlyStars";
labelDivNamePrefix = "idDivRecsLabelVoting";
coloraStellePrefix ="idDivRecsColoraStelle";


function sazEseguiVoto(tag_from,src,id,voto,nomeSezioneVoting) {
	_nomeSezioneVoting = nomeSezioneVoting;
	document.getElementById(starDivNamePrefix + nomeSezioneVoting).onmouseout=function(){};
	
	callVoting(
		{
			url: dominioRecs,
			id: id, 
			a_tag_istat: recsIstatCodes[_nomeSezioneVoting], // bi
			a_tag_from: tag_from, // bi
			src: src, // serve solo al reccomender e non viene girato a bi
			voto: voto,
			categoria: 'aziende/', 
			success: function() {
				document.getElementById(starDivNamePrefix + _nomeSezioneVoting).style.display='none';
				votoEseguito(_data, labelDivNamePrefix + _nomeSezioneVoting, 0);
				document.getElementById(labelDivNamePrefix + _nomeSezioneVoting).childNodes[0].style.padding='0';
			}, 
			error: function() {
				document.getElementById(starDivNamePrefix + _nomeSezioneVoting).style.display='none';
				defaultError(labelDivNamePrefix + _nomeSezioneVoting, 0);
				document.getElementById(labelDivNamePrefix + _nomeSezioneVoting).childNodes[0].style.padding='0';
			}
		}
	);

}

function writeToDiv(html,divName) {
	document.getElementById(divName).innerHTML = html;
}
function writeToLabelVotingSpan(txt,divName) {
	writeToDiv("<span>"+txt+"</span>",divName);
}

function showReccomendation(recRnk,recNVotes,nomeSezioneVoting) {
	starDivName = starDivNamePrefix + nomeSezioneVoting;
	labelDivName = labelDivNamePrefix + nomeSezioneVoting;
	coloraStelle = coloraStellePrefix + nomeSezioneVoting;
	if ( typeof(document.getElementById(starDivName))=="undefined" ) {
		nTentativiOnPageLoadXrecs = nTentativiOnPageLoadXrecs - 1;
		if ( nTentativiOnPageLoadXrecs>0 ) {
			setTimeout("showReccomendation(recRnk,recNVotes,'"+nomeSezioneVoting+"')",toutPageLoadXrecs);
		}
	} else {
		document.getElementById(coloraStelle).className = "rating_"+recRnk.replace("\.","-")+" current-rating";
		recsLabelDefault[nomeSezioneVoting] = "(<strong>"+recNVotes+"</strong> voti - voto medio <strong>"+recRnk+"</strong>)";
		writeToLabelVotingSpan(recsLabelDefault[nomeSezioneVoting],labelDivName);
	}
}
function show1stTimeReccomendation(nomeSezioneVoting) {
	starDivName = starDivNamePrefix + nomeSezioneVoting;
	labelDivName = labelDivNamePrefix + nomeSezioneVoting;
	if ( typeof(document.getElementById(starDivName))=="undefined" ) {
		nTentativiOnPageLoadXrecs = nTentativiOnPageLoadXrecs - 1;
		if ( nTentativiOnPageLoadXrecs>0 ) {
			setTimeout("show1stTimeReccomendation('"+nomeSezioneVoting+"')",toutPageLoadXrecs);
		}
	} else {
		recsLabelDefault[nomeSezioneVoting] = "(0 voti - Vota per primo)";
		writeToLabelVotingSpan(recsLabelDefault[nomeSezioneVoting],labelDivName);
	}
}

function getRecsInfo(idXvoting,nomeSezioneVoting) {
	getAZRankingN_Ratings(
			idXvoting,
			function(rnk,nVotes) {
				displayRnk = "";
				if ( typeof(rnk)!="undefined" && rnk>=0 ) {
					displayRnk = roundVoto(rnk) + "";
					showReccomendation(displayRnk,nVotes,nomeSezioneVoting);
				}
			},
			function(textStatus,statusCode) {
				errRes = textStatus+" "+statusCode;
				if ( errRes=="error 404" ) {
					show1stTimeReccomendation(nomeSezioneVoting);
				} else {
					document.getElementById(starDivNamePrefix+nomeSezioneVoting).style.display='none';
					writeToDivVotingSpan("OPS SIAMO OFFLINE! RIPROVA PI&Ugrave; TARDI.",labelDivNamePrefix+nomeSezioneVoting);
					document.getElementById(labelDivNamePrefix+nomeSezioneVoting).childNodes[0].style.padding='0';
				}
			}
		);
}
