
function debug(msg, obj) {
	if (typeof(console) != "undefined" && typeof(console.debug) == "function") {
		console.debug(msg, obj);
	}
}

function getMapCenter() {
	return mapContext.places[mapContext.places.length-1];
}

function RemoveMap() {
	var map = document.getElementById("map");
	if (map != null) {
		var mapContainer = map.parentNode;
		mapContainer.parentNode.removeChild(mapContainer);
	}
}

var mapContext = {
	zoomLevel: 11,
	mapPages: {
		freewriting: {name: "farticle", category: true},
		pilgrimroute: {name: "proute", category: false},
		service: {name: "service", category: false},
		accservice: {name: "accservice", category: false}
	},
	mapIcons: {
		pilgrimroute: {
			foreign: '/img/poi/poi_zarandokut.png',
			domestic: '/img/poi/poi_zarandokut.png'
		},
		freewriting: {
			route: "/img/poi/poi_napi_szakasz.png",
			placedesc: "/img/poi/poi_informacios_pont.png",
			kegydesc: "/img/poi/poi_kegyhely.png",
			roadguide: "/img/poi/poi_informacios_pont.png",
			article: "/img/poi/poi_informacios_pont.png"
		},
		accservice: {
			pilgrim: "/img/poi/poi_zarandok_szallas.png",
			//tourist: "/img/poi/poi_zarandok_szallas.png",
			apartment: "/img/poi/poi_apartman.png",
			apartman: "/img/poi/poi_apartman.png",
			//panzio: "/img/poi/poi_apartman.png",
			//parokia: "/img/poi/poi_zarandok_szallas.png",
			//local_goverment: "/img/poi/poi_zarandok_szallas.png",
			//gym: "/img/poi/poi_zarandok_szallas.png",
			//pension: "/img/poi/poi_zarandok_szallas.png",
			//camping: "/img/poi/poi_zarandok_szallas.png",
			//vacationer: "/img/poi/poi_zarandok_szallas.png",
			hostel: "/img/poi/poi_apartman.png",
			//youth_hostel: "/img/poi/poi_apartman.png",
			//guesthouse: "/img/poi/poi_apartman.png",
			//guestroom: "/img/poi/poi_apartman.png",
			//hotel_4: "/img/poi/poi_apartman.png",
			//hotel_3: "/img/poi/poi_apartman.png",
			hotel: "/img/poi/poi_apartman.png"
		},
		service: {
			doctor: "/img/poi/poi_orvosi_rendelo.png",
			pharmacy: "/img/poi/poi_gyogyszertar-v2.png",
			railwaystation: "/img/poi/poi_vasutallomas.png",
			busstop: "/img/poi/poi_buszmegallo.png", 
			internet: "/img/poi/poi_internet.png",
			market: "/img/poi/poi_abc.png",
			restaurant: "/img/poi/poi_etterem.png",
			post: "/img/poi/poi_posta.png"
		}
	},
	icons: {
		blue_pushpin	: "http://maps.google.com/mapfiles/ms/micons/blue-pushpin.png",
		red_dot			: "http://maps.google.com/mapfiles/ms/micons/red-dot.png",
		abc				: "/img/poi/poi_abc.png",
		apartman		: "/img/poi/poi_apartman.png",
		apartment		: "/img/poi/poi_apartman.png",
		etterem			: "/img/poi/poi_etterem.png",
		gyogyszertar	: "/img/poi/poi_gyogyszertar.png",
		informacios_pont: "/img/poi/poi_informacios_pont.png",
		kegyhely		: "/img/poi/poi_kegyhely.png",
		napi_szakasz	: "/img/poi/poi_napi_szakasz.png",
		orvosi_rendelo	: "/img/poi/poi_orvosi_rendelo.png",
		zarandok_szallas: "/img/poi/poi_zarandok_szallas.png",
		base			: "/img/poi/poi_base.png"
	},
	places: [],
	geocodes: [],
	routeBoxes: {},
	infoWindow: null,
	selected: null,
	
	add: function (fltLat, fltLng, strName) {
		mapContext.places.push({lat: fltLat, lng: fltLng, name: strName});
		debug("mapContext.places", mapContext.places);
	},
	
	select: function (structure, id, name) {
		this.selected = {structure: structure, id: id, name: name};
	},
	
	init: function () {		
		var divMap = document.getElementById("map");
		
		if (divMap != null && mapContext.places.length > 0) {
			this.control.init();
			if (this.selected != null) {
				this.showHeightGraph(this.selected.structure, this.selected.id, this.selected.name);
			}
			
			var place = mapContext.places[mapContext.places.length-1];
			
			var position = new google.maps.LatLng(place.lat, place.lng);
			
			mapContext.map = new google.maps.Map(divMap, {
				zoom: mapContext.zoomLevel,
				center: position,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			});
			
			/*
			var marker = new google.maps.Marker({
				position: new google.maps.LatLng(place.lat, place.lng),
				title: place.name,
				clickable: true,
				map: mapContext.map
			});
			*/
			
			var fullmap = {
				ne_lat: 90,
				ne_lng: 180,
				sw_lat: -90,
				sw_lng: -180,
				c_lat: 0,
				c_lng: 0,
				name: "nearby"
			};
			$.getJSON("/common/service/requestparser", fullmap, mapContext.fullmap);
		} else {
			RemoveMap();
		}
	},
	
	fullmap: function (data) {
		mapContext.captions = data.captions;
		mapContext.geocodes = [];
		for (var i=0; i<data.geocodes.length; i++) {
			var geocode = data.geocodes[i];
			if (geocode.type.indexOf("track") < 0) {
				if (geocode.lat != -1 && geocode.lng != -1) {
					mapContext.geocodes.push(geocode);
					var marker = new google.maps.Marker({
						position: new google.maps.LatLng(geocode.lat, geocode.lng),
						title: geocode.caption,
						icon: mapContext.icon(geocode),
						clickable: true,
						map: mapContext.map
					});
					geocode.marker = marker;
					mapContext.info(marker, geocode);
				}
			}
		}
		
		// utak körüli téglalapok (sarkainak) eltárolása
		for (var i=0; i<data.geocodes.length; i++) {
			var geocode = data.geocodes[i];
			if (geocode.type.indexOf("track_upper_right") > -1 || geocode.type.indexOf("track_bottom_left") > -1) {
				var route_name = geocode.structure + "_" + geocode.structure_id;
				if (typeof(mapContext.routeBoxes[route_name]) == "undefined") {
					mapContext.routeBoxes[route_name] = {};
					mapContext.routeBoxes[route_name].structure = geocode.structure;
					mapContext.routeBoxes[route_name].structure_id = geocode.structure_id;
				}
				if (geocode.type.indexOf("bottom_left") > -1) {
					mapContext.routeBoxes[route_name].sw_lat = geocode.lat;
					mapContext.routeBoxes[route_name].sw_lng = geocode.lng;
				} else if (geocode.type.indexOf("upper_right") > -1) {
					mapContext.routeBoxes[route_name].ne_lat = geocode.lat;
					mapContext.routeBoxes[route_name].ne_lng = geocode.lng;
				}
			}
		}
		
		google.maps.event.addListener(mapContext.map, 'idle', mapContext.nearby);
		mapContext.nearby();
	},
	
	
	nearby: function (data) {
		var bounds = mapContext.pos();
		for (var i=0; i<mapContext.geocodes.length; i++) {
			var geocode = mapContext.geocodes[i];
			if (bounds.sw_lat < geocode.lat && bounds.ne_lat > geocode.lat
					&& bounds.sw_lng < geocode.lng && bounds.ne_lng > geocode.lng) {
				geocode.show = true;
			} else {
				geocode.show = false;
			}
		}
		mapContext.links();
		mapContext.track();
		mapContext.control.updateMarkerDisplay();
	},
	
	pos: function () {
		var bounds = mapContext.map.getBounds();
		
		//debug("bounds", bounds);
		
		var latDiff = bounds.getNorthEast().lat() - bounds.getSouthWest().lat();
		var lngDiff = bounds.getNorthEast().lng() - bounds.getSouthWest().lng();
		var threshold = 0.1;
		
		return {
			ne_lat: bounds.getNorthEast().lat() + latDiff*threshold,
			ne_lng: bounds.getNorthEast().lng() + lngDiff*threshold,
			sw_lat: bounds.getSouthWest().lat() - latDiff*threshold,
			sw_lng: bounds.getSouthWest().lng() - latDiff*threshold,
			c_lat: bounds.getCenter().lat(),
			c_lng: bounds.getCenter().lng()
		};
	},
	
	show: function (intPos) {
		document.location = "#map";
		
		var geocode = mapContext.geocodes[intPos];
		
		var position = new google.maps.LatLng(geocode.lat, geocode.lng);
		mapContext.map.setCenter(position);
		
		if (mapContext.infoWindow != null) mapContext.infoWindow.close();
		
		mapContext.infoWindow = new google.maps.InfoWindow({position: position, content: geocode.caption});
		mapContext.infoWindow.open(mapContext.map);
	},
	
	showPlace: function (intPos) {
		var place = mapContext.places[intPos];
		var position = new google.maps.LatLng(place.lat, place.lng);
		mapContext.map.setCenter(position);
	},
	
	links: function () {
		//var cfgUL = {_tag: "table", id: "ul_nearby_places"};
		var cfgUL = {_tag: "ul", id: "ul_nearby_places"};
		
		var ulLinks = Xin.dom.get("ul_nearby_places");
		var divLinks = Xin.dom.get("div_nearby_places");
		
		if (ulLinks != null) {
			divLinks.removeChild(ulLinks);
		}
		
		var objAreas = {select: []};
		
		for (var i=0; i<mapContext.places.length; i++) {
			var place = mapContext.places[i];
			
			var li = {_tag: "li", _items: []};
			li._items.push({_tag: "a", href: "javascript: mapContext.showPlace("+i+");", 
				_items: [{_tag: "img", src: mapContext.icons.red_dot, width: "16px"}]
			});
			li._items.push({_tag: "a", href: "javascript: void(0);", title: place.name, _text: mapContext.trim(place.name)});
			
			objAreas["select"].push(li);
		}
		
		for (var i=0; i<mapContext.geocodes.length; i++) {
			var geocode = mapContext.geocodes[i];
			if (typeof(geocode.show) == "undefined" || geocode.show == true) {
				if (geocode.type.indexOf("track") < 0) {
					if (typeof(objAreas[geocode.structure]) == "undefined") {
						objAreas[geocode.structure] = [];
					}
				
					var li = {_tag: "li", _items: []};
					li._items.push({_tag: "a", href: "javascript: mapContext.show("+i+");", _items: [
						{_tag: "img", src: mapContext.icon(geocode), width: "16px"}]});
					li._items.push({_tag: "a", href: mapContext.url(geocode), 
						title: mapContext.captionText(geocode), _text: mapContext.caption(geocode)});
				
					// target: "_blank", 
					objAreas[geocode.structure].push(li);
				}
			}
		}
		
		for (var strArea in objAreas) {
			var arrItems = objAreas[strArea];
			
			var cfgArea = {_tag: "li", _class: "title", _text: captionContext.caption("poigrp_"+strArea), list: {_tag: "ul"}};
			
			for (var i=0; i<arrItems.length; i++) {
				cfgArea.list["li_"+i] = arrItems[i];
			}
			
			cfgUL["li_"+strArea] = cfgArea;
		}
		
		var domUL = Xin.dom.create(cfgUL, divLinks);
	}, 

	trim: function (strCaption) {
		if (strCaption.length > 40) {
			return strCaption.substring(0, 40)+'...';
		}
		return strCaption;
	},
	
	caption: function (geocode) {
		return mapContext.trim(mapContext.captionText(geocode));
	},
	
	captionText: function (geocode) {
		if (geocode.structure == null) {
			return geocode.caption;
		} else {
			for (var i=0; i<mapContext.captions.length; i++) {
				var item = mapContext.captions[i];
				if (geocode.structure == item.name && geocode.structure_id == item.id) {
					return item.title;
				}
			}
		
			return geocode.caption;
		}
	},
	
	icon: function (geocode) {
		//debug("geocode", geocode);
		if (geocode.structure != null && geocode.structure.length > 0) { 
			var iconStructure = mapContext.mapIcons[geocode.structure];
			if (typeof(iconStructure) == "undefined") {
				//alert("Structure: "+geocode.structure+" not found!");
				return mapContext.icons.base;
			}
			
			var iconType = iconStructure[geocode.type];
			if (typeof(iconType) == "undefined") {
				//alert("Type: "+geocode.structure+"/"+geocode.type+" not found!");
				return mapContext.icons.base;
			}
			
			return iconType;
		} else {
			return mapContext.icons.blue_pushpin;
		}
	},
	
	track: function () {
		// felbontás megadása zoom level alapján
		var zoom = mapContext.map.getZoom();
		var resolution;
		if (zoom < 9) {
			resolution = 4;
		} else if (zoom < 10) {
			resolution = 3;
		} else if (zoom < 12) {
			resolution = 2;
		} else {
			resolution = 1;
		}
		
		// látható téglalapok útjainak berajzolása
		for (route_name in mapContext.routeBoxes) {
			var routeBox = mapContext.routeBoxes[route_name];
			var pos = mapContext.pos();
			if ((pos.ne_lat >= routeBox.sw_lat) && (pos.sw_lat <= routeBox.ne_lat) &&
					(pos.ne_lng >= routeBox.sw_lng) && (pos.sw_lng <= routeBox.ne_lng)) {
				if (typeof(routeBox.path) == "undefined" || routeBox.pathRes != resolution) {
					routeBox.pathRes = resolution;
					mapContext.trackPoints(routeBox, this.trackUrl(routeBox.structure, routeBox.structure_id, "track"+resolution+".js"));
				} else {
					routeBox.path.setMap(mapContext.map);
				}
			} else {
				if (typeof(routeBox.path) != "undefined") {
					routeBox.path.setMap(null);
				}
			}
		}
	},
	
	trackPoints: function (routeBox, url) {
		$.getJSON(url, null, function (data) {
			var arrPoints = [];
			
			for (var i=0; i<data.length; i++) {
				var geocode = data[i];
				arrPoints.push(new google.maps.LatLng(geocode.lat, geocode.lng));
			}
			
			var routePath = new google.maps.Polyline({
				path: arrPoints,
				clickable: false,
				strokeColor: "#FF0000",
				strokeOpacity: 1.0,
				strokeWeight: 2
			});
			
			if (typeof(routeBox.path) != "undefined") {
				routeBox.path.setMap(null);
			}
			routeBox.path = routePath;
			routeBox.path.setMap(mapContext.map);
		});
	},
	
	url: function (geocode) {
		var cfgPage = mapContext.mapPages[geocode.structure];
		var strUrl = "";
		
		if (typeof(cfgPage) == "undefined") {
			alert("Page map not found: "+geocode.structure);
		} else {
			strUrl = "/tart/";
			strUrl += cfgPage.name;
			strUrl += "/";
			
			if (cfgPage.category) {
				strUrl += geocode.url; strUrl += "/";
			}
			
			strUrl += geocode.structure_id;
			
			if (cfgPage.category) {
				strUrl += "/1";
			}
		}
		
		return strUrl+"#map";
	},
	
	info: function (marker, geocode) {
		var strUrl = mapContext.url(geocode);
		google.maps.event.addListener(marker, 'click', function() {
			document.location = strUrl;
		});
	},
	
	links2: function () {
		var cfgUL = {_tag: "ul", id: "ul_nearby_places"};
		
		var ulLinks = Xin.dom.get("ul_nearby_places");
		var divLinks = Xin.dom.get("div_nearby_places");
		
		if (ulLinks != null) {
			divLinks.removeChild(ulLinks);
		}
		
		for (var i=0; i<mapContext.geocodes.length; i++) {
			var geocode = mapContext.geocodes[i];
			cfgUL["geocode_"+i] = {
				_tag: "li", 
				link: {_tag: "a", href: geocode.url, _text: geocode.caption}
			};
		}
		
		var domUL = Xin.dom.create(cfgUL, divLinks);
	},
	
	trackUrl: function (structure, id, filename) {
		var idPath = "";
		var idString = id+"";
		for (var i=0; i<idString.length; i++) {
			idPath += idString[i]+"/";
		}
		return "/track/"+structure+"/"+idPath+"/"+filename;
	},
	
	showHeightGraph: function (structure, id, name) {
		$.getJSON(this.trackUrl(structure, id, "metadata.js"), null, function (data) {
			$('#mapHeightGraph').remove();
			var graph = $('<div/>');
			graph.attr('id', 'mapHeightGraph').css({width: '100%', height: 160, marginTop: 10});
			$('#control').after(graph);
			
			var line = [];
			for (var i=0; i<data.elevation.length; i++) {
				var point = [data.elevation[i].distance, data.elevation[i].height];
				line.push(point);
			}
			
			$.jqplot('mapHeightGraph', [line], {
				title: name+' szintt&eacute;rk&eacute;p',
				axes: {
					xaxis: {
						min: data.elevation[0].distance,
						max: data.elevation[data.elevation.length-1].distance,
						tickOptions: {formatString: '%d m'},
						numberTicks: 10
					},
					yaxis: {
						tickOptions: {formatString: '%d m'}
					}
				},
				seriesDefaults: {
					showMarker: false,
					fill: true,
					fillAndStroke: true,
					color: 'rgba(0, 120, 0, 1)',
					fillColor: 'rgba(0, 120, 0, 0.5)',
					shadowAngle: -45,
					rendererOptions: {smooth: true}
				},
				highlighter: {
					show: true,
					tooltipLocation: 'n',
					useAxesFormatters: false,
					formatString: 'Távolság: %d m, Magasság: %d m'
				}
			});
		});
	},
	
	control: {
		config: {
			displayButtons: {
				service: {
					mode: 'AUTO',
					zoomLevel: 9,
					text: 'Szolgáltatások'
				},
				accservice: {
					mode: 'AUTO',
					zoomLevel: 9,
					text: 'Szállás szolg.'
				},
				freewriting: {
					mode: 'AUTO',
					zoomLevel: 8,
					text: 'Szabad írások'
				},
				pilgrimroute: {
					mode: 'AUTO',
					zoomLevel: 9,
					text: 'Zarándokutak'
				},
				dailysection: {
					mode: 'AUTO',
					zoomLevel: 8,
					text: 'Napi szakaszok'
				}
			},
			height: 56,
			fullscreen: false
		},
		
		init: function () {
			var control = $('<div/>').attr('id', 'control').css({width: '100%', height: this.config.height, position: 'relative'});
			var buttons =  $('<div/>').css({position: 'absolute', width: '100%', bottom: '0px', left: '0px'});
			control.append(buttons);
			$('#map').after(control);
			buttons.append(this.createFullscreenButton());
			for (var type in this.config.displayButtons) {
				buttons.append(this.createDisplayButton(type, this.config.displayButtons[type]));
			}
		},
		
		createButton: function (id, text, width) {
			var button = $('<div/>');
			button.attr('id', id);
			button.css({background: '#FFFFFF', float: 'left', textAlign: 'center', lineHeight: '20px', fontSize: '8pt', border: '1px #707A86 solid', width: width, height: 20, margin: '2px', boxShadow: '2px 2px 4px #A0A0A0'});
			button.html(text);
			button.hover(function () {
				button.css({cursor: 'pointer', backgroundColor: '#EEEEEE'});
			}, function () {
				button.css({cursor: 'default', backgroundColor: '#FFFFFF'});
			});
			return button;
		},
		
		createDisplayButton: function (type, config) {
			var button = this.createButton(type+'Toggle', config.text+': '+config.mode, 145);
			button.click(function () {
				mapContext.control.toggleMarkerDisplay(type);
				mapContext.control.updateMarkerDisplay();
			});
			return button;
		},
		
		createFullscreenButton: function () {
			var button = this.createButton('fullscreenToggle', 'Teljes képernyő', 110);
			button.css({float: 'right'});
			button.click(function () {
				mapContext.control.toggleFullscreen(true);
			});
			return button;
		},
		
		toggleMarkerDisplay: function (type) {
			var obj = this.config.displayButtons[type];
			if (obj.mode == 'AUTO') {
				obj.mode = 'KI';
			} else if (obj.mode == 'KI') {
				obj.mode = 'BE';
			} else {
				obj.mode = 'AUTO';
			}
			$('#'+type+'Toggle').html(obj.text+': '+obj.mode);
			this.updateMarkerDisplay();
		},
		
		updateMarkerDisplay: function () {
			for (var type in this.config.displayButtons) {
				var obj = this.config.displayButtons[type];
				var auto = obj.mode == 'AUTO';
				var show = auto ? obj.zoomLevel <= mapContext.map.getZoom() : obj.mode == 'BE';
				var button = $('#'+type+'Toggle');
				if (show) {
					button.css('font-weight', 'bold');
				} else {
					button.css('font-weight', 'normal');
				}
				this.showMarkers(type, show);
			}
		},
		
		// accservice, freewriting, pilgrimroute
		showMarkers: function (marker, visible) {			
			for (var i=0; i<mapContext.geocodes.length; i++) {
				var geocode = mapContext.geocodes[i];
				if (typeof(geocode.marker) != "undefined") {
					if (geocode.structure == marker) {
						geocode.marker.setVisible(visible);
					}
				}
			}
		},
		
		toggleFullscreen: function () {
			if (!this.config.fullscreen) {
				var winHeight = $(window).height();
				this.config.fullscreen = true;
				$('#fullscreenToggle').css('font-weight', 'bold');
				var center = mapContext.map.getCenter();
				var mapDiv = $('#map');
				var mapTop = mapDiv.offset().top;
				this.config.base = {width: mapDiv.css('width'), height: mapDiv.css('height'), zIndex: mapDiv.css('z-index')};
				if (winHeight-mapTop < this.config.height) {
					$('#control').css({width: this.config.base.width, height: this.config.height, position: 'absolute', top: winHeight-this.config.height});
				} else {
					$('#control').css({width: this.config.base.width, height: winHeight-mapTop});
				}
				mapDiv.css({position: "absolute", width: '100%', height: winHeight-this.config.height, left: 0, top: 0, zIndex: 999, boxShadow: '2px 2px 4px #A0A0A0'});
				google.maps.event.trigger(mapContext.map, "resize");
				mapContext.map.setCenter(center);
				$('html, body').scrollTop(0);
			} else {
				this.config.fullscreen = false;
				$('#fullscreenToggle').css('font-weight', 'normal');
				var center = mapContext.map.getCenter();
				var mapDiv = $('#map');
				$('#control').css({width: '100%', height: this.config.height, position: 'relative', top: 0});
				mapDiv.css({position: "relative", width: this.config.base.width, height: this.config.base.height, zIndex: this.config.base.zIndex, boxShadow: 'none'});
				google.maps.event.trigger(mapContext.map, "resize");
				mapContext.map.setCenter(center);
			}
		}
	}
};

// mapContext.add(47.528021365733366, 19.014775156974792, 'LP Iroda');

$(document).ready(function(){
	mapContext.init();
});

/*

var flightPlanCoordinates = [
    new google.maps.LatLng(37.772323, -122.214897),
    new google.maps.LatLng(21.291982, -157.821856),
    new google.maps.LatLng(-18.142599, 178.431),
    new google.maps.LatLng(-27.46758, 153.027892)
  ];
var flightPath = new google.maps.Polyline({
    path: flightPlanCoordinates,
    strokeColor: "#FF0000",
    strokeOpacity: 1.0,
    strokeWeight: 2
});

flightPath.setMap(map);

freewriting: "farticle",
pilgrimroute: "proute",
service: "service",
accservice: "accservice"

*/


