var map; // global var to store the google map
var centerCoord = new google.maps.LatLng(45.40048,-71.88374); // Sherbrooke
var browserDetectedLocation = null;

// global variables used throughout the js functionality
var markersArray = [];
var infoWindow = new google.maps.InfoWindow({});

function setLocation()
{
	// try to get user location via W3C standard Geolocation in browsers or via Google Gears
	if(navigator.geolocation) 
	{
	    navigator.geolocation.getCurrentPosition(function(position) 
		{
			blueIcon = "http://apanq.qc.ca/wp/wp-content/themes/apanq/images/you.png";
			browserDetectedLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
			map.setCenter(browserDetectedLocation);
			
			var marker = new google.maps.Marker({
			      position: browserDetectedLocation, 
			      map: map, 
			      title: 'Vous \352tes ici',
				  icon: blueIcon,
				  zIndex: 0
			});
			//addMarker(browserDetectedLocation,'You are here!');
			$('#home-messages').text("On vous a localis\351...");
	    }, function() {
	     // error getting location, though supported
			$('#home-messages').text("On n'arrive pas \340 vous localiser");
	    });
	} else if (google.gears) 
	// if location not found using W3C standard try with Google Gears if browser supports it
	{
	    var geo = google.gears.factory.create('beta.geolocation');
	    geo.getCurrentPosition(function(position) 
		{
			blueIcon = "http://apanq.qc.ca/wp/wp-content/themes/apanq/images/you.png";
			browserDetectedLocation = new google.maps.LatLng(position.latitude,position.longitude);
			map.setCenter(browserDetectedLocation);
			var marker = new google.maps.Marker({
			      position: browserDetectedLocation, 
			      map: map, 
			      title: 'Vous \352tes ici',
				  icon: blueIcon,
				  zIndex: 0
			});
			
			//addMarker(browserDetectedLocation,'You are here!');
			$('#home-messages').text('On vous a localis\351...');
	    }, function() {
			// error getting location, though supported
			$('#home-messages').text("On n'arrive pas \340 vous localiser");
	    });
	} 
	else	
	{
		// Browser doesn't support Geolocation
		$('#home-messages').text("On n'arrive pas \340 vous localiser");
	}	
}

function InitMap(options, mapIdentifier, defaultLocation, detectLocation)
{ // function to initialize map
	var settings = // json variable for default settings
	{
		zoom: 7,
		center: defaultLocation,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	if (options!=null) settings = options; // if no options provided, start the map with default settings
	map = new google.maps.Map(document.getElementById(mapIdentifier), settings);
		
	map.setCenter(defaultLocation);
	if(detectLocation==true) setLocation(); // try to get user location via W3C standard Geolocation in browsers or via Google Gears
	else
	{
		$('#home-messages').text("Cliquez sur une sapini\350re \340 droite pour la localiser");
	}
	// idle - This event is fired when the map becomes idle after panning (dragging moving etc) or zooming
	/*google.maps.event.addListener(map, 'idle', function() {
		clearOverlays();
	  });
	*/
	
	return map;
}

function handle_clicks()
{
	$('#home-sidebar ul li a').live('click',function(){
		var coordString = $(this).attr('rel');
		var coordTitle = $(this).text();
		var coordArray = coordString.split(',');
		var update2Location = new google.maps.LatLng(coordArray[0],coordArray[1]);
		map.setCenter(update2Location);
		addMarker(update2Location,coordTitle,coordArray[2]);
		
  		$('#home-messages').text("Visionnement de : "+coordTitle);
	});
}

/*function addMarker(m_position,m_title,m_infowindow) {
	marker = new google.maps.Marker({
	  	position: m_position,
	  	map: map,
		title: m_title
	});
	markersArray.push(marker);
  	var mark = markersArray.pop();
	google.maps.event.addListener(mark, 'click', function() {
		infoWindow.open(map,mark);
		var stringContent = m_infowindow;
		infoWindow.setContent("<div id=\"infowin-overlay\""+stringContent+"</div>");
		
		overlayHeight = $('#infowin-overlay').height();
		overlayWidth = $('#infowin-overlay').width();
		$('#infowin-overlay').parent().css('height',overlayHeight);
		$('#infowin-overlay').parent().css('width',overlayWidth);
	});
	
	markersArray.push(mark);
}*/

function addMarker(m_position,m_title,m_infowindow) {
	var markerAdded = false;
	var mark;

	if (markersArray.length!=0) 
	{
		duplicate = false;
		var markcopy;
		var markersCopy = [];
		while(markcopy=markersArray.pop())
		{
			if((markcopy.position.lat()==m_position.lat())&&(markcopy.position.lng()==m_position.lng())) duplicate = true;
			markersCopy.push(markcopy);
		}
		markersArray = markersCopy;
		if(duplicate==false)
		{
			sapin = "http://apanq.qc.ca/wp/wp-content/themes/apanq/images/sapin.png";
			marker = new google.maps.Marker({
			  	position: m_position,
			  	map: map,
				title: m_title,
				icon: sapin,
				zIndex: 0
			});
			markersArray.push(marker);
			mark = markersArray.pop();
			google.maps.event.addListener(mark, 'click', function() {
				infoWindow.open(map,mark);
				var stringContent = m_infowindow;
				infoWindow.setContent("<div id=\"infowin-overlay\""+stringContent+"</div>");

				overlayHeight = $('#infowin-overlay').height();
				overlayWidth = $('#infowin-overlay').width();
				$('#infowin-overlay').parent().css('height',overlayHeight);
				$('#infowin-overlay').parent().css('width',overlayWidth);
			});
			markersArray.push(mark);
		}
	}
	else
	{
		sapin = "http://apanq.qc.ca/wp/wp-content/themes/apanq/images/sapin.png";
		marker = new google.maps.Marker({
		  	position: m_position,
		  	map: map,
			title: m_title,
			icon: sapin,
			zIndex: 0
		});
		markersArray.push(marker);
		mark = markersArray.pop();
		google.maps.event.addListener(mark, 'click', function() {
			infoWindow.open(map,mark);
			var stringContent = m_infowindow;
			infoWindow.setContent("<div id=\"infowin-overlay\""+stringContent+"</div>");

			overlayHeight = $('#infowin-overlay').height();
			overlayWidth = $('#infowin-overlay').width();
			$('#infowin-overlay').parent().css('height',overlayHeight);
			$('#infowin-overlay').parent().css('width',overlayWidth);
		});
		markersArray.push(mark);
	}
}
/* end of functions */


$(document).ready(function(){
	if($('#map').get(0))
	{ // only initialize the map if map is located inside the page
		map = InitMap(null,'map', centerCoord, true); // initialize the map on default location
		handle_clicks(); // click events handling by jQuery	
	}
	
	/* Plantations Rˇal Beloin Inc. */
	addMarker(new google.maps.LatLng(45.07989,-71.49849),"Plantations R\351al Beloin Inc.","<p>Plantations R\351al Beloin Inc.<br />R\351al Beloin<br />74 - rue De l'\311glise - East Hereford - Qu\351bec - J0B 1S0<br /><br />819-844-2223<br /><a href='mailto:info@plantationsrealbeloin.com'>info@plantationsrealbeloin.com</a><br /><a href='http://www.plantationsrealbeloin.com' target='_blank'>www.plantationsrealbeloin.com</a><br /><br /><a href='http://g.co/maps/e9uxw' target='_blank'>Indications routi\350res</a></p>");
	
	/* Arbres de No‘l C™tˇ-Henderson */
	addMarker(new google.maps.LatLng(46.26839,-71.47861),"Arbres de No\353l C\364t\351-Henderson","<p>Arbres de No\353l C\364t\351-Henderson<br />Francis C\364t\351<br />2386 - Rang 8 - Inverness - Qu\351bec - G0S 1K0<br /><br />418-453-2482<br /><a href='mailto:emcote@sympatico.ca'>emcote@sympatico.ca</a><br /><br /><a href='http://g.co/maps/ptjnc' target='_blank'>Indications routi\350res</a></p>");
	
	/* Plantations J.J. Croteau Inc. */
	addMarker(new google.maps.LatLng(45.96484,-71.60755),"Plantations J.J. Croteau Inc.","<p>Plantations J.J. Croteau Inc.<br />J\351r\364me et Yanick Croteau<br />434 - rue du cap - St-Fortunat - Qu\351bec - G0P 1G0<br /><br />819-344-5483<br /><a href='mailto:jjcroteau@hotmail.com'>jjcroteau@hotmail.com</a><br /><a href='http://www.jjcroteau.com' target='_blank'>www.jjcroteau.com</a><br /><br /><a href='http://g.co/maps/tgamn' target='_blank'>Indications routi\350res</a></p>");
	
	/* Plantation Le Baume */
	addMarker(new google.maps.LatLng(45.95832,-72.63818),"Plantation Le Baume","<p>Plantation Le Baume<br />Louis Desmarais<br />1192 - 6e Rang Nord - Saint-Bonaventure - Qu\351bec - J0C 1C0<br /><br />819-396-3036<br /><a href='http://g.co/maps/82an4' target='_blank'>Indications routi\350res</a></p>");
	
	/* Pˇpini¸re et Sapin¸re Downey Inc. */
	addMarker(new google.maps.LatLng(45.23035,-71.93779),"P\351pini\350re et Sapin\350re Downey Inc.","<p>P\351pini\350re et Sapin\350re Downey Inc.<br />Larry Downey<br />6196 - Chemin North - Hatley - Qu\351bec - J0B 1M0<br /><br />819-566-0319<br /><a href='mailto:info@sapinieredowney.com'>info@sapinieredowney.com</a><br /><a href='http://www.sapinieredowney.ca/' target='_blank'>www.sapinieredowney.ca</a><br /><br /><a href='http://g.co/maps/8ca6a' target='_blank'>Indications routi\350res</a></p>");
	
	/* Plantations Fernet */
	addMarker(new google.maps.LatLng(46.17625,-73.26759),"Plantations Fernet","<p>Plantations Fernet<br />C\351cile Grandchamp-Fernet<br />3000 - route B\351langer - Saint-Cuthbert - Qu\351bec - J0K 2C0<br /><br />450-836-2403<br /><a href='mailto:info25@sapins-noel.com'>info25@sapins-noel.com</a><br /><a href='http://www.sapins-noel.com/' target='_blank'>www.sapins-noel.com</a><br /><br /><a href='http://g.co/maps/r6un4' target='_blank'>Indications routi\350res</a></p>");
	
	/* Plantation JLS Enr. */
	addMarker(new google.maps.LatLng(45.51213,-73.45668),"Plantation JLS Enr.","<p>Plantation JLS Enr.<br />Lucien Lapointe<br />3140 - rue de Lyon - Longueuil - Qu\351bec - J4L 3S1<br /><br />450-670-0878<br /><a href='mailto:info@sapinsdenoeljls.ca'>info@sapinsdenoeljls.ca</a><br /><a href='http://www.sapinsdenoeljls.ca' target='_blank'>www.sapinsdenoeljls.ca</a><br /><br /><a href='http://g.co/maps/8d5gk' target='_blank'>Indications routi\350res</a></p>");
	
	/* Les Sapins de l'ėle */
	addMarker(new google.maps.LatLng(46.06378,-72.81909),"Les Sapins de l'\316le","<p>Les Sapins de l'\316le<br />Daniel Leblanc<br />200 - Rang de l'\316le St-Jean - St-Fran\347ois du Lac Qc - Qu\351bec - J0G 1M0<br /><br />450-568-0828<br /><a href='mailto:dr.blanc1957@gmail.com'>dr.blanc1957@gmail.com</a><br /><br /><a href='http://g.co/maps/pn9p9' target='_blank'>Indications routi\350res</a></p>");
	
	/* Plantations Stˇphan Perreault 
	addMarker(new google.maps.LatLng(45.67118,-72.17845),"Plantations St\351phan Perreault","<p>Plantations St\351phan Perreault<br />St\351phan Perreault<br />331 - route 143 Nord - Windsor - Qu\351bec - J1S 0C1<br /><br />819-845-1160<br /><a href='#' target='_blank'>Indications routi\350res</a></p>");*/
	
	/* Les Plantations Univert */
	addMarker(new google.maps.LatLng(45.44352,-72.28769),"Les Plantations Univert","<p>Les Plantations Univert<br />Richard Plante<br />385 - 11e rang - Bonsecours - Qu\351bec - J0E 1H0<br /><br />450-535-6596<br /><a href='mailto:ricplante@cooptel.qc.ca'>ricplante@cooptel.qc.ca</a><br /><a href='http://www.pepinierearbresapinplanterjardin.com/' target='_blank'>www.pepinierearbresapinplanterjardin.com</a><br /><br /><a href='http://g.co/maps/r2uqp' target='_blank'>Indications routi\350res</a></p>");
	
	/* Plantation Steve */
	addMarker(new google.maps.LatLng(45.37298,-71.81793),"Plantation Steve","<p>Plantation Steve<br />Steve Robinson<br />1860 - Chemin Spring - Cookshire-Eaton - Qu\351bec - J0B 1M0<br /><br />819-569-7950<br /><a href='http://g.co/maps/qtv4d' target='_blank'>Indications routi\350res</a></p>");
	
	/* Plantation C & L. Tessier */
	addMarker(new google.maps.LatLng(45.30800,-71.52561),"Plantation C & L. Tessier","<p>Plantation C & L. Tessier<br />Carole Tessier<br />30 - chemin Rang 11 - St-Isidore de Clifton - Qu\351bec - J0B 2X0<br /><br />819-889-3150<br /><a href='http://g.co/maps/k8vx3' target='_blank'>Indications routi\350res</a></p>");
	
	/* Les Produits de la Ferme Vanasse (2006) Inc. */
	addMarker(new google.maps.LatLng(45.11351,-72.01921),"Les Produits de la Ferme Vanasse (2006) Inc.","<p>Les Produits de la Ferme Vanasse (2006) Inc.<br />R\351al et Christian Vanasse<br />1168 - chemin Vanasse - Ayer's Cliff - Qu\351bec - J0B 1C0<br /><br />819-838-4662<br /><a href='http://g.co/maps/kbhkd' target='_blank'>Indications routi\350res</a></p>");
	

});
