﻿/* Google Maps Functions: Reads a XML file and put some points in the map
/* First creation by Genís.
/* Updated to Google Maps V3 and documented by Xavier Vallejo
/* 2-10-10
*/

//Changes from V2 to V3: 
//- iPhone and Android support, faster load, no API key, geolocalitation...
//- IE6 is not supported :)

//Global variables
var map; //Our map
var center = new google.maps.LatLng(42.267528,2.960815); //V3, by default, catalunya
var zoom = 9; //Default zoom level
var clickedpoint; //Used when we click on a marker.

//Our code!
//Template calls "addLoadEvent" and the argument func is "MapaVeure"
function addLoadEvent(func) {
	//Check if IE or the others...
 	if (typeof window.onload != 'function') {
 		window.onload = func;
 	} else {
 		window.onload = function () {
 			func();
 		}
 	}
}

//Init Map, load XML and sets the Client
var MapaVeure = function () {
	Mapa.init();
	Mapa.llegeixXML();
	geocoder = new google.maps.Geocoder();
}

//The GControl interface is not used anymore for adding custom controls to the map. 
//In Google Maps API v3 custom controls are purely build with html, positioned on the map container and added the required event listeners.

 function CatControl(map){
 //Create personalized DIV to add our buttons (on top-left)! In this case, two zones: Costa Brava-Romania
 //The old Mapa/Satèl·lit buttons are useless in this case.
 
 //Create the general DIV
 var container = document.createElement("div");
 container.setAttribute("class","caixeszoom");
 
 //Create the two buttons, each one is a div
 var mapcbr = document.createElement("div");
 mapcbr.innerHTML = "Costa Brava";
 mapcbr.id="cbr";
 this.setButtonStyle_(mapcbr);
   
 var maprom = document.createElement("div");
 maprom.innerHTML = "Romania";
 maprom.id="rom";
 this.setButtonStyle_(maprom);
 
 //Define the events of the buttons. When clicked, change style of the two buttons.
 google.maps.event.addDomListener(mapcbr, 'click', function() {
  	CatControl.prototype.setButtonStyle_(maprom);
	CatControl.prototype.setButtonStyle2_(mapcbr);
	map.setCenter(new google.maps.LatLng(42.065607, 2.790527));
	map.setZoom(9);
 });
 
 google.maps.event.addDomListener(maprom, 'click', function() {
  	CatControl.prototype.setButtonStyle_(mapcbr);
	CatControl.prototype.setButtonStyle2_(maprom);
	map.setCenter(new google.maps.LatLng(46.179837, 25.202637));
	map.setZoom(6);
 });

 //Append the 2 buttons in the container DIV.
 container.appendChild(mapcbr);
 container.appendChild(maprom);

 //Add our DIV to the map
 map.getDiv().appendChild(container);
 return container;
}

CatControl.prototype.getDefaultPosition = function() {
	return new google.maps.ControlPosition(TOP_LEFT, new google.maps.Size(68, 7));
}

CatControl.prototype.setButtonStyle_ = function(button) {
 // button.style.textDecoration = "underline";
 button.style.color = "#000";
 button.style.backgroundColor = "white";
 button.style.font = "small Arial";
 button.style.border = "1px solid black";
 button.style.padding = "2px";
 button.style.marginTop = "7px";
 button.style.textAlign = "center";
 button.style.width = "5em";
 button.style.cursor = "pointer";
}

CatControl.prototype.setButtonStyle2_ = function(button) {
 // button.style.textDecoration = "underline";
 button.style.color = "#000";
 button.style.backgroundColor = "#CCCFBF";
 button.style.font = "small Arial";
 button.style.border = "1px solid black";
 button.style.padding = "2px";
 button.style.marginBottom = "1px";
 button.style.textAlign = "center";
 button.style.width = "5em";
 button.style.cursor = "pointer";
}

var Mapa={
 init:function() {
 //V3 don't have GBrowserIsCompatible equivalent.
 
 //Create the Map with ID="mapa", but first define all the controls.
 var myOptions = {
  zoom: zoom,
  center: center,
  scrollwheel: true,
  navigationControl: true,
  navigationControlOptions: { style: google.maps.NavigationControlStyle.LARGE},
  mapTypeId: google.maps.MapTypeId.ROADMAP, //G_NORMAL_MAP. Other Options: SATELLITE, HYBRID, TERRAIN
  mapTypeControl: true,
  streetViewControl: true //NEW in V3!!!
 }
 map = new google.maps.Map(document.getElementById("mapa"), myOptions);
 //Adds a custom controller
 map.controls[google.maps.ControlPosition.TOP_LEFT].push(new CatControl(map));
 },
 
//Function that opens a XML, parse it and sets the Markers.
//Google Maps V3 doesn't have GDownloadUrl and GXml, so we can use other AJAX queries.
llegeixXML:function() {
  //Custom function in util.js
  downloadUrl("http://www.larespromocions.com/web/xml/negocis.xml", function(data) {
 	var markers = data.documentElement.getElementsByTagName("immoble");
    for (var i = 0; i < markers.length; i++) {
    	var point = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lon")));
    	//Get data from XML
 		var id = markers[i].getAttribute("ref");
 		var nom = markers[i].getAttribute("titol");
 		var localitat = markers[i].getAttribute("pob");
 		var preu = markers[i].getAttribute("preu");
 		var tipus = markers[i].getAttribute("tipus");
 		var cat = markers[i].getAttribute("cat");
 		var web = markers[i].getAttribute("link");
 		var foto1 = markers[i].getAttribute("foto1");
 		//Create the Marker!
        Mapa.createMarker(point, id, nom, localitat, preu, tipus, cat, web, foto1);
    }
  });
 },

 //Funció que crea un marcador amb les dades
 createMarker:function(point, id, nom, localitat, preu, tipus, cat, web, foto1) { 
 iconBlue = new google.maps.MarkerImage(
	'http://labs.google.com/ridefinder/images/mm_20_blue.png',
 	new google.maps.Size(12,20),
 	new google.maps.Point(0,0),
 	new google.maps.Point(6,20)
 );
 iconShadow = new google.maps.MarkerImage(
 	'http://labs.google.com/ridefinder/images/mm_20_shadow.png',
 	new google.maps.Size(22,20),
 	new google.maps.Point(0,0),
 	new google.maps.Point(6,20)
 );
 
 	var title=nom+","+localitat+","+preu;
 	//Create new Marker
 	var mark = new google.maps.Marker({
  		position: point,
  		map: map,
 		title: title,
  		icon: iconBlue,
  		shadow: iconShadow
	});
 	// Si es fa clic sobre un marker
 	google.maps.event.addListener(mark, 'click', function() {
    	clickedpoint = mark.getPosition(); //Obtain Lat and Lng
    	//Create new InfoWindow of the Marker (V3 can open multiple Infowindows)
    	var infowindow = new google.maps.InfoWindow({
        	content: makeWindow2(nom, localitat, preu, tipus, cat, web, foto1)
        });
        //Show the window
        infowindow.open(map, mark);
        google.maps.event.addListener(infowindow,'domready',function(){
        	 $("#tabs").tabs();
        });
  	});
 },

 //Function used when we search the city in the FORM
 showLocation:function() {
 	  myform = document.getElementById('formSearch');
	  var dir = myform.q.value+", Spain";

	  geocoder.geocode( {'address': dir }, function(results, status) {
	  	if (status != google.maps.GeocoderStatus.OK) {
			alert("Lo sentimos, no se ha podido encontrar la dirección.");
	  	} else {
	  		//Get ONLY FIRST AVAILABLE RESULT!
			place = results[0].geometry.location; //v3
			point = new google.maps.LatLng(place.lat(),place.lng());
			// ComprobaZoom abans de res
			map.setCenter(point); //point
			map.setZoom(14);
	  	}
	  });
 },	
	
 //Zoom a resolució correcta
 zoomOn: function() {
 	infowindow.close();
 	map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
 	map.setCenter(clickedpoint); //clickedpoint is defined when we create the Marker.
 	map.setZoom(16);
 },

 zoomFull: function() {
 	infowindow.close();
 	map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
    map.setCenter(center);
    map.setZoom(zoom);
 }

} 

//Google MAPS V3 doesn't have GInfoWindowTab (yet). So we can use jQuery Tabs :)
function makeWindow2(nom, localitat, preu, tipus, cat, web, foto1) {
  // Create an array that will hold the tabs 
  var tabs = [
      '<div id="tabs">',
      '<ul>',
        '<li><a href="#tab-1"><span>Información</span></a></li>',
        '<li><a href="#tab-2"><span>Foto</span></a></li>',
      '</ul>',
      '<div id="tab-1">',
        "<p align='center' style='font-size:14px;font-weight:bold;'>" + nom + "</p><p align='center'>"+ preu + "<br/>" + localitat + "<br/>" + tipus + "<br/>" + cat + "<br/>" + "<a href='"+ web +"'>" + 'ver detalles' + "</a></p>",
      '</div>',
      '<div id="tab-2">',
       "<p align='center'><a href='"+ web +"'><img width='100px' height='100px'src='uploads/immobles/"+ foto1 + "'></a></p>",
      '</div>',
      '</div>'
  ].join('');

 return tabs;
} 

