var map, bounds, markers, localSearch, stores, places, bookString; 
function loadMap(bookS) {
	bookString = bookS;
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("mapcontainer"));
		map.addControl(new GLargeMapControl3D());
		bounds = new GLatLngBounds();
		markers = new Array();
		stores = new Array();
		places = new Array();
		localSearch = new GlocalSearch();
	  }

	$("#tabmapview").click(function() {
		$(this).addClass("menutabactive");
		$("#tablistview").removeClass("menutabactive");
		$("#maplistview").hide();
		$("#mapview").show();
		return false;
	});
	
	$("#tablistview").click(function() {
		$(this).addClass("menutabactive");
		$("#tabmapview").removeClass("menutabactive");
		$("#maplistview").show();
		$("#mapview").hide();
		return false;
	});

	$(".zipsearchbutton").click(function() {
		zipSearch();
		return false;
	});

	$($(".zipsearchfield")[0].form).bind("keypress", function(e) {
             if (e.keyCode == 13) {
		zipSearch();
                 return false;
            }
         });
}

function toggleplace(place) {
	if($(place).hasClass("placeactive")) {
		$(place).removeClass("placeactive");
		$(place).parent().find(".placestores").slideUp("slow");
	} else {
		$(place).addClass("placeactive");
		$(place).parent().find(".placestores").css("display", "block").slideDown("slow");
	}
	return false;
}

function centerMap() {
	map.setCenter(bounds.getCenter(), Math.min(10, map.getBoundsZoomLevel(bounds)));
}
			
function addStore(place, address, zipcode, lat, lng, booklink, maplink, storelogo, placeId) {
	if(lng != "" && lat != "") {
		showStore(place, address, zipcode, lat, lng, booklink, maplink);
	}
	var index = addPlace(place, storelogo, placeId);
	stores[index].push(new Array(place, address, zipcode, lat, lng, booklink, maplink));
	
}

function showStore(place, address, zipcode, lat, lng, booklink, maplink) {
	var latlng = new GLatLng(lat, lng);
	var icon = new GIcon();
	icon.image = "/images/2009/Logo_map_blue.png";
	icon.iconSize = new GSize(21, 21);
	icon.iconAnchor = new GPoint(10, 10);
	icon.infoWindowAnchor = new GPoint(-45, 0);
	var marker = new GMarker(latlng, icon);
	
	//listeners
	GEvent.addListener(marker, "click", function() {
		for(i=0; i < markers.length; i++) {
			markers[i].closeInfoWindow();
			markers[i].setImage("/images/2009/Logo_map_blue.png");				
		}
		var window = this.openExtInfoWindow(
        		map,
        		"map_info_window",
        		"<h3>" + place + "</h3><p>" + address + "<br />" + zipcode + "<br /><br /><a href='" + booklink + "'>" + bookString + "</a></p>",
			{beakOffset: 3}
        	);

		marker.setImage("/images/2009/Logo_map_orange.png");
	});
		
	map.addOverlay(marker);
	bounds.extend(latlng);
	markers.push(marker);
}

function showOnMap(lat, lng) {
	$("#tabmapview").addClass("menutabactive");
	$("#tablistview").removeClass("menutabactive");
	$("#maplistview").hide();
	$("#mapview").show();

	map.setZoom(10); 

	for(i=0; i < markers.length; i++) {
		if(markers[i].getLatLng().lat() == lat && markers[i].getLatLng().lng() == lng) {
			GEvent.trigger(markers[i], 'click');
		}
	}	
}

function findPlace(placeId) {
	for(i=0; i < places.length; i++) {
		if(places[i][2] == placeId) {
			return i;
		}
	}
	return -1;
}

function showPlace(index) {
	showPlaces(index);
	
	//to remove infowindow
	GEvent.trigger(map, 'click');

	while(markers.length > 0) {
		map.removeOverlay(markers.pop());				
	}
	
	bounds = new GLatLngBounds();
	if(index == -1) {
		for(index=0; index<stores.length; index++) {
			for(i=0; i<stores[index].length; i++) {
				showStore(stores[index][i][0], stores[index][i][1], stores[index][i][2], stores[index][i][3], stores[index][i][4], stores[index][i][5], stores[index][i][6]);
			}
		}
	}
	else {
		for(i=0; i<stores[index].length; i++) {
			showStore(stores[index][i][0], stores[index][i][1], stores[index][i][2], stores[index][i][3], stores[index][i][4], stores[index][i][5], stores[index][i][6]);
		}
	}

	centerMap();
}

function showPlaces(index) {
	$("#maplistview").find(".placelist").remove();

	if(index == -1) {
		for(index=0; index<stores.length; index++) {
			var clone = $(".placelistclone").clone();
			clone.find(".placeheader").find("span").html(places[index][0]);
			if(places[index][1] != "") {
				clone.find(".placeheader").find("div").css("backgroundImage", "url(" + places[index][1] + ")");
			}
			clone.addClass("placelist").removeClass("placelistclone").appendTo($("#maplistview"));
			for(i=0; i<stores[index].length; i++) {
				var storeclone = clone.find(".placelistitemclone").clone();
				storeclone.find("a:eq(0)").attr('href', stores[index][i][5]);
				storeclone.find("a:eq(1)").attr('href', 'javascript:showOnMap(' + stores[index][i][3] + ',' + stores[index][i][4] + ')');
				storeclone.find("td:eq(1)").html(stores[index][i][1]);
				storeclone.find("td:eq(2)").html(stores[index][i][2]);
				storeclone.addClass("placelistitem").removeClass("placelistitemclone").appendTo(clone.find("tbody"));
			}
		}
		
		$("#partnerdescription").hide();
	}
	else {
		var clone = $(".placelistclone").clone();
		clone.find(".placeheader").find("span").html(places[index][0]);
		if(places[index][1] != "") {
			clone.find(".placeheader").find("div").css("backgroundImage", "url(" + places[index][1] + ")");
		}
		clone.addClass("placelist").removeClass("placelistclone").appendTo($("#maplistview"));
		for(i=0; i<stores[index].length; i++) {
			var storeclone = clone.find(".placelistitemclone").clone();
			storeclone.find("a:eq(0)").attr('href', stores[index][i][5]);
			storeclone.find("a:eq(1)").attr('href', 'javascript:showOnMap(' + stores[index][i][3] + ',' + stores[index][i][4] + ')');
			storeclone.find("td:eq(1)").html(stores[index][i][1]);
			storeclone.find("td:eq(2)").html(stores[index][i][2]);
			storeclone.addClass("placelistitem").removeClass("placelistitemclone").appendTo(clone.find("tbody"));
		}
		
		toggleplace(clone.find(".placeheader"));
		$("#partnerdescription").find(".partneritem").hide();
		$("#partnerdescription").find(".partneritem:eq(" + index + ")").show();
		$("#partnerdescription").show();
	}
}

function addPlace(place, storelogo, placeId) {
	for(i=0; i<places.length; i++) {
		if(places[i][0] == place) {
			return i;
		}
	}
	
	places.push(new Array(place, storelogo, placeId));
	stores.push(new Array());
	$(".mapselectlist").append("<option value='" + (places.length-1) + "'>" + place + "</option>");

	return (places.length-1);
}

function sortByDistance(a, b) {
	if(a[1]>b[1]) return 1;
	else if(a[1]<b[1]) return -1;
	return 0;
}

function zipSearch() {
	var postcode = $(".zipsearchfield").attr("value");
	localSearch.setSearchCompleteCallback(null, 
		function() {		
			if (localSearch.results[0]) {
				//to remove infowindow
				$("#tabmapview").click();
				GEvent.trigger(map, 'click');	
				var resultLat = localSearch.results[0].lat;
				var resultLng = localSearch.results[0].lng;
				var point = new GLatLng(resultLat,resultLng);
				

				var nearestStores = new Array();
				var miles;
				for(var i=0; i < markers.length; i++) {
					miles = parseInt((point.distanceFrom(markers[i].getPoint()) / 1000));
					nearestStores.push(new Array(markers[i], miles));
				}
				
				nearestStores.sort(sortByDistance);
				map.setCenter(nearestStores[0][0].getPoint(), 10)
				GEvent.trigger(nearestStores[0][0], 'click');
				
			} else{
				alert("Postnummeret kunde ikke findes");
			}
		});	
	var language = "DK";
	if($(".langse").hasClass(".langseactive")) {
		language = "SE";
	}
	localSearch.execute(postcode + ", " + language);
	return false;
}
