/******************************************************************************
 * File Name: index.js
 * Purpose: Javascript code for maps main page
 * Author: C.Bateman
 * Date Created: 28.Oct.2008
 * Revision History:
 * Date:		Modified By:	Description:
 *
 *****************************************************************************/
 

 // Main map variables
var map;
var markerController;
var markerclusterer;
var progressBar;
var geocoder;
var sDate;
var eDate;

//overlays
var overlays;
var sliderPosition = 100;
var col = "GermanyMaps";
var overlaysInitialized = false;


$(document).ready(function(){
	if (!GBrowserIsCompatible()) {
		window.location = "help/";
	}
	
	// Initialize Google Map
	map = new GMap2(document.getElementById("gmap"));
	map.addControl(new GLargeMapControl3D());
	map.addControl(new GHierarchicalMapTypeControl());
	map.addControl(new GOverviewMapControl(new GSize(120,110)));
	map.enableScrollWheelZoom();
	map.addMapType(G_PHYSICAL_MAP);
	map.setMapType(G_PHYSICAL_MAP);
	map.setCenter(new GLatLng(39.5,-107), 5);
	
	// Sets copyright into Google Maps
	var gcr = GMapType.prototype.getCopyrights;
	GMapType.prototype.getCopyrights = function(bounds,zoom) {
		return ["Overlays &copy;" + $("#year").val() + " BYU"].concat(gcr.call(this,bounds,zoom));
	}
	
	
	
	// Ensure that all collection checkboxes are appropriately checked (fixes funny results on soft refreshes)
	$("#colList div.checkbox:not(.checked)").siblings("input:checkbox").attr("checked", false);
	$("#germanyList :checkbox").attr("checked", false);
	
	// goto params
	var gotoId = $("#gotoId").val();
	var gotoPoint = $("#gotoPoint").val();
	var gotoCisoroot = $("#gotoCisoroot").val();
	
	// Update selected collections based on previously set cookie
	if (gotoPoint == '' && gotoId == '' && gotoCisoroot == '') {
		if ($.cookie("collections") != null && $.cookie("collections") != '') {
			var cookieArray = $.cookie("collections").split(";");
			for (i in cookieArray) {
				$("#colList input[value='"+cookieArray[i]+"']").siblings("div.checkbox").addClass("checked");
				$("#colList input[value='"+cookieArray[i]+"']").attr("checked", true);
			}
			$("#colCountLabel").html("("+cookieArray.length+" selected)");
		} else {
			$("#colCountLabel").html("(0 selected)");
		}
	}
	
	// Initializes markerController, loads markers from 'markerData.php'
	markerController = new markerController("markerController", map); // (name of instance, GMap object)
	loadJsMarkers();
	
	
	
	// Initializes geocoder - used for 'go to location'
	geocoder = new GClientGeocoder();
	
	// Refreshes the map when the window is resized
	$(window).resize(function(){
		map.checkResize();
	});
	
	// Shadowbox init
	var options = {
		handleOversize:	'resize'
	};
	Shadowbox.init(options);
	
	
	// Initialize checkboxes
	$("div.checkbox").click(function() {
		if ($(this).hasClass("checked")) {
			$(this).siblings(":checkbox").attr("checked","");
			$(this).removeClass("checked")
		} else {
			$(this).siblings(":checkbox").attr("checked","checked");
			$(this).addClass("checked");
		}
	});
	
	
	
	
	// clicking label = clicking checkbox
	$("ul.checkTree li label").click(function() {
		$(this).siblings("div.checkbox").click();
	});
	
	
	// Initialize dates
	sDate = parseInt($("#startLabel").text());
	eDate = parseInt($("#endLabel").text());
	
	$("#dateStartSelect").change(function() {
		sDate = $(this).val();
		markerController.parse(true, false, true);
	});
	
	$("#dateEndSelect").change(function() {
		eDate = $(this).val();
		markerController.parse(true, false, true);
	});
	
	
	// update map when a collection is selected or removed
	$("#colList div.checkbox").click(function() {
		var colCount = $("#colList input:checked").length;
		if (colCount == 0 ) {
			markerController.parse(true, true, true);
			markerController.parseActive = false;
		} else  {
			markerController.parseActive = true;
			markerController.parse(true, true, true);
		}
		$("#colBar div.caption").css("color","");
		
		var count = colCount + $("#germanyList input:checked").length;
		$("#colCountLabel").html("("+count+" selected)");
		
	});
	
	
	// When the Germany Maps checkbox is clicked, check if they have already been initialized.
	// If not, load deferred javascript and initialize the overlays class.
	$("#germanyList div.checkbox").click(function() {
		var checkbox = $(this);
		if (!overlaysInitialized) {
			$("#loading").show();
			
			overlays = new Overlays(map, col);
			$.getScript("overlayData.php", function() { // Load and initialize overlay data
				overlaysInitialized = true;
				
				if ($(checkbox).siblings(":checkbox").attr("checked") == true) {
					overlays.activate();
					markerController.map.setCenter(new GLatLng(51.5,12.3), 6);
				} else {
					overlays.deactivate();
				}
				$("#loading").hide();
			});
		} else {
			if ($(checkbox).siblings(":checkbox").attr("checked") == true) {
				overlays.activate();
			} else {
				overlays.deactivate();
			}
		}
		$("#colBar div.caption").css("color","");
		
		var count = $("#colList input:checked").length + $("#germanyList input:checked").length;
		$("#colCountLabel").html("("+count+" selected)");
		
	});
	
	// Initializes the opacity slider
	$("#opacitySlider").slider({
		range:	"min",
		value:	100,
		min:	0,
		max:	100,
		slide:	function(event, ui) {
			sliderPosition = ui.value;
			changeOpacity(sliderPosition);
		}
	});
	
	
	// Dropdown collections menu
	$("#colBar").click(function(e) {
		var tgt = $(e.target);
		if (tgt.is("#colBar") || tgt.is("#colDrop") || tgt.is("img") || tgt.is("#colCountLabel")) {
			$("#colDropDiv").slideToggle(100);
		}
	});
	
	var slideTimer;
	$("#colBar").mouseleave(function() {
		slideTimer = setTimeout(function() {
			sliding = true; 
			$("#colDropDiv").slideUp(200, function() {
				sliding = false;
			});
		}, 300);
	});
	$("#colBar").mouseenter(function() {
		clearTimeout(slideTimer);
	});

	
	
	// Update the map
	if ((gotoPoint == '' || gotoId == '') && gotoCisoroot != 'GermanyMaps') {
		markerController.parse(true, false, true);
	} else if (gotoPoint == 1) {
		if (gotoId !== '' && gotoPoint == 1) {
			markerController.parse(true,true,true, function() {
				markerController.parseActive = false;
				markerController.popUp(gotoId, '', function() {
					setTimeout(function() {
						map.setZoom(15);
						markerController.parseActive = true;
						markerController.parse(false,false,false);
					},0);
					
				});
			});
		}
	} else if (gotoCisoroot == "GermanyMaps") {
		overlays = new Overlays(map, col);
		if (gotoId != '') {
			$.getScript("overlayData.php", function() { // Load and initialize overlay data
				overlaysInitialized = true;
				overlays.activate();
				if (gotoId != '') {
					overlays.changeOverlay(gotoId,false);
				}
				overlays.superOverlay.hide();
				
				$("#loading").hide();
				
				$("#germanyList div.checkbox").addClass("checked").siblings(":checkbox").attr("checked","checked");;
			});
		} else {
			$("#germanyList div.checkbox").click();
		}
	}
	
}); // End $(document).ready



	
function searchForm() {
	markerController.parse(true, false, true); // get new list
	
	if ($("#search").val() != '') {
		$("#clearSearch").show();
	} else {
		$("#clearSearch").hide();
	}
	
	// Omniture
	var s=s_gi("byuhbll");
	s.linkTrackVars="None";
	s.linkTrackEvents="None";
	s.tl(true, "o", "Mappify: search=" + $("#search").val());
}



// Called when "X button" in search box is pressed
function clearSearch() {
	$("#search").val('');
	$("#clearSearch").hide();
	
	markerController.parse(true,false,true);
	
}


// Generate tooltips for all items in the list pane
function listTooltips() {
	$("#searchList li").tooltip({
		delay:		0,
		track:		true,
		showURL:	false,
		bodyHandler: function() {
			var id = $(this).attr("id");
			return $("<img id='tooltipImg'/>").attr("src", markerController.getMarkerThumb(id));
		}
	});
}

// This function is called when a cluster window is viewed, and sets image tooltips for each marker in the cluster
function clusterWindowTooltip() {
	$("div.clusterWindow li").tooltip({
		delay:		0,
		track:		true,
		showURL:	false,
		bodyHandler: function() {
			var id = $(this).attr("id");
			return $("<img id='tooltipImg' />").attr("src", markerController.getMarkerThumb(id));
		}
	});
}



// This function is necessary to use shadowbox in infoWindows
function showShadowbox(a) {
	Shadowbox.open(a);
	a.blur();
	return false;
};



// Called when "Go to location" is searched.
// Moves map to the location returned by the geocoder.
// Zoom is set based on the accuracy level of the response.
/*
ACCURACY LEVELS
0	unknown
1	country
2	region (state, province)
3	sub-region (county, municipality)
4	town (city, village)
5	post code (zip code)
6	street 
7	intersection
8	address
9	premise
*/
function showAddress(address) {
	if (address == "") {
		return;
	}
	geocoder.getLocations(address + ", europe", function(response) {
		if (!response || response.Status.code != 200) {
			// FAILED
		} else {
			place = response.Placemark[0];
			point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
			accuracy = place.AddressDetails.Accuracy;
			var zoom = null;
			if (accuracy != 0) {
				if (accuracy < 2) {
					zoom = accuracy + 4;
				} else if (accuracy == 2) {
					zoom = 7;
				} else if (accuracy == 3) {
					zoom = 10;
				} else {
					zoom = accuracy + 8;
				}
				if (zoom > 15) zoom = 15;
				map.setCenter(point,zoom);
				$("#germanyVerbiage").fadeOut();
			}
		}
		
		if (overlaysInitialized && overlays.active) {
			backToOutlines();
		}
	});
}



// OVERLAYS FUNCTIONS

// Called when an arrow is clicked
function slide(dir) {
	overlays.slide(dir);
}

// Called as the opacity slider changes.  Set the opacity of map overlays.
function changeOpacity(val) {
	val = val/100
	$("div.gmnoprint > img").css("opacity", val);
}

function backToOutlines() {
	overlays.backToOutlines();
}

// Called when the collection is changed
function changeCol(selCol) {
	col = collections[selCol];
	top.location = "overlays.php?col=" + col;
}


