var ge;
/**
 * function GoogleEarthPlugin()
 * 
 * @type constructor
 * @memberOf GoogleEarthPlugin
 */
function GoogleEarthPlugin() {
	this.prototype.constructor = GoogleEarthPlugin;
}

// COSTANTI PRIVATE
GoogleEarthPlugin._TARGET_ALTITUDE = 10; // distanza in km (alternativa a
// range)
GoogleEarthPlugin._TARGET_HEADING = 0; // rotazione orizzontale
GoogleEarthPlugin._TARGET_TILT = 60; // 60 // rotazione verticale
GoogleEarthPlugin._TARGET_RANGE = 500000; // 20000; // distanza dal punto
GoogleEarthPlugin._LAYER_NAME = "";

// COSTANTI PUBBLICHE
GoogleEarthPlugin.FOLDER_NONE = "none";
GoogleEarthPlugin.FOLDER_ALL = "tutte";
GoogleEarthPlugin.FOLDER_EXPLORATION = "exploration";
GoogleEarthPlugin.FOLDER_GAS = "gas";
GoogleEarthPlugin.FOLDER_REFINING = "refining";
GoogleEarthPlugin.FOLDER_PETROLCHIMICA = "petrolchimica";
GoogleEarthPlugin.FOLDER_INGEGNERIA = "ingegneria";

// EVENTI
/** @type String */
GoogleEarthPlugin.EVT_ON_LOAD = "EVT_ON_LOAD";
/** @type String */
GoogleEarthPlugin.EVT_ON_BALLOON_CLOSE = "EVT_ON_BALLOON_CLOSE";
GoogleEarthPlugin.EVT_ON_BALLOON = "EVT_ON_BALLOON";
GoogleEarthPlugin.EVT_ON_PLACEMARK_CLICK = "EVT_ON_PLACEMARK_CLICK";

// PUBLIC VARS
/** @type String */
GoogleEarthPlugin.locale = null;
/** @type String */
GoogleEarthPlugin.currentFolder = null;
/** @type String */
GoogleEarthPlugin.currentSezione = null;
/** @type DMLPlacemark */
GoogleEarthPlugin.currentPlacemark = null;
/** @type String */
GoogleEarthPlugin.last_idPaese = null;
/** @type String */
GoogleEarthPlugin.last_idSezione = null;
/** @type EventDispatcher */
GoogleEarthPlugin.eventDispatcher = null;

// PRIVATE VARS
GoogleEarthPlugin._shadow_risultati = null;
GoogleEarthPlugin._loading = null;
GoogleEarthPlugin._loolAt = null;
GoogleEarthPlugin._balloon = null;
GoogleEarthPlugin._queue_geolocation = [];
GoogleEarthPlugin._queue_placemarks = [];
GoogleEarthPlugin._arr_placemarks_vo;
/** @type PlacemarkFactory */
GoogleEarthPlugin._placemark_factory = null;

/**
 * function toggleShadowRisultati(show)
 * 
 * @memberOf GoogleEarthPlugin
 * @param {Boolean}
 *            show
 */
GoogleEarthPlugin.toggleShadowRisultati = function(show) {
	// TODO: togliere - 08/giu/2009 - fastweb
	if (!GoogleEarthPlugin._shadow_risultati) {
		GoogleEarthPlugin.loadShadowRisultati();
	} else {

	}
};

/**
 * function toggleShadowRisultati(show)
 * 
 * @memberOf GoogleEarthPlugin
 * @param {Boolean}
 *            show
 */
GoogleEarthPlugin.toggleLoading = function(show) {
	if (!GoogleEarthPlugin._loading) {
		GoogleEarthPlugin._loadLoading();
	} else {

	}
	GoogleEarthPlugin._loading.setVisibility(show);
};

/**
 * function moveShadowRisultati(show)
 * 
 * @memberOf GoogleEarthPlugin
 */
GoogleEarthPlugin.moveShadowRisultati = function(new_x) {
	var screenOverlay = GoogleEarthPlugin._shadow_risultati;
	if (screenOverlay)
		screenOverlay.getOverlayXY().setX(new_x - 1);
};

/**
 * function _loadShadowRisultati(show)
 * 
 * @memberOf GoogleEarthPlugin
 */
GoogleEarthPlugin.loadShadowRisultati = function() {

	GoogleEarthPlugin._shadow_risultati = ge.createScreenOverlay('');
	var screenOverlay = GoogleEarthPlugin._shadow_risultati;
	screenOverlay.setIcon(ge.createIcon(''));
	screenOverlay.getIcon().setHref(
			Configurazione.siteUrl + "contenuti/sezioni/shadow_ricerca.png");
	// screenOverlay.getIcon().setHref(Configurazione.siteUrl+'contenuti/flags/flag_yellow.png');

	// Set the point inside the overlay that is used as the positioning
	// anchor point.
	screenOverlay.getOverlayXY().setXUnits(ge.UNITS_PIXELS);
	screenOverlay.getOverlayXY().setYUnits(ge.UNITS_PIXELS);
	screenOverlay.getOverlayXY().setX(0);
	screenOverlay.getOverlayXY().setY(0);

	// Set screen position in fractions.
	// screenOverlay.getOverlayXY().setXUnits(ge.UNITS_FRACTION);
	// screenOverlay.getOverlayXY().setYUnits(ge.UNITS_FRACTION);
	// screenOverlay.getOverlayXY().setX(0); // Random x.
	// screenOverlay.getOverlayXY().setY(.5); // Random y.

	// Set screen position in fractions.
	screenOverlay.getScreenXY().setXUnits(ge.UNITS_PIXELS);
	screenOverlay.getScreenXY().setYUnits(ge.UNITS_PIXELS);
	screenOverlay.getScreenXY().setX(0); // Random x.
	screenOverlay.getScreenXY().setY(0); // Random y.

	// Rotate around object's center point.
	// screenOverlay.getRotationXY().setXUnits(ge.UNITS_FRACTION);
	// screenOverlay.getRotationXY().setYUnits(ge.UNITS_FRACTION);
	// // screenOverlay.getRotationXY().setX(0.5);
	// // screenOverlay.getRotationXY().setY(0.5);
	// screenOverlay.getRotationXY().setX(50);
	// screenOverlay.getRotationXY().setY(50);

	// Set object's size in pixels.
	// screenOverlay.getSize().setXUnits(ge.UNITS_PIXELS);
	// screenOverlay.getSize().setYUnits(ge.UNITS_PIXELS);
	// screenOverlay.getSize().setX(300);
	// screenOverlay.getSize().setY(90);

	// Rotate by a random number of degrees.
	// screenOverlay.setRotation(Math.random() * 360);

	ge.getFeatures().appendChild(screenOverlay);

	screenOverlay.getOverlayXY().setX(-100);
};

/**
 * function _loadLoading()
 * 
 * @memberOf GoogleEarthPlugin
 */
GoogleEarthPlugin._loadLoading = function() {

	GoogleEarthPlugin._loading = ge.createScreenOverlay('');
	var screenOverlay = GoogleEarthPlugin._loading;
	screenOverlay.setIcon(ge.createIcon(''));
	screenOverlay.getIcon().setHref(
			Configurazione.siteUrl + "contenuti/sezioni/loading.png");
	// screenOverlay.getIcon().setHref(Configurazione.siteUrl+'contenuti/flags/flag_yellow.png');

	// Set the point inside the overlay that is used as the positioning
	// anchor point.
	screenOverlay.getOverlayXY().setXUnits(ge.UNITS_FRACTION);
	screenOverlay.getOverlayXY().setYUnits(ge.UNITS_FRACTION);
	screenOverlay.getOverlayXY().setX(.5);
	screenOverlay.getOverlayXY().setY(.5);

	// Set screen position in fractions.
	// screenOverlay.getOverlayXY().setXUnits(ge.UNITS_FRACTION);
	// screenOverlay.getOverlayXY().setYUnits(ge.UNITS_FRACTION);
	// screenOverlay.getOverlayXY().setX(0); // Random x.
	// screenOverlay.getOverlayXY().setY(.5); // Random y.

	// Set screen position in fractions.
	screenOverlay.getScreenXY().setXUnits(ge.UNITS_FRACTION);
	screenOverlay.getScreenXY().setYUnits(ge.UNITS_FRACTION);
	screenOverlay.getScreenXY().setX(.5); // Random x.
	screenOverlay.getScreenXY().setY(.5); // Random y.

	// Rotate around object's center point.
	// screenOverlay.getRotationXY().setXUnits(ge.UNITS_FRACTION);
	// screenOverlay.getRotationXY().setYUnits(ge.UNITS_FRACTION);
	// // screenOverlay.getRotationXY().setX(0.5);
	// // screenOverlay.getRotationXY().setY(0.5);
	// screenOverlay.getRotationXY().setX(50);
	// screenOverlay.getRotationXY().setY(50);

	// Set object's size in pixels.
	// screenOverlay.getSize().setXUnits(ge.UNITS_PIXELS);
	// screenOverlay.getSize().setYUnits(ge.UNITS_PIXELS);
	// screenOverlay.getSize().setX(300);
	// screenOverlay.getSize().setY(90);

	// Rotate by a random number of degrees.
	// screenOverlay.setRotation(Math.random() * 360);

	ge.getFeatures().appendChild(screenOverlay);
};

// FUNCTIONS
/**
 * function createBalloon(placemark, idSezione)
 * 
 * @memberOf GoogleEarthPlugin
 * @type Object
 * @returns {Object} GEHtmlDivBalloon
 * @param {placemark}
 *            KmlPlacemark
 */
GoogleEarthPlugin.createBalloon = function(placemark, idSezione) {
	
	GoogleEarthPlugin._clearBalloonContents();

	var innerWidth = 627;
	var innerHeight = 321;

	var bgcolor = "#F8F7F5";

	var idPaese = "";

	GoogleEarthPlugin.closeBalloon();

	GoogleEarthPlugin._balloon = ge.createHtmlDivBalloon('');
	if (placemark) {
		// GoogleEarthPlugin._balloon.setFeature(placemark); // disabilitato per
		// permettere una maggiore larghezza del balloon
		idPaese = placemark.getId();
		
		
		/* PEZZA PER LINK HTML */
		var arr_placemarks_length = GoogleEarthPlugin._arr_placemarks_vo.length;
		for ( var int = 0; int < arr_placemarks_length; int++) {
			var temp_placemark = GoogleEarthPlugin._arr_placemarks_vo[int];
			if (temp_placemark.id==idPaese) {
				if (temp_placemark.htmlLink&&temp_placemark.htmlLink.length) {
					top.location.href = temp_placemark.htmlLink;
					//window.open(temp_placemark.htmlLink,'','toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes');
					return;
				}
			}
		}
	}
	/* FINE PEZZA PER LINK HTML */
	

	// create the <div>
	var div = document.createElement('DIV');
	div.innerHTML = '<div style="width: 10px; height: 10px;"></div>';
	GoogleEarthPlugin._balloon.setContentDiv(div);
	
	GoogleEarthPlugin.last_idPaese = idPaese;
	GoogleEarthPlugin.last_idSezione = idSezione;

	// GoogleEarthPlugin._balloon.setMaxWidth(17);
	// GoogleEarthPlugin._balloon.setMinWidth(17);
	// GoogleEarthPlugin._balloon.setMaxHeight(innerHeight+2);
	// GoogleEarthPlugin._balloon.setMinHeight(innerHeight+2);

	GoogleEarthPlugin._balloon.setBackgroundColor(bgcolor);
	GoogleEarthPlugin._balloon.setForegroundColor(bgcolor);

	GoogleEarthPlugin._balloon.setCloseButtonEnabled(false);

	var filePath = Configurazione.siteUrl + Configurazione.swfBalloon
			+ "?config_user=" + Configurazione.config_user + "&idStato="
			+ idPaese + "&idSezione=" + idSezione + "&locale="
			+ GoogleEarthPlugin.locale;
//	trace("filePath: " + filePath);

	ge.setBalloon(GoogleEarthPlugin._balloon);

	setTimeout('GoogleEarthPlugin._fillBalloon("' + bgcolor + '", '+ innerWidth + ', ' + innerHeight + ', "' + filePath + '")', 300);

	/*
	var ingressoBalloon = new Tween(new Object(), 'xyz', Tween.strongEaseOut, 10, 607, 1);
	var doit = 0;
	ingressoBalloon.onMotionChanged = function(event) {
		var perc = Math.round(event.target._pos);
		doit++;
		if (doit > 30) {
			var div = document.createElement('DIV');
			div.innerHTML = '<div style="width:' + (perc) + 'px; height: 301px; overflow: hidden"></div>';
			GoogleEarthPlugin._balloon.setContentDiv(div);
			doit = 0;
		}
	}
	ingressoBalloon.onMotionFinished = function(event) {
		setTimeout('GoogleEarthPlugin._fillBalloon("' + bgcolor + '", '+ innerWidth + ', ' + innerHeight + ', "' + filePath + '")', 300);
	};
	ingressoBalloon.start();
	*/

}

/**
 * function _fillBalloon()
 * 
 * @memberOf GoogleEarthPlugin
 */
GoogleEarthPlugin._fillBalloon = function(bgcolor, innerWidth, innerHeight,
		filePath) {
	var flashvars = {
		config_user : Configurazione.config_user
	};
	var params = {};
	params.menu = "false";
	params.bgcolor = bgcolor;
	params.allowScriptAccess = "true";
	var attributes = {};
	attributes.id = "balloonSWF";
	attributes.name = "balloonSWF";
	var div_balloon = document.createElement('DIV');
	// div_balloon.innerHTML = '<div id="balloonContainer"
	// style="background-color: '+bgcolor+'px; overflow:hidden; width:
	// '+(innerWidth)+'px; height: '+innerHeight+'px"><div
	// id="balloonDiv"></div></div>';
	div_balloon.innerHTML = '<div id="balloonContainer" style="background-color: #bgcolor; overflow:hidden; width: 607px; height: 301px"><div id="balloonDiv"></div></div>';
	GoogleEarthPlugin._balloon.setContentDiv(div_balloon);

	setTimeout('GoogleEarthPlugin._swfBalloon("' + bgcolor + '", ' + innerWidth
			+ ', ' + innerHeight + ', "' + filePath + '")', 100);
//	trace("filePath: " + filePath);

	// swfobject.embedSWF(filePath, "balloonDiv", innerWidth, innerHeight,
	// "9.0.124", "expressInstall.swf", flashvars, params, attributes);

	// GoogleEarthPlugin.eventDispatcher.broadcastMessage(GoogleEarthPlugin.EVT_ON_BALLOON,
	// {type: GoogleEarthPlugin.EVT_ON_BALLOON});
};

/**
 * function _swfBalloon()
 * 
 * @memberOf GoogleEarthPlugin
 */
GoogleEarthPlugin._swfBalloon = function(bgcolor, innerWidth, innerHeight,
		filePath) {
	var flashvars = {
		config_user : Configurazione.config_user
	};
	var params = {};
	params.menu = "false";
	params.bgcolor = bgcolor;
	params.allowScriptAccess = "true";
	var attributes = {};
	attributes.id = "balloonSWF";
	attributes.name = "balloonSWF";
	swfobject.embedSWF(filePath, "balloonDiv", innerWidth, innerHeight,
			"9.0.124", "expressInstall.swf", flashvars, params, attributes);

	GoogleEarthPlugin.eventDispatcher.broadcastMessage(
			GoogleEarthPlugin.EVT_ON_BALLOON, {
				type : GoogleEarthPlugin.EVT_ON_BALLOON
			});
};

/**
 * function reopenLastBalloon()
 * 
 * @memberOf GoogleEarthPlugin
 */
GoogleEarthPlugin.reopenLastBalloon = function() {
	GoogleEarthPlugin.selectPlacemark(GoogleEarthPlugin.last_idPaese,
			GoogleEarthPlugin.last_idSezione);
};

/**
 * function reopenLastBalloon()
 * 
 * @memberOf GoogleEarthPlugin
 */
GoogleEarthPlugin.balloon_onSezione = function(idSezione_new) {
	GoogleEarthPlugin.last_idSezione = idSezione_new;
};

/**
 * function closeBalloon(placemark)
 * 
 * @memberOf GoogleEarthPlugin
 */
GoogleEarthPlugin.closeBalloon = function() {
	GoogleEarthPlugin._clearBalloonContents();
	if (GoogleEarthPlugin._balloon) {
		ge.setBalloon(null);
	}
	//
	delete GoogleEarthPlugin._balloon;
};

/**
 * function _clearBalloonContents()
 * 
 * @memberOf GoogleEarthPlugin
 */
GoogleEarthPlugin._clearBalloonContents = function() {
	try {
		$("balloonContainer").style.width = "0px";
		$("balloonContainer").style.height = "0px";
		$("balloonContainer").innerHTML = "";
	} catch (e) {
	}
};

/**
 * function initPlugin()
 * 
 * @memberOf GoogleEarthPlugin
 */
GoogleEarthPlugin._initPlugin = function() {
	google.earth.createInstance(GoogleEarthPlugin._LAYER_NAME,
			GoogleEarthPlugin._initCB, GoogleEarthPlugin._failureCB);
};

/**
 * function initCB()
 * 
 * @memberOf GoogleEarthPlugin
 */
GoogleEarthPlugin._initCB = function(instance) {

	ge = instance;
	ge.getWindow().setVisibility(true);

	// add a navigation control
	ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);

	// add some layers
	ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true);
	ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, false);
	
	// show world mini map
//	ge.getOptions().setOverviewMapVisibility(true);

	// create PlacemarkFactory instance
	GoogleEarthPlugin._placemark_factory = new PlacemarkFactory(ge);

	// GoogleEarthPlugin.eventDispatcher.broadcastMessage(GoogleEarthPlugin.EVE,
	// {target:this,type:SearchBar.EVT_ON_RESET});
	GoogleEarthPlugin.eventDispatcher.broadcastMessage(
			GoogleEarthPlugin.EVT_ON_LOAD, {
				type : GoogleEarthPlugin.EVT_ON_LOAD
			});

	google.earth.addEventListener(ge, "balloonclose",
			GoogleEarthPlugin._onBalloonClose);

};

/**
 * function _onBalloonClose()
 * 
 * @memberOf GoogleEarthPlugin
 */
GoogleEarthPlugin._onBalloonClose = function() {
	GoogleEarthPlugin._clearBalloonContents();
	GoogleEarthPlugin.eventDispatcher.broadcastMessage(
			GoogleEarthPlugin.EVT_ON_BALLOON_CLOSE, {
				type : GoogleEarthPlugin.EVT_ON_BALLOON_CLOSE
			});
};

/**
 * function _failureCB()
 * 
 * @memberOf GoogleEarthPlugin
 * @returns {String} data
 */
GoogleEarthPlugin.getBrowserData = function() {
	return ge.getPluginVersion().toString() + "<br>" + navigator.userAgent;
};

/**
 * function balloon_onLoad()
 * 
 * @memberOf GoogleEarthPlugin
 */
GoogleEarthPlugin.balloon_onLoad = function() {
//	trace("balloon_onLoad: ");
};

/**
 * function _failureCB()
 * 
 * @memberOf GoogleEarthPlugin
 */
GoogleEarthPlugin._failureCB = function(err) {
	trace("_failureCB:error instantiating google earth plugin" + err);
};

/**
 * function hideTestFolder()
 * 
 * @memberOf GoogleEarthPlugin
 */
GoogleEarthPlugin.hideTestFolder = function() {
	// GoogleEarthPlugin._test_folder.setOpen(false);
	GoogleEarthPlugin.getFolder("test").setVisibility(false);
};

/**
 * function showTestFolder()
 * 
 * @memberOf GoogleEarthPlugin
 */
GoogleEarthPlugin.showTestFolder = function() {
	// GoogleEarthPlugin._test_folder.setOpen(false);
	GoogleEarthPlugin.getFolder("test").setVisibility(true);
};

/**
 * function hideTestFolder()
 * 
 * @memberOf GoogleEarthPlugin
 */
GoogleEarthPlugin.switchFolder = function(folderName) {
//	trace("GoogleEarthPlugin.switchFolder:"+folderName);
	//
	var folderExists = GoogleEarthPlugin
			.folderExists(GoogleEarthPlugin.currentFolder);
	if (folderExists) {
		GoogleEarthPlugin.getFolder(GoogleEarthPlugin.currentFolder)
				.setVisibility(false);
	}
	//
	GoogleEarthPlugin.currentFolder = folderName;
	if (GoogleEarthPlugin.getFolder(folderName))
		GoogleEarthPlugin.getFolder(folderName).setVisibility(true);
};

/**
 * function selectPlacemark(idPaese, idSezione);
 * 
 * @memberOf GoogleEarthPlugin
 */
GoogleEarthPlugin.selectPlacemark = function(idPaese, idSezione) {
	var folder = GoogleEarthPlugin.getFolder(GoogleEarthPlugin.currentFolder);
	var arr_placemarks = folder.getFeatures().getFirstChild().getFeatures()
			.getChildNodes();
	var arr_placemarks_length = arr_placemarks.getLength();
	for ( var int = 0; int < arr_placemarks_length; int++) {
		var temp_placemark = arr_placemarks.item(int);
		var id = temp_placemark.getId();
		if (id == idPaese) {
			GoogleEarthPlugin.closeBalloon();
			GoogleEarthPlugin.currentPlacemark = temp_placemark;
			GoogleEarthPlugin.currentSezione = idSezione;
			GoogleEarthPlugin.goToPlacemark(GoogleEarthPlugin.currentPlacemark);
			google.earth.addEventListener(ge.getView(), "viewchangeend",
					GoogleEarthPlugin._onViewChangeEnd);
			break;
		}
	}
};

/**
 * function getCoords()
 * 
 * @memberOf GoogleEarthPlugin
 * @type Object
 * @returns {Object} point
 */
GoogleEarthPlugin.getCoords = function() {

	var point = ge.createPoint('');
	var la = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
	var lat = la.getLatitude();
	var lng = la.getLongitude();
	point.setLatitude(lat);
	point.setLongitude(lng);
	return point;

};

/**
 * function createPlacemark(lat, lng, folder, placemark_id)
 * 
 * @memberOf GoogleEarthPlugin
 * @type Object
 * @returns {Object} placemark
 * @param {Number}
 *            lat
 * @param {Number}
 *            lng
 * @param {String}
 *            folder
 * @param {String}
 *            placemark_id
 */
GoogleEarthPlugin.createPlacemark = function(lat, lng, folder, placemark_id, hasVideo, hasGallery) {

	return GoogleEarthPlugin._placemark_factory.createPlacemark(lat, lng,
			folder, placemark_id, hasVideo, hasGallery);

};

/**
 * function createPlacemarks(arr_placemarks)
 * 
 * @memberOf GoogleEarthPlugin
 * @type Object
 * @param {Array}
 *            arr_placemarks
 */
GoogleEarthPlugin.createPlacemarks = function(arr_placemarks) {
	
	if (!GoogleEarthPlugin._arr_placemarks_vo) GoogleEarthPlugin._arr_placemarks_vo = arr_placemarks;
	
	GoogleEarthPlugin.toggleLoading(true);

	GoogleEarthPlugin.switchFolder(GoogleEarthPlugin.FOLDER_NONE);

	GoogleEarthPlugin._queue_placemarks = [];
	GoogleEarthPlugin._queue_geolocation = [];

	for ( var i = 0; i < arr_placemarks.length; i++) {
		var placemark_vo = arr_placemarks[i];
		if (placemark_vo.point.x != null) {
			GoogleEarthPlugin._queue_placemarks.push(placemark_vo);
		} else {
			GoogleEarthPlugin._queue_geolocation.push(placemark_vo);
		}
	}
	GoogleEarthPlugin._startPlacemarksQueue();

};

/**
 * function getFolder(folderName)
 * 
 * @memberOf GoogleEarthPlugin
 * @type KMLFolder
 * @param {String}
 *            folderName
 * @return {KMLFolder} folder
 */
GoogleEarthPlugin.getFolder = function(folderName) {

	return GoogleEarthPlugin._placemark_factory.getFolder(folderName);

};

/**
 * function folderExists(folderName)
 * 
 * @memberOf GoogleEarthPlugin
 * @type Boolean
 * @param {String}
 *            folderName
 * @return {Boolean} folder
 */
GoogleEarthPlugin.folderExists = function(folderName) {

	return GoogleEarthPlugin._placemark_factory.folderExists(folderName);

};

/**
 * function _startPlacemarksQueue()
 * 
 * @memberOf GoogleEarthPlugin
 */
GoogleEarthPlugin._startPlacemarksQueue = function() {
	/** @type PlacemarkVO */
	var placemark_vo;

	if (GoogleEarthPlugin._queue_geolocation.length) {
		var geocoder = new google.maps.ClientGeocoder();
		placemark_vo = GoogleEarthPlugin._queue_geolocation[0];
		var geocodeLocation = placemark_vo.destination;
		geocoder.getLatLng(geocodeLocation,
				GoogleEarthPlugin._addPlacemarkToQueue);
	} else {
		GoogleEarthPlugin._showLoadedPlacemarks();
	}

};

/**
 * function _showLoadedPlacemarks()
 * 
 * @memberOf GoogleEarthPlugin
 */
GoogleEarthPlugin._showLoadedPlacemarks = function() {
	GoogleEarthPlugin.toggleLoading(false);
	/** @type PlacemarkVO */
	var placemark_vo = GoogleEarthPlugin._queue_placemarks[0];
	if (!placemark_vo)
		return;
	//
	var arr_placemarks = GoogleEarthPlugin._placemark_factory
			.createPlacemarks(GoogleEarthPlugin._queue_placemarks);
	var arr_placemarks_length = arr_placemarks.getLength();

	for ( var int = 0; int < arr_placemarks_length; int++) {
		var temp_placemark = arr_placemarks.item(int);
		google.earth.addEventListener(temp_placemark, "click",
				GoogleEarthPlugin.placemark_onClick);
	}
	//
	GoogleEarthPlugin._queue_geolocation = [];
	GoogleEarthPlugin._queue_placemarks = [];
	//
	GoogleEarthPlugin.switchFolder(placemark_vo.folder);
};

/**
 * function placemark_onClick()
 * 
 * @memberOf GoogleEarthPlugin
 */
GoogleEarthPlugin.placemark_onClick = function(evt) {
	GoogleEarthPlugin.currentPlacemark = evt.getTarget();
	var id = GoogleEarthPlugin.currentPlacemark.getId();
	GoogleEarthPlugin.currentSezione = "default";
	//
	GoogleEarthPlugin.goToPlacemark(GoogleEarthPlugin.currentPlacemark);
	google.earth.addEventListener(ge.getView(), "viewchangeend",
			GoogleEarthPlugin._onViewChangeEnd);
	// GoogleEarthPlugin.createBalloon(placemark);
	GoogleEarthPlugin.eventDispatcher.broadcastMessage(
			GoogleEarthPlugin.EVT_ON_PLACEMARK_CLICK, {
				type : GoogleEarthPlugin.EVT_ON_PLACEMARK_CLICK
			});
};

/**
 * function _addPlacemarkToQueue(point)
 * 
 * @memberOf GoogleEarthPlugin
 * @param {}
 *            placemark
 */
GoogleEarthPlugin._addPlacemarkToQueue = function(point) {

	/** @type PlacemarkVO */
	var placemark_vo = GoogleEarthPlugin._queue_geolocation.shift();
	if (point) {
	} else {
		return;
	}
	if (!placemark_vo)
		return;
	placemark_vo.point = point;
	GoogleEarthPlugin._queue_placemarks.push(placemark_vo);
	//
	// GoogleEarthPlugin._startPlacemarksQueue();
	// IMPOSTO UN TIMEOUT PER EVITARE L'ERRORE 620 DI GOOGLE, POSSIBILE CON LE
	// CHIAMATE IN LOOP
	setTimeout("GoogleEarthPlugin._startPlacemarksQueue()", 150);
};

/**
 * function goToPlacemark(placemark)
 * 
 * @memberOf GoogleEarthPlugin
 * @param {}
 *            placemark
 */
GoogleEarthPlugin.goToPlacemark = function(placemark) {

	var lat = placemark.getGeometry().getLatitude();
	var lng = placemark.getGeometry().getLongitude();

	var point = {};
	point.y = lat;
	point.x = lng;

	GoogleEarthPlugin._goToPoint(point);

};

/**
 * function goToPlace(destination)
 * 
 * @memberOf GoogleEarthPlugin
 * @param {String}
 *            destination
 */
GoogleEarthPlugin.goToPlace = function(destination) {
	var geocodeLocation = destination;
	var geocoder = new google.maps.ClientGeocoder();

	geocoder.getLatLng(geocodeLocation, GoogleEarthPlugin._goToPoint);
};

/**
 * function goToPoint(point)
 * 
 * @memberOf GoogleEarthPlugin
 * @type Object
 * @returns {}
 * @param {point}
 *            object {x:x, y:y}
 * @param {Number}
 *            tilt
 * @param {Number}
 *            range
 */
GoogleEarthPlugin.goToPoint = function(point) {
	if (point) {
		if (!GoogleEarthPlugin._lookAt)
			GoogleEarthPlugin._lookAt = ge.createLookAt('');
		GoogleEarthPlugin._lookAt
				.set(point.y, point.x, GoogleEarthPlugin._TARGET_ALTITUDE,
						ge.ALTITUDE_RELATIVE_TO_GROUND,
						GoogleEarthPlugin._TARGET_HEADING,
						GoogleEarthPlugin._TARGET_TILT,
						GoogleEarthPlugin._TARGET_RANGE);
		ge.getView().setAbstractView(GoogleEarthPlugin._lookAt);
	}
};

/**
 * function zoomOut()
 * 
 * @memberOf GoogleEarthPlugin
 * @type Object
 * @returns {}
 */
GoogleEarthPlugin.zoomOut = function() {
	var camera = ge.getView().copyAsLookAt(ge.ALTITUDE_ABSOLUTE);
	var lat = camera.getLatitude();
	var lng = camera.getLongitude();

	if (!GoogleEarthPlugin._lookAt)
		GoogleEarthPlugin._lookAt = ge.createLookAt('');
	GoogleEarthPlugin._lookAt.set(lat, lng, 1, ge.ALTITUDE_RELATIVE_TO_GROUND,
			0, 0, 80 * 100000);
	ge.getView().setAbstractView(GoogleEarthPlugin._lookAt);
};

/**
 * function _goToPoint(point, tilt, range)
 * 
 * @memberOf GoogleEarthPlugin
 * @type Object
 * @returns {}
 * @param {point}
 *            object {x:x, y:y}
 * @param {Number}
 *            tilt
 * @param {Number}
 *            range
 */
GoogleEarthPlugin._goToPoint = function(point, tilt, range) {
	if (point) {
		if (!GoogleEarthPlugin._lookAt)
			GoogleEarthPlugin._lookAt = ge.createLookAt('');
		GoogleEarthPlugin._lookAt.set(point.y, point.x,
				GoogleEarthPlugin._TARGET_ALTITUDE,
				ge.ALTITUDE_RELATIVE_TO_GROUND,
				GoogleEarthPlugin._TARGET_HEADING, tilt
						|| GoogleEarthPlugin._TARGET_TILT, range
						|| GoogleEarthPlugin._TARGET_RANGE);
		ge.getView().setAbstractView(GoogleEarthPlugin._lookAt);
	}
};

/**
 * function _onViewChangeEnd()
 * 
 * @memberOf GoogleEarthPlugin
 */
GoogleEarthPlugin._onViewChangeEnd = function(event) {

	google.earth.removeEventListener(ge.getView(), "viewchangeend",
			GoogleEarthPlugin._onViewChangeEnd);

	if (GoogleEarthPlugin.currentSezione)
		setTimeout("GoogleEarthPlugin._delayedBalloon()", 150);

};

/**
 * function _delayedBalloon()
 * 
 * @memberOf GoogleEarthPlugin
 */
GoogleEarthPlugin._delayedBalloon = function(event) {

	GoogleEarthPlugin.createBalloon(GoogleEarthPlugin.currentPlacemark,
			GoogleEarthPlugin.currentSezione);

};

/**
 * function init()
 * 
 * @memberOf GoogleEarthPlugin
 */
GoogleEarthPlugin.init = function(layerName) {

	this.eventDispatcher = new EventDispatcher();

	GoogleEarthPlugin._LAYER_NAME = layerName;

	google.load("earth", "1");
	google.load("maps", "2");
	google.load("swfobject", "2.1");

	google.setOnLoadCallback(GoogleEarthPlugin._initPlugin);

};

//
/**
 * function PlacemarkVO()
 * 
 * @type constructor
 * @memberOf PlacemarkVO
 */
function PlacemarkVO() {
}
PlacemarkVO.prototype.constructor = PlacemarkVO;
PlacemarkVO.prototype.destination = '';
PlacemarkVO.prototype.point = {};
PlacemarkVO.prototype.folder = "";
PlacemarkVO.prototype.id = "";
PlacemarkVO.prototype.hasVideo = false;
PlacemarkVO.prototype.hasGallery = false

/**
 * function PlacemarkFactory(ge_instance)
 * 
 * @type constructor
 * @param {GEPlugin}
 *            ge_instance
 * @memberOf Object
 */
function PlacemarkFactory(ge_instance) {
	this.prototype = {};
	this.ge = ge_instance;
}
PlacemarkFactory.prototype.constructor = PlacemarkFactory;
//
PlacemarkFactory.folders = {};
PlacemarkFactory.stylemaps = {};
/**
 * property ge
 * 
 * @type {GEPlugin}
 * @memberOf PlacemarkFactory
 */
PlacemarkFactory.prototype.ge = {};

/**
 * function createPlacemark(lat, lng, folderName, placemark_id)
 * 
 * @memberOf PlacemarkFactory
 * @param {Number}
 *            lat
 * @param {Number}
 *            lng
 * @param {String}
 *            folderName
 * @param {String}
 *            placemark_id
 * @param {Boolean}
 *            hasVideo
 * @param {Boolean}
 *            hasGallery
 * @type KmlPlacemark
 * @returns {KmlPlacemark} placemark
 */
PlacemarkFactory.prototype.createPlacemark = function(lat, lng, folderName,
		placemark_id, hasVideo, hasGallery) {
//	trace("createPlacemark: "+createPlacemark);
//	trace("	folderName: "+folderName);

	// placemark_id = (placemark_id) ? (placemark_id+"_"+folderName) : "";
	placemark_id = (placemark_id) ? (placemark_id) : "";

	var folder;
	if (PlacemarkFactory.folders[folderName]) {
		folder = PlacemarkFactory.folders[folderName];
	} else {
		folder = this._createFolder(folderName);
//		this._createStyleMap(folderName);
	}

	if ((!lat) || (!lng)) {
		var camera = this.ge.getView().copyAsLookAt(this.ge.ALTITUDE_ABSOLUTE);
		lat = camera.getLatitude();
		lng = camera.getLongitude();
	}

	var kmlString = '';
	kmlString += '<Placemark id="' + placemark_id + '">';
	// kmlString+=' <!-- inherited from Feature element -->';
	// kmlString+=' <name>...<\/name> <!-- string -->';
	// kmlString+=' <visibility>1<\/visibility> <!-- boolean -->';
	// kmlString+=' <open>0<\/open> <!-- boolean -->';
	// kmlString+=' <atom:author>...<atom:author> <!-- xmlns:atom -->';
	// kmlString+=' <atom:link>...<\/atom:link> kmlString <!-- xmlns:atom -->';
	// kmlString+=' <address>...<\/address> <!-- string -->';
	// kmlString+=' <xal:AddressDetails>...<\/xal:AddressDetails> <!-- xmlns:xal
	// -->';
	// kmlString+=' <phoneNumber>...<\/phoneNumber> <!-- kmlString+ing -->';
	// kmlString+=' <Snippet maxLines="2">...<\/Snippet> <!-- string -->';
	// kmlString+=' <description>...<\/description> <!-- string -->';
	// kmlString+=' <AbstractView>...<\/AbstractView> <!-- Camera or LookAt
	// -->';
	// kmlString+=' <TimePrimitive>...<\/TimePrimitive>';
	kmlString += '  <Point>';
	kmlString += '  		<coordinates>';
	kmlString += '  			' + lng + ',' + lat;
	kmlString += '  		</coordinates>';
	kmlString += '  </Point>';
	kmlString += '  <styleUrl>#styleMap_' + folderName + '<\/styleUrl>';
	// kmlString+=' <StyleSelector>...<\/StyleSelector>';
	// kmlString+=' <Region>...<\/Region>';
	// kmlString+=' <Metadata>...<\/Metadata> <!-- deprecated in KML 2.2 -->';
	// kmlString+=' <ExtendedData>...<\/ExtendedData> <!-- new in KML 2.2 -->';
	// kmlString+=' <!-- specific to Placemark element -->';
	// kmlString+=' <Geometry>...<\/Geometry>';
	kmlString += '<\/Placemark>';

	var placemark = ge.parseKml(kmlString);
	folder.getFeatures().appendChild(placemark);

	return placemark;

};

/**
 * function createPlacemarks(placemarks)
 * 
 * @memberOf PlacemarkFactory
 * @param {Array}
 *            placemarks
 */
PlacemarkFactory.prototype.createPlacemarks = function(placemarks) {
	
//	trace("PlacemarkFactory.createPlacemarks");
	
	/** @type PlacemarkVO */
	var placemark_vo;

	var folder;
	var folderName;
	var styleMapName;
	
	
	var kmlString = '';

	kmlString += '<?xml version="1.0" encoding="UTF-8"?>';
	kmlString += '<kml xmlns="http:\/\/www.opengis.net\/kml\/2.2">';
	kmlString += '  <Document>';

	for ( var i = 0; i < placemarks.length; i++) {
		placemark_vo = placemarks[i];
		// if (placemark_vo.point)
		// GoogleEarthPlugin.createPlacemark(placemark_vo.point.y,
		// placemark_vo.point.x, placemark_vo.folder, placemark_vo.id);
		
		if (placemark_vo.point) {

			folderName = placemark_vo.folder;
			// var placemark_id = placemark_vo.id+"_"+folderName;
			var placemark_id = placemark_vo.id;
			var lng = placemark_vo.point.x;
			var lat = placemark_vo.point.y;
			
			var attivita = folderName.split("_")[0];
			styleMapName = attivita;
			
			if (placemark_vo.hasGallery==true) styleMapName += "_g"; 
			if (placemark_vo.hasVideo==true) styleMapName += "_v"; 
			
			this.getStyleMap(styleMapName);

			kmlString += '<Placemark id="' + placemark_id + '">';
			// kmlString+=' <!-- inherited from Feature element -->';
			// kmlString+=' <name>...<\/name> <!-- string -->';
			// kmlString+=' <visibility>1<\/visibility> <!-- boolean -->';
			// kmlString+=' <open>0<\/open> <!-- boolean -->';
			// kmlString+=' <atom:author>...<atom:author> <!-- xmlns:atom -->';
			// kmlString+=' <atom:link>...<\/atom:link> kmlString <!--
			// xmlns:atom -->';
			// kmlString+=' <address>...<\/address> <!-- string -->';
			// kmlString+=' <xal:AddressDetails>...<\/xal:AddressDetails> <!--
			// xmlns:xal -->';
			// kmlString+=' <phoneNumber>...<\/phoneNumber> <!-- kmlString+ing
			// -->';
			// kmlString+=' <Snippet maxLines="2">...<\/Snippet> <!-- string
			// -->';
			// kmlString+=' <description>...<\/description> <!-- string -->';
			// kmlString+=' <AbstractView>...<\/AbstractView> <!-- Camera or
			// LookAt -->';
			// kmlString+=' <TimePrimitive>...<\/TimePrimitive>';
			kmlString += '  <Point>';
			kmlString += '  		<coordinates>';
			kmlString += '  			' + lng + ',' + lat;
			kmlString += '  		</coordinates>';
			kmlString += '  </Point>';
			kmlString += '  <styleUrl>#styleMap_' + styleMapName + '<\/styleUrl>';
			// kmlString+=' <StyleSelector>...<\/StyleSelector>';
			// kmlString+=' <Region>...<\/Region>';
			// kmlString+=' <Metadata>...<\/Metadata> <!-- deprecated in KML 2.2
			// -->';
			// kmlString+=' <ExtendedData>...<\/ExtendedData> <!-- new in KML
			// 2.2 -->';
			// kmlString+=' <!-- specific to Placemark element -->';
			// kmlString+=' <Geometry>...<\/Geometry>';
			kmlString += '<\/Placemark>';

		} else {
			trace("!!!!!!!!!!!!!!!!!!! error creating placemark");
			trace(placemark_vo);
		}
	}
	
	kmlString += '  <\/Document>';
	kmlString += '<\/kml>';

	if (PlacemarkFactory.folders[folderName]) {
		folder = PlacemarkFactory.folders[folderName];
	} else {
		folder = this._createFolder(folderName);
//		this._createStyleMap(folderName);
	}

	var new_placemarks = ge.parseKml(kmlString);
	folder.getFeatures().appendChild(new_placemarks);

	// placemarks
	var arr_placemarks = folder.getFeatures().getFirstChild().getFeatures()
			.getChildNodes();

	return arr_placemarks;

};

/**
 * function getFolder(folderName)
 * 
 * @memberOf PlacemarkFactory
 * @param {String}
 *            folderName
 * @type KmlFolder
 * @returns {KmlFolder} folder
 */
PlacemarkFactory.prototype.getFolder = function(folderName) {
	return PlacemarkFactory.folders[folderName]
	                                || this._createFolder(folderName);
};

/**
 * function getStyleMap(styleMapName)
 * 
 * @memberOf PlacemarkFactory
 * @param {String}
 *            styleMapName
 */
PlacemarkFactory.prototype.getStyleMap = function(styleMapName) {
	return PlacemarkFactory.stylemaps[styleMapName]
			|| this._createStyleMap(styleMapName);
};

/**
 * function folderExists(folderName)
 * 
 * @memberOf PlacemarkFactory
 * @param {String}
 *            folderName
 * @type KmlFolder
 * @returns {KmlFolder} folder
 */
PlacemarkFactory.prototype.folderExists = function(folderName) {
	var out = (PlacemarkFactory.folders[folderName] != null);
	return out;
};

/**
 * function styleMapExists(styleMapName)
 * 
 * @memberOf PlacemarkFactory
 * @param {String}
 *            styleMapName
 */
PlacemarkFactory.prototype.styleMapExists = function(styleMapName) {
	var out = (PlacemarkFactory.stylemaps[styleMapName] != null);
	return out;
};

/**
 * function _getCoords()
 * 
 * @memberOf PlacemarkFactory
 * @type Object
 * @returns {Object} point
 */
PlacemarkFactory.prototype._getCoords = function() {

	var point = this.ge.createPoint('');
	var la = this.ge.getView()
			.copyAsLookAt(this.ge.ALTITUDE_RELATIVE_TO_GROUND);
	var lat = la.getLatitude();
	var lng = la.getLongitude();
	point.setLatitude(lat);
	point.setLongitude(lng);
	return point;

};

/**
 * function _createStyleMap(folderName)
 * 
 * @memberOf PlacemarkFactory
 * @param {String}
 *            styleMapName
 * @type String
 * @returns {String} stylemapname
 */
PlacemarkFactory.prototype._createStyleMap = function(styleMapName) {

//	trace("PlacemarkFactory._createStyleMap("+styleMapName+")");
	
	var offsetX = 0;
	var offsetY = 0;
	var scale = 2;
	var units = ge.UNITS_FRACTION; // UNITS_FRACTION, UNITS_PIXELS

	// IMPOSTAZIONE VARIABILI
	var normalPNG;
	var highLightPNG;
	
	var attivita = styleMapName.split("_")[0];
//	trace("attivita: "+attivita);

	switch (attivita) {
	case GoogleEarthPlugin.FOLDER_ALL:
		normalPNG = Configurazione.siteUrl + 'contenuti/icons/icon_all';
		highLightPNG = Configurazione.siteUrl + 'contenuti/icons/icon_all';
		break;
	case GoogleEarthPlugin.FOLDER_EXPLORATION:
		normalPNG = Configurazione.siteUrl + 'contenuti/icons/icon_exploration';
		highLightPNG = Configurazione.siteUrl + 'contenuti/icons/icon_exploration';
		break;
	case GoogleEarthPlugin.FOLDER_GAS:
		normalPNG = Configurazione.siteUrl + 'contenuti/icons/icon_gas';
		highLightPNG = Configurazione.siteUrl + 'contenuti/icons/icon_gas';
		break;
	case GoogleEarthPlugin.FOLDER_INGEGNERIA:
		normalPNG = Configurazione.siteUrl + 'contenuti/icons/icon_ingegneria';
		highLightPNG = Configurazione.siteUrl + 'contenuti/icons/icon_ingegneria';
		break;
	case GoogleEarthPlugin.FOLDER_PETROLCHIMICA:
		normalPNG = Configurazione.siteUrl + 'contenuti/icons/icon_petrol';
		highLightPNG = Configurazione.siteUrl + 'contenuti/icons/icon_petrol';
		break;
	case GoogleEarthPlugin.FOLDER_REFINING:
		normalPNG = Configurazione.siteUrl + 'contenuti/icons/icon_refining';
		highLightPNG = Configurazione.siteUrl + 'contenuti/icons/icon_refining';
		break;
	default:
		normalPNG = Configurazione.siteUrl + 'contenuti/icons/icon_all';
		highLightPNG = Configurazione.siteUrl + 'contenuti/icons/icon_all';
		break;
	}
	
	var hasGallery = styleMapName.split("_")[1];
	var hasVideo = styleMapName.split("_")[2];
	
	if (hasGallery=="g") {
		normalPNG+="_g";
		highLightPNG+="_g";
	}
	
	if ((hasVideo=="v")||(hasGallery=="v")) { // fix nel caso ci siano solo video
		normalPNG+="_v";
		highLightPNG+="_v";
	}
	
	normalPNG+=".png";
//	trace("	normalPNG: "+normalPNG);
	highLightPNG+=".png";

	var str = '';
	str += '<?xml version="1.0" encoding="UTF-8"?>';
	str += '<kml xmlns="http:\/\/www.opengis.net\/kml\/2.2">';
	str += '  <Document>';
	str += '    <Style id="styleIconHighlight_' + styleMapName + '">';
	str += '      <IconStyle>';
	str += '      <scale>' + scale + '<\/scale>';
	str += '		<hotSpot x="' + offsetX + '" y="' + offsetY + '" xunits="'
			+ units + '" yunits="' + units + '"></hotSpot>';
	str += '        <Icon>';
	str += '          <href>' + highLightPNG + '<\/href>';
	str += '        <\/Icon>';
	str += '      <\/IconStyle>';
	str += '    <\/Style>';
	str += '    <Style id="styleIconNormal_' + styleMapName + '">';
	str += '      <IconStyle>';
	str += '      <scale>' + scale + '<\/scale>';
	str += '		<hotSpot x="' + offsetX + '" y="' + offsetY + '" xunits="'
			+ units + '" yunits="' + units + '"></hotSpot>';
	str += '        <Icon>';
	str += '          <href>' + normalPNG + '<\/href>';
	str += '        <\/Icon>';
	str += '      <\/IconStyle>';
	str += '    <\/Style>';
	str += '    <StyleMap id="styleMap_' + styleMapName + '">';
	str += '      <Pair>';
	str += '        <key>normal<\/key>';
	str += '        <styleUrl>#styleIconNormal_' + styleMapName + '<\/styleUrl>';
	str += '      <\/Pair>';
	str += '      <Pair>';
	str += '        <key>highlight<\/key>';
	str += '        <styleUrl>#styleIconHighlight_' + styleMapName + '<\/styleUrl>';
	str += '      <\/Pair>';
	str += '    <\/StyleMap>';
	str += '  <\/Document>';
	str += '<\/kml>';

	var style = ge.parseKml(str);
	ge.getFeatures().appendChild(style);
	
	PlacemarkFactory.stylemaps[styleMapName] = style;

	return '#styleMap_' + styleMapName;

};

/**
 * function _createFolder(folderName)
 * 
 * @memberOf PlacemarkFactory
 * @param {String}
 *            folderName
 * @type KmlFolder
 * @returns {KmlFolder} folder
 */
PlacemarkFactory.prototype._createFolder = function(folderName) {
	var folder = PlacemarkFactory.folders[folderName];
	if (folder)
		return folder;
	//
	folder = this.ge.createFolder(folderName);
	PlacemarkFactory.folders[folderName] = folder;
	folder.setVisibility(true);
	folder.setOpen(true);
	this.ge.getFeatures().appendChild(folder);
	return folder;
};
