var bounds, markers, localSearch, stores, places, bookString; 

function loadMap(bookS) {
	bookString = bookS;
// 56.206704,10.689697 
	mapUtils.initialize('mapcontainer','56.331766','10.69519');
	markers = new Array();
	stores = new Array();
	places = new Array();
	geocoder = new google.maps.Geocoder();
	
  // Initialize the local searcher

	/*
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("mapcontainer"));
		map.addControl(new GLargeMapControl3D());
		map.setMapType(G_PHYSICAL_MAP); 
		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();	
		$("#viewtxt").html($("#txtMapview").html());		
		return false;
	});
	
	$("#tablistview").click(function() {
		$(this).addClass("menutabactive");
		$("#tabmapview").removeClass("menutabactive");
		$("#maplistview").show();
		$("#mapview").hide();
		$("#viewtxt").html($("#txtListview").html());	
		return false;
	});


	$(".zipsearchfield").focus(function(){
		if($(".zipsearchfield").val() == $("#txtPostnummerElleBy").html())
		{
			$(".zipsearchfield").val("");
		}	
	});

	$(".zipsearchbutton_new").click(function() {
		if($(".zipsearchfield").val() != "" && $(".zipsearchfield").val() != $("#txtPostnummerElleBy").html())
		{
			zipSearch();
			return false;
		}
	});

	$($(".zipsearchfield")[0].form).bind("keypress", function(e) {
            if (e.keyCode == 13 && $(".zipsearchfield").val() != "" && $(".zipsearchfield").val() != $("#txtPostnummerElleBy").html()) 
			{
				zipSearch();
                return false;
            }
     });
}

function doSearch() {
    var address = "";
	var postcode = $(".zipsearchfield").attr("value");

	if(isNaN(postcode) == false)
	{
		// Number typed in
		if(postcode.length != 4)
		{
			alert($("#txtUgyldigPostnr").html());
			return false;
		}
		if(postcode >= 1000 && postcode <= 1999)
		{
			postcode = 2400;
		}
		address = "Danmark " + postcode;
	} else {
		// Text typed in
		address = "Danmark " + postcode;
	}

	geocoder.geocode( { 'address': address}, function(results, status) {
	  if (status == google.maps.GeocoderStatus.OK) 
	  {
		map.setCenter(results[0].geometry.location);
		map.setZoom(11);
	  } else {
		alert("Adressen kunne ikke findes, prøv igen");
	  }
	});
}

function updateLokationList()
{
	if($(".zipsearchfield").attr("value") != "" && $(".zipsearchfield").val() != $("#txtPostnummerElleBy").html())
	{
		var resultArray = new Array();
		var visibleBounds = map.getBounds();
		var visibleZoomedBounds = map.getBounds();
		
		for(var i = 0; i < markers.length; i++) 
		{
			if (visibleZoomedBounds.containsLatLng(markers[i].getLatLng())) {
				resultArray.push(markers[i].getLatLng().lat());
			}
		}
		//to remove infowindow
		GEvent.trigger(map, 'click');

		displayZipResult(resultArray);	
	}
}
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 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 myLatlng = new google.maps.LatLng(initAtLat,initAtLong);
	var latlng = new google.maps.LatLng(lat,lng);
	//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);
	*/
  var image = new google.maps.MarkerImage('/images/2009/Logo_map_blue.png',
      // This marker is 20 pixels wide by 32 pixels tall.
      new google.maps.Size(21, 21),
      // The origin for this image is 0,0.
      new google.maps.Point(0,0),
      // The anchor for this image is the base of the flagpole at 0,32.
      new google.maps.Point(0, 21));


	var marker = new google.maps.Marker({
		position: latlng, 
		map: map,
        icon: image,
		title:"Se detaljer",
        visible: true
	});

	var getSRC = $("#btnGoogleBook").html();
	var contentString = "<h3>" + place + "</h3><p>" + address + "<br />" + zipcode + "<br /><br /><a href='" + maplink + "'class=\"googleboxLink\" target=\"_blank\" onfocus=\"this.blur();\">" + $("#txtHentRute").html() + "</a><br /><a href='javascript:updateLokationList()' class=\"googleboxLink\" onfocus=\"this.blur();\">" + $("#txtSoegNear").html() + "</a><br /><a href='" + booklink + "' class=\"googleboxLinkBook\" onfocus=\"this.blur();\"><img src=\"" + getSRC + "\" alt=\"Book\" class=\"gMapBookKnap\" /></a><br /></p>";
	//listeners			
	var myOptions = {
			 content: '<div id="map_info_window" style="overflow:hidden;width:200px"><div id="map_info_window_t">&nbsp;</div><div id="map_info_window_contents" style="margin-left:0px">' + contentString + '</div><div id="map_info_window_b">&nbsp;</div></div>'
			,disableAutoPan: false
			,maxWidth: 0
			,pixelOffset: new google.maps.Size(-215, -250)
			,zIndex: null
			,boxStyle: { 
			  background: "transparent url() no-repeat"
			  ,width: "200px"
			 }
			,closeBoxMargin: "-2000px 0 0 0"
			,closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif"
			,infoBoxClearance: new google.maps.Size(1, 1)
			,isHidden: false
			,pane: "floatPane"
			,enableEventPropagation: false
	};

	var ib = new InfoBox(myOptions);

	google.maps.event.addListener(marker, 'click', function() {
		//ib.close();
		$('#map_info_window').remove();
		ib.open(map, marker);
	});
	/* WORKING
	google.maps.event.addListener(marker, 'click', function() {
		infowindow.close();
		infowindow.setContent("<div class=\"infoWindowContent\"><h3>" + place + "</h3><p>" + address + "<br />" + zipcode + "<br /><br /><a href='" + maplink + "'class=\"googleboxLink\" target=\"_blank\" onfocus=\"this.blur();\">" + $("#txtHentRute").html() + "</a><br /><a href='javascript:updateLokationList()' class=\"googleboxLink\" onfocus=\"this.blur();\">" + $("#txtSoegNear").html() + "</a><br /><a href='" + booklink + "' class=\"googleboxLinkBook\" onfocus=\"this.blur();\"><img src=\"" + getSRC + "\" alt=\"Book\" class=\"gMapBookKnap\" /></a><br /></p></div>");
		infowindow.open(map,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) {
	$('#map_info_window').remove();
	$('#zipSearchResultFrame').hide();

	showPlaces(index);

	$('#lbl_outputSearchType').html(" på");
	$('#selectDisplayArea').html(": " + $('#mapselectlist').find(':selected').text());

	// Remove all marker from the map
    for (i in markers) {
      markers[i].setMap(null);
    }


	bounds = new google.maps.LatLngBounds();
	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]);
		}
		
		var myLatlng = new google.maps.LatLng(stores[index][0][3], stores[index][0][4]);
		map.setCenter(myLatlng);
	}
}

function showPlaces(index) {
	$("#maplistview").find(".placelist_new").remove();

	if(index == -1) {
	// Show full map
		$('#mapcontainer').css('height','506px');
		$('.mapcontainerbordertop_new').css('top','-506px');

		for(index=0; index<stores.length; index++) {
			var clone = $(".placelistclone").clone();
			clone.find(".placeheader_new").find("span").html(places[index][0]);
			if(places[index][1] != "") {
				clone.find(".placeheader_new").find("div").css("backgroundImage", "url(" + places[index][1] + ")");
			}
			if(index == 0) {
				clone.addClass("placelist_new").removeClass("placelistclone");	
				clone.css("border-top", "1px solid #b0b0b0").appendTo($("#maplistview"));	
			} else {
				clone.addClass("placelist_new").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', 'javascript:showOnMap(' + stores[index][i][3] + ',' + stores[index][i][4] + ')');
				storeclone.find("a:eq(1)").attr('href', stores[index][i][5]);
				storeclone.find("td:eq(0)").html(stores[index][i][1]);
				storeclone.find("td:eq(1)").html(stores[index][i][2]);
				storeclone.addClass("placelistitem").removeClass("placelistitemclone").appendTo(clone.find("tbody"));
			}
		}		
		$("#partnerdescription").hide();
	}
	else 
	{
	// Show selected
		$('#mapcontainer').css('height','324px');
		$('.mapcontainerbordertop_new').css('top','-324px');
		var clone = $(".placelistclone").clone();
		clone.find(".placeheader_new").find("span").html(places[index][0]);
		if(places[index][1] != "") {
			clone.find(".placeheader_new").find("div").css("backgroundImage", "url(" + places[index][1] + ")");
		}
		clone.addClass("placelist_new").removeClass("placelistclone");	
		clone.css("border-top", "1px solid #b0b0b0").appendTo($("#maplistview"));
		for(i=0; i<stores[index].length; i++) {
			var storeclone = clone.find(".placelistitemclone").clone();
			storeclone.find("a:eq(0)").attr('href', 'javascript:showOnMap(' + stores[index][i][3] + ',' + stores[index][i][4] + ')');
			storeclone.find("a:eq(1)").attr('href', stores[index][i][5]);
			storeclone.find("td:eq(0)").html(stores[index][i][1]);
			storeclone.find("td:eq(1)").html(stores[index][i][2]);
			storeclone.addClass("placelistitem").removeClass("placelistitemclone").appendTo(clone.find("tbody"));
		}
		
		toggleplace(clone.find(".placeheader_new"));
		$("#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 closeAdressBox()
{
	$('#zipSearchResultFrame').hide();
}

function displayZipResult(resultArray)
{
	//alert(resultArray);
	var getResult = "<div>Afhentningssteder i nærheden af din valgte destination</div>";
	var loopI = 0;
	for(index=0; index<stores.length; index++) {
		for(i=0; i<stores[index].length; i++) {
			for(y=0; y<resultArray.length; y++) {
				if(stores[index][i][3] == resultArray[y])
				{
					if(loopI < 4)
					{	
						getResult +=  "<div><b>" + stores[index][i][0] + "</b>, <span class=\"zipAdr\">" + stores[index][i][1] + "</span><br />» <a href=\"" + stores[index][i][5] + "\" onfocus=\"this.blur();\">Book nu</a><br /></div>";
						loopI++;
						if(loopI == 4)
						{
							getResult +=  "Der kan ikke vises flere på listen, begræns evt. dit søgeområde.";
						}
					}
				}	
			}
		}
	}
	getResult +=  "<div id=\"closeWinLink\"><a href=\"javascript:closeAdressBox();\" onfocus=\"this.blur();\" title=\"Luk vindue\"><b>X</b></a><br /></div>";
	$('#zipSearchResultFrame').show();
	$('#zipSearchResultMidt').html(getResult);
}
function displayListviewResult(resultArray)
{
		$("#maplistview").find(".placelist_new").remove();
		var currentElement;
		var loopI = 0;
		for(index=0; index<stores.length; index++) {
			for(i=0; i<stores[index].length; i++) {
				for(y=0; y<resultArray.length; y++) {
					if(stores[index][i][3] == resultArray[y])
					{		
						var nameElm = stores[index][i][0].split(" ");
						if(currentElement == nameElm[0])
						{
							var storeclone = clone.find(".placelistitemclone").clone();
							storeclone.find("a:eq(0)").attr("href", "javascript:showOnMap(" + stores[index][i][3] + "," + stores[index][i][4] + ")");
							storeclone.find("a:eq(1)").attr("href", stores[index][i][5]);
							storeclone.find("td:eq(0)").html(stores[index][i][1]);
							storeclone.find("td:eq(1)").html(stores[index][i][2]);
							storeclone.addClass("placelistitem").removeClass("placelistitemclone").appendTo(clone.find("tbody"));	

							currentElement = nameElm[0];
						} else {
							var clone = $(".placelistclone").clone(); 

							if(nameElm[0] == "City" || nameElm[0] == "Dit" || nameElm[0] == "Pelican")
							{
								clone.find(".placeheader_new").find("span").html(nameElm[0]+" "+nameElm[1]);
							} else {
								clone.find(".placeheader_new").find("span").html(nameElm[0]);
							}

							if(loopI==0)
							{
								clone.find(".placeheader_new").css("border-top", "1px solid #b0b0b0");
							}

							if(places[index][1] != "") {
								clone.find(".placeheader_new").find("div").css("backgroundImage", "url(" + places[index][1] + ")");
							}
							if(index == 0) {
								clone.addClass("placelist_new").removeClass("placelistclone").appendTo($("#maplistview"));		
							} else {
								clone.addClass("placelist_new").removeClass("placelistclone").appendTo($("#maplistview"));	
							}

							var storeclone = clone.find(".placelistitemclone").clone();
							storeclone.find("a:eq(0)").attr("href", "javascript:showOnMap(" + stores[index][i][3] + "," + stores[index][i][4] + ")");
							storeclone.find("a:eq(1)").attr("href", stores[index][i][5]);
							storeclone.find("td:eq(0)").html(stores[index][i][1]);
							storeclone.find("td:eq(1)").html(stores[index][i][2]);
							storeclone.addClass("placelistitem").removeClass("placelistitemclone").appendTo(clone.find("tbody"));	
							
							var getClone = clone.find(".placeheader_new");
							//$("#partnerdescription").find(".partneritem").hide();
							//$("#partnerdescription").find(".partneritem:eq(" + index + ")").show();
							//$("#partnerdescription").show();
							
							$(getClone).addClass("placeactive");
							$(getClone).parent().find(".placestores").css("display", "block").slideDown("slow");

							currentElement = nameElm[0];
						}

						loopI++;						
					}
				}
			}
		}
}

function zipSearch() {
	doSearch();

	displayListviewResult(resultArray);
	displayZipResult(resultArray);
	/*
	var postcode = $(".zipsearchfield").attr("value");
	var searchType = "";
	if(isNaN(postcode) == false)
	{
		// Number typed in
		if(postcode.length != 4)
		{
			alert($("#txtUgyldigPostnr").html());
			return false;
		}
		if(postcode >= 1000 && postcode <= 1999)
		{
			postcode = 2400;
		}
		searchType = " " + $("#txtVedPostnrSog").html();
	} else {
		// Text typed in
		searchType = " " + $("#txtVedTxtSog").html();
	}
	
	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));
				}

			// IE 8 Bug workaround: start
				var listViewVisible = false;
				if($("#maplistview").is(":visible") == true)
				{
					$("#tabmapview").click();
					listViewVisible = true;
				}
			// IE 8 Bug workaround: slut

				nearestStores.sort(sortByDistance);
				map.setCenter(nearestStores[0][0].getPoint(), 12);
				// Get visible markers and set zoom level
				var count = 0;
				var resultArray = new Array();
				var visibleBounds = map.getBounds();

				for (var i = 0; i < markers.length; i++) 
				{
					if (visibleBounds.containsLatLng(markers[i].getLatLng())) {
						count++;
					}
				}
				if(count<=2) {
					map.setCenter(visibleBounds.getCenter(), 14);
				} else if(count<8 && count>2){
					map.setCenter(visibleBounds.getCenter(), 12);

				} else if(count<14 && count>8){
					map.setCenter(visibleBounds.getCenter(), 11);
				} else {
					map.setCenter(visibleBounds.getCenter(), 10);				
				}

				var visibleZoomedBounds = map.getBounds();

				for (var i = 0; i < markers.length; i++) 
				{
					if (visibleZoomedBounds.containsLatLng(markers[i].getLatLng())) {
						resultArray.push(markers[i].getLatLng().lat());
					}
				}

			// IE 8 Bug workaround: start
				if(listViewVisible == true)
				{
					$("#tablistview").click();
				}
			// IE 8 Bug workaround: slut				

				displayListviewResult(resultArray);
				displayZipResult(resultArray);

				// listener
				GEvent.addListener(map, "moveend", function() {	
				// Get search result for list view	
					var count = 0;
					var resultArray = new Array();
					var visibleZoomedBounds = map.getBounds();
					
					for(var i = 0; i < markers.length; i++) 
					{
						if (visibleZoomedBounds.containsLatLng(markers[i].getLatLng())) 
						{
							resultArray.push(markers[i].getLatLng().lat());
						}
					}

					if($("#mapview").is(":visible") == true)
					{
						displayListviewResult(resultArray);
						displayZipResult(resultArray);
					} else {
						displayListviewResult(resultArray);
					}
				});

				$("#selectDisplayArea").html(searchType + ": " + postcode);
			} else{
				alert($("#txtForkertPostnr").html());
			}
		});	
	var language = "DK";
	if($(".langse").hasClass(".langseactive")) {
		language = "SE";
	}
	localSearch.execute(postcode + ", " + language);
	*/
	return false;
}


$(document).ready(function(){
	$(".zipsearchfield").val($("#txtPostnummerElleBy").html());
	$("#viewtxt").html($("#txtMapview").html());
	$("#selectDisplayArea").html($("#txtDefaultDisplay").html());
	$(".txtPostnrogbyInp").html($("#txtPostnrogby").html());
	
	
});
