var map_client = new Object();

// addMarkerIcon
map_client.addMarkerIcon = function(name, src){
	var icon = map_client.markerIcons[name] = src;
	return true;
}

// attachGmap
map_client.attachGmap = function(){
	
	map_client.mapTypes = Object();
	map_client.mapTypes['Map'] = G_NORMAL_MAP;
	map_client.mapTypes['Satellite'] = G_SATELLITE_MAP ;
	map_client.mapTypes['Hybrid'] = G_HYBRID_MAP;
	map_client.mapTypes['Terrain'] = G_PHYSICAL_MAP;
	
	map_client.xml = $.ajax({ dataType: "xml", url: "/module/acms_maps?mapXml="+map_client.map_id, async: false }).responseXML;
	
	map_client.gmap = new GMap2(document.getElementById(map_client.wrapper_id));
	
	$('#tripMap div:first div:first > div:eq(1)').after('<div id="gmap_opacity_overlay"></div>');
	//$('#tripMap').prepend('<div id="gmap_opacity_overlay"></div>');
	
	$('#gmap_opacity_overlay').css('opacity', 0.1);
	$('#gmap_opacity_overlay').css('position', 'absolute');
	$('#gmap_opacity_overlay').css('z-index', '99');
	$('#gmap_opacity_overlay').width(  $('#tripMap').width() + 'px'  );
	$('#gmap_opacity_overlay').height(  $('#tripMap').height() + 'px'  );
	
	map_client.parseXml();
	if(typeof(map_client.waypointInit) == 'function'){
		map_client.waypointInit();
	}
	
}

map_client.addLegend = function(){
	//$('#tripMap').after('<div id="gmap_legend"><div class="title">Key</div><dl></dl></div>');
	$('#tripMap').after('<div id="gmap_legend"><h5>Key</h5><dl></dl></div>');
	
	var inLegend = new Object();
	
	for(var iconName in map_client.markerIcons){
		
		var iconSrc = map_client.markerIcons[iconName];
	
		iconDisplayName = iconName;
		if(iconDisplayName.substr(0, 5) == 'Peak '){ iconDisplayName = 'Peaks'; }
		if(iconDisplayName.substr(0, 5) == 'Pass '){ iconDisplayName = 'Pass'; }
		if(iconDisplayName.substr(0, 6) == 'Arrow '){ iconDisplayName = 'Trip Direction'; }
		
		var currInLegend = inLegend[iconDisplayName];
		if(typeof(currInLegend) != 'boolean'){ currInLegend = false; }
		
		var currOnMap =  map_client.markersOnMap[iconName];
		if(typeof(currOnMap) != 'boolean'){ currOnMap = false; }
		
		if(iconName != 'Point' && currOnMap && !currInLegend){
			$('#gmap_legend dl').append('<dd><img src="' + iconSrc + '" alt="' + iconDisplayName + '" title="' + iconDisplayName + '"></dd><dt>' + iconDisplayName + '</dt>');
			inLegend[iconDisplayName] = true;
		}
		
		// Stop duplicates of similar icons
		map_client.markersOnMap[iconDisplayName] = true;
	}
	
	// map_client.lineColours['Transport'] = '#00FF00';
	
	for(var lineName in map_client.lineColours){
		var lineColour = map_client.lineColours[lineName];
		
		if(map_client.linesOnMap[lineColour]){
			$('#gmap_legend dl').append('<dd><div style="height:4px; min-height:4px; width: 22px; margin: 13px 0 0 5px; background: ' + lineColour + '"></div></dd><dt>&nbsp;' + lineName + '</dt>');		
		}
	}
	
	$('#gmap_legend').append('<br class="cleafix"/>');
}

// parseXml
map_client.parseXml = function(){
	
	var map = $(map_client.xml).find('map');
	// Parse mapType, lat, lng and zoom
	
	map_client.mapType = map.attr('mapType');
	map_client.lat = parseFloat(map.attr('lat'));
	map_client.lng = parseFloat(map.attr('lng'));
	map_client.zoom = parseInt(map.attr('zoom'));
	map_client.clientControls = parseInt(map.attr('clientControls'));
	
	if(map_client.mapType == 'undefined'){ map_client.mapType = 'Satellite'; }
		
	map_client.gmap.setCenter(new google.maps.LatLng(map_client.lat, map_client.lng), map_client.zoom);
	map_client.gmap.setMapType(map_client.mapTypes[map_client.mapType]);
	
	if(map_client.clientControls == 1){
		map_client.gmap.addControl(new GLargeMapControl());
	}
	else{
		map_client.gmap.disableDragging();
	}
	
	map_client.markersOnMap = new Object();
	map_client.linesOnMap = new Object();
	
	map.find('marker').each(function(){
					 
		if( $(this).attr('type') == 'marker' ){
			
			var iconName = $(this).attr('icon');
			var iconSrc = map_client.markerIcons[iconName];
			var labelStr = unescape($(this).attr('labelStr')).replace(/%20/g,' ').replace(/%27/g,'\'');
			
			map_client.markersOnMap[iconName] = true;
			
			if(typeof(iconName) != 'string' || iconName == ''){ iconName = ''; }
			if(typeof(labelStr) != 'string' || labelStr == ''){ labelStr = ''; }
			
			var node = $(this).find('node:first');
			
			var nodeLat = parseFloat(node.attr('lat'));
			var nodeLng = parseFloat(node.attr('lng'));
			
			var nodeLatLng = new google.maps.LatLng(nodeLat, nodeLng);		
			
			// ADD MARKER TO MAP
			if(iconName == 'Label' || (typeof(iconSrc) == 'string' && iconName != 'Default')){
				
				if(iconName == 'Label'){
					
					if(labelStr != ''){
						var labelSrc = map_client.labelGenPath + '?text=' + escape(labelStr);
						$.ajax({
							url: labelSrc+'&info',
							async: true,
							cache: true,
							success: function(labelDim){
								labelDim = labelDim.split(',');
								labelDim[0] = parseInt(labelDim[0]);
								labelDim[1] = parseInt(labelDim[1]);
								
								var icon = new GIcon(G_DEFAULT_ICON);
								icon.image = labelSrc;
								
								icon.iconSize = new GSize(labelDim[0], labelDim[1]);
								icon.iconAnchor = new GPoint(0, labelDim[1]);
								
								icon.shadow = '';
						
								var options = { icon:icon };
								
								var overlay = new GMarker(nodeLatLng, options);
								map_client.gmap.addOverlay(overlay);
							}
						});
						
						/*labelDim = $.ajax({ url: labelSrc+'&info', async: false, cache: true }).responseText;
						labelDim = labelDim.split(',');
						labelDim[0] = parseInt(labelDim[0]);
						labelDim[1] = parseInt(labelDim[1]);
						
						var icon = new GIcon(G_DEFAULT_ICON);
						icon.image = labelSrc;
						
						icon.iconSize = new GSize(labelDim[0], labelDim[1]);
						icon.iconAnchor = new GPoint(0, labelDim[1]);
						
						icon.shadow = '';
						
						var options = { icon:icon };
						
						var overlay = new GMarker(nodeLatLng, options);
						map_client.gmap.addOverlay(overlay);*/
					}
				}
				else{
					
					var icon = new GIcon(G_DEFAULT_ICON);
					icon.image = iconSrc;
					icon.iconSize = new GSize(22, 22);
					icon.iconAnchor = new GPoint(11, 11);
					icon.shadow = '';
	
					var options = { icon:icon };
					
					var overlay = new GMarker(nodeLatLng, options);
					map_client.gmap.addOverlay(overlay);
				}
			}
			else{
				var overlay = new GMarker(nodeLatLng);
				map_client.gmap.addOverlay(overlay);
			}
			
			var info = $(this).find('infoHtml:first').text();
			//info = info.replace('<!--[CDATA[','');
			//info = info.replace(']]-->','');
			if(info != '' && typeof(info) == 'string'){
				GEvent.addListener(overlay, "click", function(overlay){
					map_client.infoPopup(info);
				});
			}
			
		}
		else if( $(this).attr('type') == 'line' ){
			var nodes = new Array();
			
			$(this).find('node').each(function(){
				var nodeLat = parseFloat($(this).attr('lat'));
				var nodeLng = parseFloat($(this).attr('lng'));
				var nodeLatLng = new google.maps.LatLng(nodeLat, nodeLng);
				nodes[nodes.length] = nodeLatLng;
			});
			var lineCol = map_client.lineColours[$(this).attr('colour')];
			
			map_client.linesOnMap[lineCol] = true;
			
			var weight = parseInt($(this).attr('weight'));
			if(weight == 0 || weight != weight){ weight = 2; }
			
			var overlay = new GPolyline(nodes, lineCol, weight, 1);
			map_client.gmap.addOverlay(overlay);
		}
	});
	
	map_client.addLegend();
}

map_client.infoPopup_close = function(){
	$('#map_client_infoPopup').remove();
}

map_client.infoPopup = function(){
	map_client.infoPopup_close();
	var wrap = $('#'+map_client.wrapper_id);
	
	wrap.css({ position:'relative' });
	wrap.append('<div id="map_client_infoPopup"></div>');
	
	var popup = $('#map_client_infoPopup');
	popup.append('<a id="map_client_infoPopup_close" href="javascript:;" onClick="map_client.infoPopup_close();">Close</a>');
	popup.append('<div id="map_client_infoPopup_inner">' +  + '</div>');
}

// show
map_client.show = function(){
	$('#'+map_client.wrapper_id).fadeTo(2000, 1);
}

// addWaypoint
map_client.addWaypoint = function(lat, lng, zoom){
	var key = map_client.waypoints.length;
	map_client.waypoints[key] = new Object();
	var waypoint = map_client.waypoints[key];
		
	waypoint.lat = lat;
	waypoint.lng = lng;
	waypoint.zoom = zoom;
}

// addWaypointControls
map_client.addWaypointControls = function(){
	
	if(map_client.waypoints.length > 0){
		
		$('#'+map_client.wrapper_id).after('<div id="active_itinerary_item"></div>');
		$('#'+map_client.wrapper_id).after('<div id="map_client_controls"></div>');
		
		var controls = $('#map_client_controls');
		
		controls.append('<a href="javascript:;" onClick="map_client.prevWaypoint()">Previous Itinerary Item</a> | ');
		controls.append('<a href="javascript:;" onClick="map_client.nextWaypoint()">Next Itinerary Item</a>');
		
		map_client.currWaypoint = 0;
		map_client.focusWaypoint(0);
	}
	
	$('div.itinerary_item').each(function(){
		var id = $(this).attr('id');
		id = parseInt(id.replace('itinerary_', ''));
		$(this).click(function(){
			map_client.focusWaypoint(id);
		});
	});
}

map_client.focusWaypoint = function(key){
	map_client.currWaypoint = key;
	var waypoint = map_client.waypoints[key];
	
	$('div.itinerary_item').removeClass('focus');
	$('div.itinerary_item#itinerary_'+key).addClass('focus');
	
	$('#active_itinerary_item').html($('div.itinerary_item#itinerary_'+key).html());
	
	map_client.gmap.setCenter(new google.maps.LatLng(waypoint.lat, waypoint.lng), waypoint.zoom);
}

map_client.nextWaypoint = function(){
	map_client.currWaypoint++;
	if(map_client.currWaypoint >= map_client.waypoints.length){ map_client.currWaypoint = 0; }
	map_client.focusWaypoint(map_client.currWaypoint);
}

map_client.prevWaypoint = function(){
	map_client.currWaypoint--;
	if(map_client.currWaypoint < 0){ map_client.currWaypoint = map_client.waypoints.length - 1; }
	map_client.focusWaypoint(map_client.currWaypoint);
}

// load
map_client.load = function(wrapper_id, map_id){
	
	map_client.waypoints = Array();
	
	map_client.currMarker = 0;
	map_client.googleMapsApiLoaded = false;
	
	/* CONFIG - START */
		map_client.path = '/scripts/map_editor/';
		//map_client.labelGenPath = '/scripts/map_editor/images/mapLabel.php';
		map_client.labelGenPath = '/scripts/map_editor/images/mapLabel_proxy.php';

	
		map_client.lineColours = new Object();
		//map_client.lineColours['Over Land Transport'] = '#00FF00';
		map_client.lineColours['Transfer'] = '#00FF00';
		//map_client.lineColours['In Land Flight'] = '#000000';
		map_client.lineColours['Internal Flight'] = '#000000';
		map_client.lineColours['Trek'] =  '#E21C24';
		map_client.lineColours['Bike'] =  '#0071BC';
		
		map_client.markerIcons = new Object();
		map_client.addMarkerIcon('Point', map_client.path+'images/markers/map_icon_point.png');
		map_client.addMarkerIcon('Plane', map_client.path+'images/markers/map_icon_plane.png');
		
		//map_client.addMarkerIcon('Bus', map_client.path+'images/markers/map_icon_bus.png');
		//map_client.addMarkerIcon('Cable Train', map_client.path+'images/markers/map_icon_cable_train.png');
		//map_client.addMarkerIcon('Cable Car', map_client.path+'images/markers/map_icon_cable_car.png');
		//map_client.addMarkerIcon('Bike', map_client.path+'images/markers/map_icon_bike.png');
		//map_client.addMarkerIcon('Trek', map_client.path+'images/markers/map_icon_trek.png');
		//map_client.addMarkerIcon('House', map_client.path+'images/markers/map_icon_house.png');
		//map_client.addMarkerIcon('Tent', map_client.path+'images/markers/map_icon_tent.png');
		
		map_client.addMarkerIcon('Peak Large', map_client.path+'images/markers/map_icon_peak_large.png');
		map_client.addMarkerIcon('Peak Medium', map_client.path+'images/markers/map_icon_peak_medium.png');
		map_client.addMarkerIcon('Peak Small', map_client.path+'images/markers/map_icon_peak_small.png');
		// These appear to be out of date
		//map_client.addMarkerIcon('River', map_client.path+'images/markers/map_icon_river.png');
		//map_client.addMarkerIcon('Pass', map_client.path+'images/markers/map_icon_pass.png');
		
		//map_client.addMarkerIcon('North', map_client.path+'images/markers/map_icon_north.png');
		//map_client.addMarkerIcon('North/East', map_client.path+'images/markers/map_icon_NE.png');
		//map_client.addMarkerIcon('East', map_client.path+'images/markers/map_icon_east.png');
		//map_client.addMarkerIcon('South/East', map_client.path+'images/markers/map_icon_SE.png');
		//map_client.addMarkerIcon('South', map_client.path+'images/markers/map_icon_south.png');
		//map_client.addMarkerIcon('South/West', map_client.path+'images/markers/map_icon_SW.png');
		//map_client.addMarkerIcon('West', map_client.path+'images/markers/map_icon_west.png');
		//map_client.addMarkerIcon('North/West', map_client.path+'images/markers/map_icon_NW.png');
		
		//map_client.addMarkerIcon('Arrow N', map_client.path+'images/markers/map_icon_arrow_north.png');
		//map_client.addMarkerIcon('Arrow N/E', map_client.path+'images/markers/map_icon_arrow_north_east.png');
		//map_client.addMarkerIcon('Arrow E', map_client.path+'images/markers/map_icon_arrow_east.png');
		//map_client.addMarkerIcon('Arrow S/E', map_client.path+'images/markers/map_icon_arrow_south_east.png');
		//map_client.addMarkerIcon('Arrow S', map_client.path+'images/markers/map_icon_arrow_south.png');
		//map_client.addMarkerIcon('Arrow S/W', map_client.path+'images/markers/map_icon_arrow_south_west.png');
		//map_client.addMarkerIcon('Arrow W', map_client.path+'images/markers/map_icon_arrow_west.png');
		//map_client.addMarkerIcon('Arrow N/W', map_client.path+'images/markers/map_icon_arrow_north_west.png');
		
		map_client.addMarkerIcon('Arrow N', map_client.path+'images/markers/map_icon_arrow_north.png');
		map_client.addMarkerIcon('Arrow N/NE', map_client.path+'images/markers/map_icon_arrow_nne.png');
		map_client.addMarkerIcon('Arrow N/E', map_client.path+'images/markers/map_icon_arrow_north_east.png');
		map_client.addMarkerIcon('Arrow E/NE', map_client.path+'images/markers/map_icon_arrow_ene.png');
		map_client.addMarkerIcon('Arrow E', map_client.path+'images/markers/map_icon_arrow_east.png');
		map_client.addMarkerIcon('Arrow E/SE', map_client.path+'images/markers/map_icon_arrow_ese.png');
		map_client.addMarkerIcon('Arrow S/E', map_client.path+'images/markers/map_icon_arrow_south_east.png');
		map_client.addMarkerIcon('Arrow S/SE', map_client.path+'images/markers/map_icon_arrow_sse.png');
		map_client.addMarkerIcon('Arrow S', map_client.path+'images/markers/map_icon_arrow_south.png');
		map_client.addMarkerIcon('Arrow S/SW', map_client.path+'images/markers/map_icon_arrow_ssw.png');
		map_client.addMarkerIcon('Arrow S/W', map_client.path+'images/markers/map_icon_arrow_south_west.png');
		map_client.addMarkerIcon('Arrow W/SW', map_client.path+'images/markers/map_icon_arrow_wsw.png');
		map_client.addMarkerIcon('Arrow W', map_client.path+'images/markers/map_icon_arrow_west.png');
		map_client.addMarkerIcon('Arrow W/NW', map_client.path+'images/markers/map_icon_arrow_wnw.png');
		map_client.addMarkerIcon('Arrow N/W', map_client.path+'images/markers/map_icon_arrow_north_west.png');
		map_client.addMarkerIcon('Arrow N/NW', map_client.path+'images/markers/map_icon_arrow_nnw.png');
		
		map_client.addMarkerIcon('Pass Small N/S', map_client.path+'images/markers/map_icon_pass_small_n_s.png');
		map_client.addMarkerIcon('Pass Small NNE/SSW', map_client.path+'images/markers/map_icon_pass_small_nne_ssw.png');
		map_client.addMarkerIcon('Pass Small NE/SW', map_client.path+'images/markers/map_icon_pass_small_ne_sw.png');
		map_client.addMarkerIcon('Pass Small ENE/WSW', map_client.path+'images/markers/map_icon_pass_small_ene_wsw.png');
		map_client.addMarkerIcon('Pass Small E/W', map_client.path+'images/markers/map_icon_pass_small_e_w.png');
		map_client.addMarkerIcon('Pass Small ESE/WNW', map_client.path+'images/markers/map_icon_pass_small_ese_wnw.png');
		map_client.addMarkerIcon('Pass Small SE/NW', map_client.path+'images/markers/map_icon_pass_small_se_nw.png');
		map_client.addMarkerIcon('Pass Small SSE/NNW', map_client.path+'images/markers/map_icon_pass_small_sse_nnw.png');
		
		map_client.addMarkerIcon('Pass LARGE N/S', map_client.path+'images/markers/map_icon_pass_large_n_s.png');
		map_client.addMarkerIcon('Pass LARGE NNE/SSW', map_client.path+'images/markers/map_icon_pass_large_nne_ssw.png');
		map_client.addMarkerIcon('Pass LARGE NE/SW', map_client.path+'images/markers/map_icon_pass_large_ne_sw.png');
		map_client.addMarkerIcon('Pass LARGE ENE/WSW', map_client.path+'images/markers/map_icon_pass_large_ene_wsw.png');
		map_client.addMarkerIcon('Pass LARGE E/W', map_client.path+'images/markers/map_icon_pass_large_e_w.png');
		map_client.addMarkerIcon('Pass LARGE ESE/WNW', map_client.path+'images/markers/map_icon_pass_large_ese_wnw.png');
		map_client.addMarkerIcon('Pass LARGE SE/NW', map_client.path+'images/markers/map_icon_pass_large_se_nw.png');
		map_client.addMarkerIcon('Pass LARGE SSE/NNW', map_client.path+'images/markers/map_icon_pass_large_sse_nnw.png');
		
	/* CONFIG - END */
	
	
	map_client.wrapper_id = wrapper_id;
	map_client.map_id = map_id;
	
	if(map_client.googleMapsApiLoaded == false){
		var script = document.createElement("script");
		script.setAttribute("src", "http://maps.google.com/maps?file=api&v=2.x&key="+_map_client_api_key+"&c&async=2&callback=map_client.attachGmap");
		script.setAttribute("type", "text/javascript");
		document.documentElement.firstChild.appendChild(script);
		map_client.googleMapsApiLoaded = true;
	}
	
};
