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/en/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("No results found.");
		}
	});
}


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/en/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="/en/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_en + "</b> (" + showMe.Population_en + ")<br/>";
		infoWindowHTML[0] += "<p>" + showMe.Signification_en + "</p>";
    infoWindowHTML[0] += community_images(arg, showMe);
		infoWindowHTML[0] += "<span>"+ showMe.Latitude + " , " + showMe.Longitude + "</span><br/>";
		infoWindowHTML[0] += "</div>";

		if (showMe.Id_community != "14" && showMe.Id_community != "15") {
			infoWindowHTML[0] += "<div class='divKnowmore'><a href='/en/Les-Nunavimmiuts/Le-territoire/14-villages-et-1-communaute/" + showMe.Community_en + "' class='knowmore'>More information</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_en + "</b> (" + arg.item[y].Community_en + ")<br /><a href='/en/L-institut/Departements/Museologie/Collection-d-art-inuit-du-Nunavik/Artistes/detail/?id=" + arg.item[y].ID_Artiste + "' class='knowmore'>More information</a></p>";
		}
		infoWindowHTML[0] += "</div>";
		infoWindowHTML[0] += "<div class='divKnowmore'><a href='/en/L-institut/Departements/Museologie/Collection-d-art-inuit-du-Nunavik/Artistes' class='knowmore'>View all artists</a></div>";
		
		infoWindowHTML[1] = "<div class='mapContent'>";
		for (y = 0; y < arg.item.length; y++) {
			infoWindowHTML[1] += "<b>" + arg.item[y].Web_nom_artiste_en + "</b> (" + arg.item[y].Community_en + ")<br/>";
			infoWindowHTML[1] += "<p>" + limitCharSize(arg.item[y].Web_biography_en,200) + "<br /><a href='/en/L-institut/Departements/Museologie/Collection-d-art-inuit-du-Nunavik/Artistes/detail/?id=" + arg.item[y].ID_Artiste + "' class='knowmore'>More information</a></p>";	
		}
		infoWindowHTML[1] += "</div>";
		infoWindowHTML[1] += "<div class='divKnowmore'><a href='/en/L-institut/Departements/Museologie/Collection-d-art-inuit-du-Nunavik/Artistes' class='knowmore'>View all biographies</a></div>";
		
		infoWindowHTML[2] = "<div class='mapContent'>";
		infoWindowHTML[2] += "<p><a href='/en/Les-collections'>Collections</a></p>";
		infoWindowHTML[2] += "<p><a href='/en/Aumaaggiivik/Aumaaggiivik-secretariat-des-arts-du-Nunavik/Art-contemporain'>Database of current artists</a></p>";
		infoWindowHTML[2] += "<p><a href='/en/L-institut/Departements/Museologie/Collection-d-art-inuit-du-Nunavik/Artistes'>Department of museology</a></p>";
		infoWindowHTML[2] += "<p><a href='/en/L-institut/Departements/Recherche-bibliotheque-archives'>Research, Library & Archives</a></p>";
		infoWindowHTML[2] += "</div>";
		
		var infoTabs = [
		  new GInfoWindowTab("Artists", infoWindowHTML[0]),
		  new GInfoWindowTab("Biographies", infoWindowHTML[1]),
		  new GInfoWindowTab("Links", 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_en', 'web_sujet_en');
		infoWindowHTML[0] += "</div>";
		infoWindowHTML[0] += "<div class='divKnowmore'><a href='/en/Les-collections/Art-et-ethnographie/Sculptures' class='knowmore'>View sculptures</a></div>";
		infoWindow = marker.openInfoWindowHtml(infoWindowHTML[0]);
    
	} else if (collection == "objetsarts-oeuvres") {

		infoWindowHTML[0] = "<div class='mapContent'>";
		infoWindowHTML[0] += "<b>Works on paper</b><br/>";
    infoWindowHTML[0] += vignettes_img(arg.item, arg.item[x], null, 'Web_nom_artiste_en', 'web_sujet_en');
		infoWindowHTML[0] += "</div>";
		infoWindowHTML[0] += "<div class='divKnowmore'><a href='/en/Les-collections/Art-et-ethnographie/Oeuvres-sur-papier' class='knowmore'>View works on paper</a></div>";
		infoWindow = marker.openInfoWindowHtml(infoWindowHTML[0]);
    
	} else if (collection == "objetsarts-artifacts") {
		
    infoWindowHTML[0] = "<div class='mapContent'>";
		infoWindowHTML[0] += "<b>Artifacts</b><br/>";
    var artifact_html_link = "<a href='/en/Les-collections/Art-et-ethnographie/Artefacts/detail/?id=" + showMe.ID_NIAC + "' class='knowmore'>";
		infoWindowHTML[0] += vignettes_img(arg.item, arg.item[x], artifact_html_link, 'Web_nom_artiste_en', 'web_sujet_en');
		infoWindowHTML[0] += "</div>";
		infoWindowHTML[0] += "<div class='divKnowmore'><a href='/en/Les-collections/Art-et-ethnographie/Artefacts' class='knowmore'>View artifacts</a></div>";
		infoWindow = marker.openInfoWindowHtml(infoWindowHTML[0]);

	} else if (collection == "tuumasi") { //DESSINS

		infoWindowHTML[0] = "<div class='mapContent'>";
		infoWindowHTML[0] += "<b>Drawings</b><br/>";
		infoWindowHTML[0] += vignettes_img(arg.item, arg.item[x], null, 'title_en', 'Credit_en');
		infoWindowHTML[0] += "</div>";
		infoWindowHTML[0] += "<div class='divKnowmore'><a href='/en/Les-collections/Bibliotheque-et-archives/Dessins' class='knowmore'>View drawings</a></div>";
		infoWindow = marker.openInfoWindowHtml(infoWindowHTML[0]);
    
	} else if (collection == "photo") { //Photos historiques

		infoWindowHTML[0] = "<div class='mapContent'>";
		infoWindowHTML[0] += "<b>Historical photos</b><br/>";
		infoWindowHTML[0] += vignettes_img(arg.item, arg.item[x], null, 'Web_description_en', 'Credit');
		infoWindowHTML[0] += "</div>";
		infoWindowHTML[0] += "<div class='divKnowmore'><a href='/en/Les-collections/Bibliotheque-et-archives/Photos-historiques' class='knowmore'>View historic photos</a></div>";
		infoWindow = marker.openInfoWindowHtml(infoWindowHTML[0]);
    
	} else if (collection == "archivesOralesINF") {

		infoWindowHTML[0] = "<div class='mapContent'>";
		infoWindowHTML[0] += "<b>Oral histories</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_en, arg.item[ran[i]].ArchivesOrales.Credit_en, true);
        infoWindowHTML[0] += "</div>";
			}
			infoWindowHTML[0] += "</div>";
		}else{
		  infoWindowHTML[0] += vignettes_txt(showMe.ArchivesOrales.Web_description_fonds_en, showMe.ArchivesOrales.Credit_en, false);
    }
    
		infoWindowHTML[0] += "</div>";
		infoWindowHTML[0] += "<div class='divKnowmore'><a href='/en/Les-collections/Bibliotheque-et-archives/Histoires-orales' class='knowmore'>Listen to oral history</a></div>";
		infoWindow = marker.openInfoWindowHtml(infoWindowHTML[0]);

	} else if (collection == "site") {
    
		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_en + "</b><br/>" + arg.item[y].web_periode_en + "</p>";
			infoWindowHTML[0] += "<p>" + limitCharSize(arg.item[y].Description_en,300) + "</p><hr />";
		}
		infoWindowHTML[0] += "</div>";
		infoWindowHTML[0] += "<div class='divKnowmore'><a href='/en/L-institut/Departements/Archeologie/Ressources-en-ligne/Sites-archeologiques' class='knowmore'>More information</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>Artifacts</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_en, null, true);
        infoWindowHTML[0] += '</div>';
			}
			infoWindowHTML[0] += "</div>";
		}else{
		  infoWindowHTML[0] += vignettes_txt(showMe.Typologie_Typologie_en, null, false);
    }
    
		infoWindowHTML[0] += "</div>";
		infoWindowHTML[0] += "<div class='divKnowmore'><a href='/en/Les-collections/Archeologie/Artefacts/list' class='knowmore'>View all artifacts</a></div>";
		infoWindow = marker.openInfoWindowHtml(infoWindowHTML[0]);

	} else if (collection == "qajartalik") { //Petroglyphes

		infoWindowHTML[0] = "<div class='mapContent'>";
		infoWindowHTML[0] += "<b>Petroglyphes</b><br/>";
		infoWindowHTML[0] += vignettes_img(arg.item, arg.item[x], null, 'Categorie_Qajartalik_Categorie_en', null);
		infoWindowHTML[0] += "</div>";
		infoWindowHTML[0] += "<div class='divKnowmore'><a href='/en/Les-collections/Archeologie/Petroglyphes/list' class='knowmore'>View all petroglyphs</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_en + ")";
		infoWindowHTML[0] += "<p>" + showMe.categories_entites_en + "</p>";
		infoWindowHTML[0] += "</div>";
//		infoWindowHTML[0] += "<div class='divKnowmore'><a href='/en/detail/?id=" + showMe. + "' class='knowmore'>More information</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='/en/detail/?id=" + showMe. + "' class='knowmore'>More information</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));
  });
  
});

