var map;
var mapControl;
var items;
var baseIcon = new GIcon();
	baseIcon.image = "";
	baseIcon.shadow = "";
	baseIcon.iconSize = new GSize(32, 32);
	baseIcon.shadowSize = new GSize(32, 32);
	baseIcon.iconAnchor = new GPoint(16, 32);
	baseIcon.infoWindowAnchor = new GPoint(16, 5);
var bounds;
var southWest;
var northEast;
var northEastLng = "-80";
var northEastLat = "64";
var southWestLng = "-56";
var southWestLat = "44";
/*var collection;*/
var query_from = "/geo.php";
var query_params;
var query_json;
var latlng;
var geoXml_ubg = new GGeoXml("http://avataq.qc.ca/design/fr/kml/upper_borden.kml");

var infoWinSkipPan = 0;

function initialize() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map_canvas"), { size: new GSize(699,550) } );
		map.setCenter(new GLatLng(59,-70), 5);
		map.savePosition();

//		GEvent.addListener(map, "infowindowclose", function (){
//			if(!infoWinSkipPan){
//				map.setCenter(map.getCenter(), 5);
//				window.setTimeout(function() {
//					map.panTo(new GLatLng(59,-70));
//				}, 500);
//			}
//			//infoWinSkipPan = 0;
//		});
//		
////		map.addMapType(G_SATELLITE_3D_MAP);

//		mapControl = new GMapTypeControl();
//		map.addControl(mapControl);
		map.setMapType(G_SATELLITE_MAP);
		map.setUIToDefault();
		
		toogleKML();
		
		bounds = map.getBounds();
	    southWest = bounds.getSouthWest();
	    northEast = bounds.getNorthEast();
	    northEastLng = northEast.lng();
	    northEastLat = northEast.lat();
	    southWestLng = southWest.lng();
	    southWestLat = southWest.lat();

		getJSON($('input[@name=mapTypes]:checked').val());
	}
}

function getJSON(collection) {
  if (collection) {
  	collection = collection; //$('input[@name=mapTypes]:checked').val();
  } else {
  	collection = "Community";
  }
    
	query_params = "?action=getItems&item=" + collection + "&max=10000&lat1=" + northEastLat + "&lon1=" + southWestLng + "&lat2=" + southWestLat + "&lon2=" + northEastLng;
	query_json = query_from + query_params;
	
	var itemsCnt = 0;
	
	$.getJSON(query_json, function(data){
		$.each(data, function(i,arg){
			items = arg.item.length;
			itemsCnt = itemsCnt + items;
			
			if (items > 0 && arg.communities.Village_geolocalisateur == "1") {
				$.each(arg.item, function(x){
					if (arg.item[x].Latitude && arg.item[x].Longitude) {
						point = new GLatLng(arg.item[x].Latitude, arg.item[x].Longitude);
					} else {
						point = new GLatLng(arg.communities.Latitude, arg.communities.Longitude);
					}
					
					loadMarkers(i,x,point,arg,collection);
				});
			}
		});
		
		if (itemsCnt == 0) {
			alert("Aucun résultat n'a été trouvé.");
		}
	});
}

function showMapType(jq_radio){
	map.clearOverlays();
	getJSON(jq_radio.val());
	map.setCenter(map.getCenter(), 5);

	window.setTimeout(function() {
		map.panTo(new GLatLng(59,-70));
	}, 1000);

	toogleKML();
}

function loadMarkers(i,x,point,arg,collection){
	var avataqIcon = new GIcon(baseIcon);
	avataqIcon.image = "/design/fr/images/markers/icon_" + collection + ".png";
	
	markerOptions = { icon:avataqIcon };
	var marker = new GMarker(point, markerOptions);
	
	GEvent.addListener(marker, "click", function (){
		infoWinSkipPan = 1;
		infoWindowHTML(i, x, marker, arg, collection);
		infoWinSkipPan = 0;
		map.setCenter(marker.getLatLng());
//		map.panTo(marker.getLatLng());
//		createMiniMap(point, i);
	});

	map.addOverlay(marker);
}


function createMiniMap(point, i) {
	var detailMap = new GMap2(document.getElementById("detailmap_" + i));
	detailMap.setMapType(G_SATELLITE_MAP);
	detailMap.setCenter(point, 13);
	detailMap.addControl(new GSmallMapControl());
}


function vignettes_txt(str_name, str_sujet, padded)
{
	var str = padded ? '<div class="vignettes-txt">' : "";
	str += (str_name != null && str_name) ? "<b>" + str_name + "</b><br/>" : "";
	str += (str_sujet != null && str_sujet) ? str_sujet + "<br/>" : "";
	str += padded ? '</div>' : "";
  return str;
}

function vignettes_img(items, item, imglink, str_name, str_sujet)
{
  var infowin = "";
	if (items.length >= 1 && items[0].Web_img_vignette != "") {
	  infowin += "<div class='picture'>";
    var rans = ranGen(items.length,2);
    for (var i = 0; i < rans.length; i++) {
      ran_item = items[rans[i]];
      infowin += '<div class="vignettes-img">';
      if (imglink != null) {
      	var left_part = '<a href="/fr/Les-Collections/Art-et-ethnographie/Artefacts/detail/?id=' + ran_item.ID_NIAC + '" class="knowmore">';
        infowin += left_part + "<img border='0' src='http://70.38.68.49/img/" + ran_item.Web_img_vignette + "'/></a>";
      }else{
        infowin += '<img border="0" src="http://70.38.68.49/img/' + ran_item.Web_img_vignette + '"/>';
      }
    	infowin += '<div class="vignettes-txt">';
    	infowin += (str_name != null && ran_item[str_name]) ? "<b>" + ran_item[str_name] + "</b><br/>" : "";
    	infowin += (str_sujet != null && ran_item[str_sujet]) ? ran_item[str_sujet] + "<br/>" : "";
    	infowin += '</div>';
      infowin += '</div>';
    }
	  infowin += "</div>";
	}else{
    infowin += (str_name != null && ran_item[str_name]) ? "<b>" + ran_item[str_name] + "</b><br/>" : "";
    infowin += (str_sujet != null && ran_item[str_sujet]) ? ran_item[str_sujet] + "<br/>" : "";
	}
	return infowin;
}

function community_images(arg, showMe){
  var info = "";
	if (arg.item.length >= 1 && arg.item[0].Web_img != "") {
		info += "<div class='picture'>";
		if(ran = ranGen(arg.item.length,2)){
			for (var i = 0; i < ran.length; i++) {
				info += "<img src='http://70.38.68.49/img/" + arg.item[ran[i]].Web_img + "'/>";
			}
    }else{
      info += "<img src='http://70.38.68.49/img/" + arg.item[0].Web_img + "'/>";
    }
		info += "</div>";
	}
  return info;
}

function infoWindowHTML(i, x, marker, arg, collection) {
	var infoWindowHTML = [];
	var infoTabs = [];
	var infoWindow;
	var showMe = arg.item[x];

	if (collection == "Community") {
		infoWindowHTML[0] = "<div class='mapContent'>";
		infoWindowHTML[0] += "<b>" + showMe.Community_fr + "</b> (" + showMe.Population_fr + ")<br/>";
		infoWindowHTML[0] += "<p>" + showMe.Signification_fr + "</p>";
    infoWindowHTML[0] += community_images(arg, showMe);
		infoWindowHTML[0] += "<span>"+ showMe.Latitude + " , " + showMe.Longitude + "</span><br/>";
		infoWindowHTML[0] += "</div>";
		
		if (arg.communities.Id_community != "14" && arg.communities.Id_community != "15") {
			infoWindowHTML[0] += "<div class='divKnowmore'><a href='/fr/Les-Nunavimmiuts/Le-territoire/14-villages-et-1-communaute/" + showMe.Community_fr + "' class='knowmore'>En savoir +</a></div>";
		}
		infoWindow = marker.openInfoWindowHtml(infoWindowHTML[0]);
    
	} else if (collection == "artistes") {
    
		infoWindowHTML[0] = "<div class='mapContent'>";
		for (y = 0; y < arg.item.length; y++) {
			infoWindowHTML[0] += "<p><b>" + arg.item[y].Web_nom_artiste_fr + "</b> (" + arg.item[y].Community_fr + ")<br /><a href='/fr/L-institut/Departements/Museologie/Collection-d-art-inuit-du-Nunavik/Artistes/detail/?id=" + arg.item[y].ID_Artiste + "' class='knowmore'>En savoir +</a></p>";
		}
		infoWindowHTML[0] += "</div>";
		infoWindowHTML[0] += "<div class='divKnowmore'><a href='/fr/L-institut/Departements/Museologie/Collection-d-art-inuit-du-Nunavik/Artistes' class='knowmore'>Voir tous les artistes</a></div>";
		
		infoWindowHTML[1] = "<div class='mapContent'>";
		for (y = 0; y < arg.item.length; y++) {
			infoWindowHTML[1] += "<b>" + arg.item[y].Web_nom_artiste_fr + "</b> (" + arg.item[y].Community_fr + ")<br/>";
			infoWindowHTML[1] += "<p>" + limitCharSize(arg.item[y].Web_biography_en,200) + "<br /><a href='/fr/L-institut/Departements/Museologie/Collection-d-art-inuit-du-Nunavik/Artistes/detail/?id=" + arg.item[y].ID_Artiste + "' class='knowmore'>En savoir +</a></p>";
		}
		infoWindowHTML[1] += "</div>";
		infoWindowHTML[1] += "<div class='divKnowmore'><a href='/fr/L-institut/Departements/Museologie/Collection-d-art-inuit-du-Nunavik/Artistes' class='knowmore'>Voir toutes les biographies</a></div>";
		
		infoWindowHTML[2] = "<div class='mapContent'>";
		infoWindowHTML[2] += "<p><a href='/fr/Les-collections'>Les Collections</a></p>";
		infoWindowHTML[2] += "<p><a href='/fr/Aumaaggiivik/Aumaaggiivik-secretariat-des-arts-du-Nunavik/Art-contemporain'>Base de données des artistes contemporains</a></p>";
		infoWindowHTML[2] += "<p><a href='/fr/L-institut/Departements/Museologie/Collection-d-art-inuit-du-Nunavik/Artistes'>Le département muséologie</a></p>";
		infoWindowHTML[2] += "<p><a href='/fr/L-institut/Departements/Recherche-bibliotheque-archives'>Le département Recherche, bibliothèque et archives</a></p>";
		infoWindowHTML[2] += "</div>";
		
		var infoTabs = [
		  new GInfoWindowTab("Artistes", infoWindowHTML[0]),
		  new GInfoWindowTab("Biographies", infoWindowHTML[1]),
		  new GInfoWindowTab("Liens", infoWindowHTML[2])
		];
		infoWindow = marker.openInfoWindowTabsHtml(infoTabs);
    
	} else if (collection == "objetsarts-Sculptures") {
    
		infoWindowHTML[0] = "<div class='mapContent'>";
		infoWindowHTML[0] += "<b>" + showMe.Category_Web_category + "</b><br/>";
		infoWindowHTML[0] += vignettes_img(arg.item, arg.item[x], null, 'Web_nom_artiste_fr', 'web_sujet_fr');
		infoWindowHTML[0] += "</div>";
		infoWindowHTML[0] += "<div class='divKnowmore'><a href='/fr/Les-collections/Art-et-ethnographie/Sculptures' class='knowmore'>Voir toutes les sculptures</a></div>";
		infoWindow = marker.openInfoWindowHtml(infoWindowHTML[0]);
    
	} else if (collection == "objetsarts-oeuvres") {
    
		infoWindowHTML[0] = "<div class='mapContent'>";
		infoWindowHTML[0] += "<b>" + showMe.Category_Web_category + "</b><br/>";
		infoWindowHTML[0] += vignettes_img(arg.item, arg.item[x], null, 'Web_nom_artiste_fr', 'web_sujet_fr');
		infoWindowHTML[0] += "</div>";
		infoWindowHTML[0] += "<div class='divKnowmore'><a href='/fr/Les-collections/Art-et-ethnographie/Oeuvres-sur-papier' class='knowmore'>Voir toutes les oeuvres sur papier</a></div>";
		infoWindow = marker.openInfoWindowHtml(infoWindowHTML[0]);
    
	} else if (collection == "objetsarts-artifacts") {
    
		infoWindowHTML[0] = "<div class='mapContent'>";
		infoWindowHTML[0] += "<b>" + showMe.Category_Web_category + "</b><br/>";
		var artifact_html_link = 1;
		infoWindowHTML[0] += vignettes_img(arg.item, arg.item[x], artifact_html_link, 'Web_nom_artiste_fr', 'web_sujet_fr');
		infoWindowHTML[0] += "</div>";
		infoWindowHTML[0] += "<div class='divKnowmore'><a href='/fr/Les-collections/Art-et-ethnographie/Artefacts' class='knowmore'>Voir tous les artefacts</a></div>";
		infoWindow = marker.openInfoWindowHtml(infoWindowHTML[0]);

	} else if (collection == "tuumasi") { //dessins
	
		infoWindowHTML[0] = "<div class='mapContent'>";
		infoWindowHTML[0] += "<b>Dessins</b><br/>";
		infoWindowHTML[0] += vignettes_img(arg.item, arg.item[x], null, 'title_fr', 'Credit_fr');
		infoWindowHTML[0] += "</div>";
		infoWindowHTML[0] += "<div class='divKnowmore'><a href='/fr/Les-collections/Bibliotheque-et-archives/Dessins' class='knowmore'>Voir tous les dessins</a></div>";
		infoWindow = marker.openInfoWindowHtml(infoWindowHTML[0]);
    
	} else if (collection == "photo") {
    
		infoWindowHTML[0] = "<div class='mapContent'>";
		infoWindowHTML[0] += "<b>Photos historiques</b><br/>";
		infoWindowHTML[0] += vignettes_img(arg.item, arg.item[x], null, 'Web_description_fr', 'Credit');
		infoWindowHTML[0] += "</div>";
		infoWindowHTML[0] += "<div class='divKnowmore'><a href='/fr/Les-collections/Bibliotheque-et-archives/Photos-historiques' class='knowmore'>Voir toutes les photos historiques</a></div>";
		infoWindow = marker.openInfoWindowHtml(infoWindowHTML[0]);
    
	} else if (collection == "archivesOralesINF") {
    
		infoWindowHTML[0] = "<div class='mapContent'>";
		infoWindowHTML[0] += "<b>Histoires Orales</b><br/>";
    
		if (arg.item.length >= 1 && arg.item[0].ArchivesOralesDOC[0].Web_img_vignette != "") {
			infoWindowHTML[0] += "<div class='picture'>";
			var ran = ranGen(arg.item.length,2);
			for (var i = 0; i < ran.length; i++) {
        infoWindowHTML[0] += '<div class="vignettes-img">';
				infoWindowHTML[0] += "<img border='0' src='http://70.38.68.49/img/" + arg.item[ran[i]].ArchivesOralesDOC[i].Web_img_vignette + "'/>";
    		infoWindowHTML[0] += vignettes_txt(arg.item[ran[i]].ArchivesOrales.Web_description_fonds_fr, arg.item[ran[i]].ArchivesOrales.Credit_fr, true);
        infoWindowHTML[0] += '</div>';
			}
			infoWindowHTML[0] += "</div>";
		} else {
		  infoWindowHTML[0] += vignettes_txt(showMe.ArchivesOrales.Web_description_fonds_fr, showMe.ArchivesOrales.Credit_fr, false);
    }
    
		infoWindowHTML[0] += "</div>";
		infoWindowHTML[0] += "<div class='divKnowmore'><a href='/fr/Les-collections/Bibliotheque-et-archives/Histoires-orales' class='knowmore'>Écouter l’histoire orale</a></div>";
		infoWindow = marker.openInfoWindowHtml(infoWindowHTML[0]);
    
	} else if (collection == "site") { //Sites archéologiques
    
		infoWindowHTML[0] = "<div class='mapContent'>";
		for (y = 0; y < arg.item.length; y++) {
			infoWindowHTML[0] += "<p>" + arg.item[y].Code_Borden + "<br/ ><br /><b>" + arg.item[y].Community_fr + "</b><br/>" + arg.item[y].web_periode_fr + "</p>";
			infoWindowHTML[0] += "<p>" + limitCharSize(arg.item[y].Description_fr,300) + "</p><hr />";
		}
		infoWindowHTML[0] += "</div>";
		infoWindowHTML[0] += "<div class='divKnowmore'><a href='/fr/L-institut/Departements/Archeologie/Ressources-en-ligne/Sites-archeologiques' class='knowmore'>En savoir +</a></div>";
		
		infoWindowHTML[1] = "<div class='mapContent'>";
		for (y = 0; y < arg.item.length; y++) {
			if (arg.item.length >= 1) {
				if (arg.item[y].SitePhoto.length > 0) {
					infoWindowHTML[1] += "<div><img src='http://70.38.68.49/img/" + arg.item[y].SitePhoto[0].Web_img_vignette + "'/><br/>" + arg.item[y].SitePhoto[0].Image_Nom + "</div><hr />";
				}
			}
		}
		infoWindowHTML[1] += "</div>";
		
		infoWindowHTML[2] = "<div class='mapContent'>";
		for (y = 0; y < arg.item.length; y++) {
			if (arg.item.length >= 1) {
				if (arg.item[y].Structure.length > 0) {
					infoWindowHTML[2] += "<div><img src='http://70.38.68.49/img/" + arg.item[y].Structure[0].Web_img_vignette + "'/><br/>" + arg.item[y].Structure[0].Image_Nom + "</div><hr />";
				}
			}
		}
		infoWindowHTML[2] += "</div>";
	
		var infoTabs = [
		  new GInfoWindowTab('Site', infoWindowHTML[0]),
		  new GInfoWindowTab("Photos", infoWindowHTML[1]),
		  new GInfoWindowTab("Structures", infoWindowHTML[2])
		];
		infoWindow = marker.openInfoWindowTabsHtml(infoTabs);
    
	} else if (collection == "artefacts") {
    
		infoWindowHTML[0] = "<div class='mapContent tallpop'>";
		infoWindowHTML[0] += "<b>Artefacts</b><br/>";
		if (arg.item.length >= 1 && arg.item[0].Artefact_PHOTO_A_Artefact_img_vignette_A != "") {
      infoWindowHTML[0] += "<div class='picture'>";
      var ran = ranGen(arg.item.length, 2);
      for (var i = 0; i < ran.length; i++) {
        infoWindowHTML[0] += '<div class="vignettes-img">';
        infoWindowHTML[0] += "<img border='0' src='http://70.38.68.49/img/" + arg.item[ran[i]].Artefact_PHOTO_A_Artefact_img_vignette_A + "'/>";
        infoWindowHTML[0] += vignettes_txt(arg.item[ran[i]].Typologie_Typologie_fr, null, true);
        infoWindowHTML[0] += "</div>";
      }
      infoWindowHTML[0] += "</div>";
    } else {
      infoWindowHTML[0] += vignettes_txt(showMe.Typologie_Typologie_fr, null, false);
    }
		infoWindowHTML[0] += "</div>";
		infoWindowHTML[0] += "<div class='divKnowmore'><a href='/fr/Les-collections/Archeologie/Artefacts/list' class='knowmore'>Voir les artefacts</a></div>";
		infoWindow = marker.openInfoWindowHtml(infoWindowHTML[0]);
    
	} else if (collection == "qajartalik") { //Petroglyphes
    
		infoWindowHTML[0] = "<div class='mapContent'>";
		infoWindowHTML[0] += "<b>Pétroglyphes</b><br/>";
		infoWindowHTML[0] += vignettes_img(arg.item, arg.item[x], null, 'Categorie_Qajartalik_Categorie_fr', null);
		infoWindowHTML[0] += "</div>";
		infoWindowHTML[0] += "<div class='divKnowmore'><a href='/fr/Les-collections/Archeologie/Petroglyphes/list' class='knowmore'>Voir les pétroglyphes</a></div>";
		infoWindow = marker.openInfoWindowHtml(infoWindowHTML[0]);
    
	} else if (collection == "Nunatop-MILIEU_HUMAIN_EQUIPEMENTS_INFRASTRUCTURES" || collection == "Nunatop-MILIEU_RIVERAIN" || collection == "Nunatop-HYDROGRAPHIE" || collection == "Nunatop-PAYSAGE" || collection == "Nunatop-VEGETATION_FAUNE") {
    
		infoWindowHTML[0] = "<div class='mapContent smallpop'>";
		infoWindowHTML[0] += "<b>" + showMe.Name + "</b> (" + showMe.Entity_fr + ")";
		infoWindowHTML[0] += "<p>" + showMe.categories_entites_fr + "</p>";
		infoWindowHTML[0] += "</div>";
//		infoWindowHTML[0] += "<div class='divKnowmore'><a href='/fr/detail/?id=" + showMe. + "' class='knowmore'>En savoir +</a></div>";
		infoWindow = marker.openInfoWindowHtml(infoWindowHTML[0]);
    
	} else {
	
		infoWindowHTML[0] = "<div class='mapContent'>";
		infoWindowHTML[0] += "Nothing";
		infoWindowHTML[0] += "</div>";
//		infoWindowHTML[0] += "<div class='divKnowmore'><a href='/fr/detail/?id=" + showMe. + "' class='knowmore'>En savoir +</a></div>";
		infoWindow = marker.openInfoWindowHtml(infoWindowHTML[0]);
	}
	
	return infoWindow;
}

//create as many values as the range into 'values' then
//return as many as needed into 'ids'.
function ranGen(range, how_many)
{
    if(range < 2)
        return  (new Array())[0] = 0;

    how_many = range < how_many ? range : how_many;

    var values = new Array(how_many);
    for(var xxx=0; xxx < range; xxx++){
        values[xxx] = xxx;
    }

    var ids = new Array();
    for(var xxx=0; xxx < how_many; xxx++){
        var index = Math.round(Math.random() * (values.length-1));
        ids.push(values[index]);
        values.splice(index, 1);
    }

    //if(ids[0] == ids[1])alert("NOT RANDOM");
    return ids;
}

function limitCharSize(text, limit) {
	if (text.length > limit) {
		text = text.substring(0, limit) + "...";
	}
	
	return text;
}

function toogleKML() {
	if ($('#showkml:checked').val() != null) {
		map.addOverlay(geoXml_ubg);
	} else {
		map.removeOverlay(geoXml_ubg);
	}
}

function failureCallback() {
	// we can do something here if there's an error
}

$(document).ready(function() {
	initialize();
	$('#showkml').click(toogleKML);
  map.disableScrollWheelZoom();
  
  // initialy if no map types is selected we force the first.
  if(!$('input[@name=mapTypes]:checked').val()){
    $('input#mapTypes1').attr("checked", true);
  }

  $('input:radio').click(function(e){
	  showMapType($(this));
  });
  
});

