/**
 *
 *	PRE: getPosiciomouse.js
 *
 */
var map = null;
var gBarris = Array();
var gIcons = Array();
gIcons.lastIcon = function(){
	if (this.length > 0) return this[this.length-1];
	return null;
}



function initMapa(latIni, lonIni, zoomIni)
{
  if(GBrowserIsCompatible())
  {
    if(!document.getElementById('mapaDiv')) return false;
    map = new GMap2(document.getElementById('mapaDiv'));
    map.enableContinuousZoom();
    map.enableDoubleClickZoom();
    //map.addControl(new GLargeMapControl());
    //map.addControl(new GMapTypeControl());
    map.addControl(new GSmallMapControl());

    // Event OnLoad del mapa
	GEvent.addListener(map, "load", function() {
		_onLoadMap();
	});

	function getAbsolutePosition(element) {
	  var r = { x: element.offsetLeft, y: element.offsetTop };
	  if (element.offsetParent) {
	    var tmp = getAbsolutePosition(element.offsetParent);
	    r.x += tmp.x;
	    r.y += tmp.y;
	  }
	  return r;
	};


	/*
	Es molt millor utilitzar l'event MouseMove des de fora del mapa, és molt més ràpid
	GEvent.addListener(map, "mousemove", function(e)
	{
	});
	*/

    map.setCenter(new GLatLng(latIni, lonIni), zoomIni);

		/*
		// Al clickar al mapa crea un poligon
		GEvent.addListener(map, "click", function(overlay,latlng) {
		  var lat = latlng.lat();
		  var lon = latlng.lng();
		  var latOffset = 0.01;
		  var lonOffset = 0.01;
		  var polygon = new GPolygon([
		    new GLatLng(lat, lon - lonOffset),
		    new GLatLng(lat + latOffset, lon),
		    new GLatLng(lat, lon + lonOffset),
		    new GLatLng(lat - latOffset, lon),
		    new GLatLng(lat, lon - lonOffset)
				], "#f33f00", 5, 1, "#ff0000", 0.2);
			map.addOverlay(polygon);
			aa();
		});
		*/


/*
		// Al clickar al mapa indica la posició i el zoom
		GEvent.addListener(map,"click", function(overlay,latlng) {
		  if (overlay) {
		    // ignore if we click on the info window
		    return;
		  }
		  var tileCoordinate = new GPoint();
		  var tilePoint = new GPoint();
		  var currentProjection = G_NORMAL_MAP.getProjection();
		  tilePoint = currentProjection.fromLatLngToPixel(latlng, map.getZoom());
		  tileCoordinate.x = Math.floor(tilePoint.x / 256);
		  tileCoordinate.y = Math.floor(tilePoint.y / 256);
		  var myHtml = "Latitude: " + latlng.lat() + "<br/>Longitude: " + latlng.lng() +
		    "<br/>The Tile Coordinate is:<br/> x: " + tileCoordinate.x +
		    "<br/> y: " + tileCoordinate.y + "<br/> at zoom level " + map.getZoom();
		  map.openInfoWindow(latlng, myHtml);
		 });
*/

  }//end browser compatible
}



function _onLoadMap()
{
	if (typeof onLoadMap == "function") onLoadMap();
	if (typeof pintaBarris == "function") pintaBarris();
}

function getDefaultIcon()
{
  var icon = new GIcon();
  icon.image =  './img/'+HOST+'/apartments.png';
  icon.shadow = './img/iconsApartments/shadow.png';
  icon.iconSize = new GSize(34,38);
  icon.shadowSize = new GSize(34,38);
  icon.iconAnchor = new GPoint(17,34);
  icon.infoWindowAnchor = new GPoint(17,0);
//  icon.printImage = 'http://google.webassist.com/google/markers/flag/pacifica.gif';
//  icon.mozPrintImage = 'http://google.webassist.com/google/markers/flag/pacifica_mozprint.png';
//  icon.printShadow = 'http://google.webassist.com/google/markers/flag/shadow.gif';
  icon.transparent = './img/'+HOST+'/apartments-trans.png';
  return icon;
}

function insertIconMap(lat, lon, msg, icon)
{
	if (!icon) icon = getDefaultIcon();

	if (lat != "" && lon != "")
	{
		var marker = new GMarker(new GPoint(lat, lon), icon);
		if (msg != ""){
			GEvent.addListener(marker, 'click', function() {
				marker.openInfoWindowHtml(msg);
			});
		}
		map.addOverlay(marker);
	}
}

function askPosition(addr, idApart, msg, icon)
{
	// Si no tenim latitud i longitud, busquem
	var geocoder = new GClientGeocoder();
	geocoder.getLatLng (
		addr,
		function(point) {
			if(point) {
				// Guardem la posició de l'apartament a la base de dades
				consultaHttp("process/processProduct_A.php?action=setLatLonApart&lat="+point.x+"&lon="+point.y+"&productId="+idApart);

				if (!icon) icon = getDefaultIcon();
				var marker = new GMarker(point, icon);
				GEvent.addListener(marker, 'click', function() {
					marker.openInfoWindowHtml(msg);
				});
				map.addOverlay(marker);

			}
		}
	);
}

function pintaBarris()
{
	var gruixVores = 3;
	var opacitatVores = 1;
	var opacitatInterior = 0.25;

	for (var i=0; i<gBarris.length; i++){
		var colorVores = gBarris[i].selected ? gBarris[i].colorVoresSelected : gBarris[i].colorVores;
		var colorInterior = gBarris[i].selected ? gBarris[i].colorInteriorSelected : gBarris[i].colorInterior;
		var polygon = new GPolygon(gBarris[i].getPunts(), colorVores, gruixVores, opacitatVores, colorInterior, opacitatInterior);
		GEvent.bind(polygon, "mouseover", gBarris[i], gBarris[i].showNom);
		GEvent.bind(polygon, "mouseout", gBarris[i], gBarris[i].hideNom);
		GEvent.bind(polygon, "click", gBarris[i], gBarris[i].goto);

		map.addOverlay(polygon);
	}

}



//##########################################################################################
//##########################################################################################



/**
 *	Aquest objecte pinta uns poligons que representen barris
 */
function CBarri(map)
{
	this.colorVores = "#757575";
	this.colorInterior = "#ffffff";
	this.colorVoresSelected = "#757575";
	this.colorInteriorSelected = "#666666";
	this.map = map;
	this.punts = Array();
	this.nom = "";
	this.link = "";
	this.containerNom = null;	// objecte GLatLngBounds
	this.nomObj = null;
	this.selected = false;
}
CBarri.prototype.setPunts = function (arrPnts){
	this.punts = arrPnts;
}
CBarri.prototype.setNom = function (nom){
	this.nom = "<div style='position:absolute; background-color:#ffffff; text-align:center; padding:5px; '>"+nom+"</div>";
}
CBarri.prototype.setContainerNom = function (container){
	this.containerNom = container;
}
CBarri.prototype.getPunts = function (arrPnts){
	return this.punts;
}
CBarri.prototype.getNom = function (nom){
	return this.nom;
}
CBarri.prototype.getContainerNom = function (){
	return this.containerNom;
}
CBarri.prototype.showNom = function (){
	mostraEtiquetaNomBarri(this.nom);
	/*
	if (this.nomObj == null){
		this.nomObj = new EscriuText(this.map, this.containerNom, this.nom);
		map.addOverlay(this.nomObj);
	}
	*/
}
CBarri.prototype.hideNom = function (){
	ocultaEtiquetaNomBarri();
	/*
	if (this.nomObj != null){
		map.removeOverlay(this.nomObj);
		this.nomObj = null;
	}
	*/
}
CBarri.prototype.setLink = function (link){
	this.link = link;
}
CBarri.prototype.goto = function (){
	if (this.link != "") document.location = this.link;
}

CBarri.prototype.setColorFons = function (color){
	this.colorInterior = color;
}
CBarri.prototype.setColorVores = function (color){
	this.colorVores = color;
}
CBarri.prototype.setSelected = function (){
	this.selected = true;
}




//##########################################################################################
//##########################################################################################

/**
 *	Aquest objecte escriu text al damunt del mapa.
 *
 *	@param bounds (GLatLngBounds) Container de la capa que contindrà el text
 *	@param textHTML (string) Text HTML a escriure
 */

/*
function EscriuText(map, bounds, textHTML)
{
	this.map_ 			= map;
	this.bounds_ 		= bounds;
	this.textHTML_ 	= textHTML;
	this.div_ 			= null;
}
EscriuText.prototype = new GOverlay();

// Creem un DIV on hi posarem el text
EscriuText.prototype.initialize = function(map) {
	var div = document.createElement("div");
	div.style.position = "absolute";
	div.setAttribute("class", "textGMaps");
	div.setAttribute("className", "textGMaps");
	div.style.textAlign = "left";
	div.innerHTML = this.textHTML_;

	this.div_ = div;


	// Fem que el text aparegui al fons de tot (incloses les ombres de les icones)
	this.map_.getPane(G_MAP_MARKER_SHADOW_PANE).appendChild(div);
}

// Eliminar el DIV del mapa
EscriuText.prototype.remove = function() {
	this.div_.parentNode.removeChild(this.div_);
	gEtiquetaNomBarri = "";
}

// Copy our data to a new Rectangle
EscriuText.prototype.copy = function() {
	return new EscriuText(this.pos_, this.textHTML_);
}

// Repinta la capa depenent de la projecció i el zoom actual
EscriuText.prototype.redraw = function(force) {
	// Si no hi ha un canvi de zoom no cal fer res
	if (!force) return;

	var c1 = this.map_.fromLatLngToDivPixel(this.bounds_.getSouthWest());
	var c2 = this.map_.fromLatLngToDivPixel(this.bounds_.getNorthEast());

  // Now position our DIV based on the DIV coordinates of our bounds
  this.div_.style.width =  Math.abs(c2.x - c1.x) + "px";
  this.div_.style.height = Math.abs(c2.y - c1.y) + "px";
  this.div_.style.left =   Math.min(c2.x, c1.x)  + "px";
  this.div_.style.top =    Math.min(c2.y, c1.y)  + "px";

  var z = this.map_.getZoom();
  if (z == 13) this.div_.style.fontSize = "16px";
  else if (z == 12) this.div_.style.fontSize = "12px";
  else if (z == 11) this.div_.style.fontSize = "8px";
}


*/