var countryMapViewer = new Object();

countryMapViewer.ajaxUrl = '/profiles/1915_KE_Adventure/scripts/countryMapEditor/ajax.php';

countryMapViewer.create = function(elemId, countryId){
	
	var url = location.href;
	url = url.split('/');
	
	if(url[2] == 'ke.proof.server5.artavia.co.uk'){
		countryMapViewer.apiKey = 'ABQIAAAAF-8FI9pV89EsIWypB45cKBSMuZGgP-_DnhK4o4ozYrLTFsSBJxQuw7fI8I2JYXEyVdjTfSRJh2mxXA';
	}
	else if(url[2] == 'keadventure.com' || url[2] == 'www.keadventure.com'){
		countryMapViewer.apiKey = 'ABQIAAAAF-8FI9pV89EsIWypB45cKBRMiyjzYOGLwC0mgW1P_wKJPt3TnxSiBCO0HgeUZWTXjem09jsisA_V3w';
	}
	else if(url[2] == 'keadventure.co.uk' || url[2] == 'www.keadventure.co.uk'){
		countryMapViewer.apiKey = 'ABQIAAAAF-8FI9pV89EsIWypB45cKBTJ9ixfPiv8N21lqRfSn79JXOZGrxRdNUn3_vRfp8BZwYGGW22r6QVrsA';
	}
	
	//countryMapViewer.apiKey = 'ABQIAAAAp_UQq7E0wZ2pvu4XiXxuqRRLFuMbXE3lvrRvdJCVkCkWpjsjVhQfMmueVsKz5_DrgF537pOYfT-xbw';
	
	$('#'+elemId).html('<p>Loading country map...</p>');
	
	//$('#'+elemId).after('<div id="mapDebug">' + countryMapViewer.apiKey + '</div>');
	$('#mapDebug').css('display', 'none');
	
	countryMapViewer.elemId = elemId;
	countryMapViewer.countryId = countryId;
	
	countryMapViewer.markers = new Array();
	
	countryMapViewer.activityStates = new Object();
	
	countryMapViewer.includeCSS();
	countryMapViewer.loadTemplate();
	
}

countryMapViewer.loadTemplate = function(){
	
	$.ajax({
		type: "GET",
		url: countryMapViewer.ajaxUrl,
		data: 'loadTemplate',
		success: function(html){
			
			$('#' + countryMapViewer.elemId).html(html);
			
			$('.countryMapViewer_activity_checkbox').each(function(){
				var id = countryMapViewer.getActivityId(this);
				countryMapViewer.activityStates[id] = true;
			});
			
			countryMapViewer.loadGmap();
		}
	});
}

countryMapViewer.loadGmap = function(){
	var script = document.createElement("script");
	script.setAttribute("src", "http://maps.google.com/maps?file=api&v=2.x&key="+countryMapViewer.apiKey+"&c&async=2&callback=countryMapViewer.loadMapMarkers");
	script.setAttribute("type", "text/javascript");
	document.documentElement.firstChild.appendChild(script);
}

countryMapViewer.getActivityId = function(elem){
	var id = $(elem).attr('id');
	id = id.replace('countryMapViewer_activity_checkbox_', '');	
	return countryMapViewer.stripPad(id);
}

countryMapViewer.stripPad = function(id){
	var idOut = '';
	
	var regex = /^0+/;
	var idOut = id.replace(regex, '');
	
	return parseInt(idOut);
}

countryMapViewer.attachGmap = function(){

	countryMapViewer.gmap = new GMap2(document.getElementById("countryMapViewer_map"));
	
	countryMapViewer.gmap.addMapType(G_PHYSICAL_MAP);
	countryMapViewer.gmap.setMapType(G_PHYSICAL_MAP);
	
	//countryMapViewer.gmap.addMapType(G_HYBRID_MAP);
	//countryMapViewer.gmap.setMapType(G_HYBRID_MAP);
	
	countryMapViewer.gmap.addControl(new GLargeMapControl());
	countryMapViewer.gmap.addControl(new GMapTypeControl());
	
   	countryMapViewer.centerMap();
	
	$('.countryMapViewer_activity_checkbox').click(countryMapViewer.selectActivity);
	$('.countryMapViewer_severity_checkbox').click(countryMapViewer.drawSelectedMarkers);
	
	$('.countryMapViewer_activity_checkbox:visible').each(function(){
		countryMapViewer.selectInitialActivities(this);
	});
}

countryMapViewer.selectInitialActivities = function(elem){
	
	if(typeof(elem.originalTarget) == 'object'){
		elem = elem.originalTarget;
	}
	else if(typeof(elem.currentTarget) == 'object'){
		elem = elem.currentTarget;
	}
		
	var id = countryMapViewer.getActivityId(elem);
	
	countryMapViewer.activityStates[id] = true;
	
	var src = $(elem).attr('src');
	src = src.replace('/off/', '/on/');
	$(elem).attr('src', src);

	$(elem).addClass('selected');
	
	countryMapViewer.drawSelectedMarkers();
}

countryMapViewer.selectActivity = function(elem){
	
	if(typeof(elem.originalTarget) == 'object'){
		elem = elem.originalTarget;
	}
	else if(typeof(elem.currentTarget) == 'object'){
		elem = elem.currentTarget;
	}
	
	if($(elem).hasClass('selected')){
		var id = countryMapViewer.getActivityId(this);
		if(id == ''){ return false; }
		
		countryMapViewer.activityStates[id] = false;
		
		var src = $(this).attr('src');
		src = src.replace('/on/', '/off/');
		$(this).attr('src', src);
		$(this).removeClass('selected');
	}
	else {
		var id = countryMapViewer.getActivityId(elem);
		countryMapViewer.activityStates[id] = true;
		
		var src = $(elem).attr('src');
		src = src.replace('/off/', '/on/');
		$(elem).attr('src', src);
		$(elem).addClass('selected');
	}
	
	countryMapViewer.drawSelectedMarkers();
}

countryMapViewer.deselectAllActivities = function(){							/*           Deselect all activities */
	$('.countryMapViewer_activity_checkbox').removeClass('selected');
	$('.countryMapViewer_activity_checkbox').each(function(){
		var src = $(this).attr('src');
		src = src.replace('/on/', '/off/');
		$(this).attr('src', src);
	})
	
	countryMapViewer.drawSelectedMarkers();
}

countryMapViewer.selectAllActivities = function(){								/*           Select all activities   */
	$('.countryMapViewer_activity_checkbox').addClass('selected');
	$('.countryMapViewer_activity_checkbox').each(function(){
		var src = $(this).attr('src');
		src = src.replace('/off/', '/on/');
		$(this).attr('src', src);
	})
	
	countryMapViewer.drawSelectedMarkers();
}

countryMapViewer.deselectAllSeverities = function(){
	$('.countryMapViewer_severity_checkbox').attr('checked','');
	countryMapViewer.drawSelectedMarkers();
}

countryMapViewer.selectAllSeverities = function(){
	$('.countryMapViewer_severity_checkbox').attr('checked','checked');
	countryMapViewer.drawSelectedMarkers();
}

countryMapViewer.centerMap = function(){
	countryMapViewer.gmap.setCenter(new google.maps.LatLng(countryMapViewer.lat, countryMapViewer.lng), countryMapViewer.zoom);
}

countryMapViewer.drawSelectedMarkers = function(){
	
	var markersInPlace = new Object();
	
	var severities = Object();
	
	$('.countryMapViewer_severity_checkbox').each(function(){       
		var codes = $(this).val();
		codes = codes.split(',');
		for(var i in codes){
			severities[codes[i]] = false;
		}
	});
	
	$('.countryMapViewer_severity_checkbox:checked').each(function(){       
		var codes = $(this).val();
		codes = codes.split(',');
		for(var i in codes){
			severities[codes[i]] = true;
		}
	});
	
	for(var i in countryMapViewer.markers){
		
		var marker = countryMapViewer.markers[i];
		
		if(typeof(marker.overlay) == 'object'){
			countryMapViewer.gmap.removeOverlay(marker.overlay);
		}
		
		var activityInt = countryMapViewer.stripPad(marker.activity);
		
		if( countryMapViewer.activityStates[activityInt] == true ){
			
			if(
				marker.lat != 0 &&
				marker.lng != 0 &&
				(
			    		typeof(severities[marker.grade]) == 'undefined' ||
					(typeof(severities[marker.grade]) == 'boolean' && severities[marker.grade] == true)
				) &&
				!markersInPlace[marker.lat+','+marker.lng]
			){
				markersInPlace[marker.lat+','+marker.lng] = true;
				
				var latLng = new google.maps.LatLng(marker.lat, marker.lng);
				
				var src = $('#countryMapViewer_activity_' + marker.activity + ' img').attr('src');
				src = src.replace('/on/','/off/');
				
				marker.icon = new GIcon();
				marker.icon.image = src;
				marker.icon.shadow = '';
				marker.icon.iconSize = new GSize(16, 16);
				marker.icon.iconAnchor = new GPoint(8, 8);
				
				marker.options = { title : marker.name, icon: marker.icon };
				
				marker.overlay = new GMarker(latLng, marker.options);
				marker.overlay.key = marker.key;
				
				if(marker.lat == marker.lat){ // Checks to see of marker.lat in NaN (for some reason NaN != NaN)
					countryMapViewer.gmap.addOverlay(marker.overlay);
									
					GEvent.addListener(marker.overlay, "click", function(overlay){
						countryMapViewer.markerInfo(this.key);
					});
				}
				
			}
		}
	}
}

countryMapViewer.markerInfo = function(key){
	var marker = countryMapViewer.markers[key];
	
	$('#countryMapViewer_markerInfo').remove();
	
	var map = $('#countryMapViewer_map');
	map.append('<div id="countryMapViewer_markerInfo"></div>');
	
	var markerInfo = $('#countryMapViewer_markerInfo');
	markerInfo.css('opacity', '0');
	markerInfo.css('display', 'block');
	
	var map_w = parseInt(map.width());
	var map_h = parseInt(map.height());
	
	var info_w = parseInt(markerInfo.width());
	var info_h = parseInt(markerInfo.height());
	
	var top = parseInt((map_h / 2) - (info_h / 2)) + 'px';
	var left = parseInt((map_w / 2) - (info_w / 2)) + 'px';
	
	markerInfo.css('top', top);
	markerInfo.css('left', left);
	
	markerInfo.append('<a id="countryMapViewer_markerInfo_close" href="javascript:;" onClick="countryMapViewer.markerInfoClose()" >Close</a>');
	
	markerInfo.append('<h3>'+marker.name+'</h3>');
	
	if(marker.image != ''){
		markerInfo.append('<img width="200" height="112" src="/images/ke_trips_uploads/'+marker.image+'" alt="'+marker.name+'" title="'+marker.name+'" />');
	}
	
	markerInfo.append('<div id="countryMapViewer_markerInfo_details"><div id="countryMapViewer_markerInfo_detailsInner">'+marker.html+'</div></div>')
	markerInfo.append('<ul id="countryMapViewer_markerInfo_links"></ul>');
	
	// /trip/3957/across-the-high-atlas/dates.html
	var url_details = '/trip/' + marker.trip.substring(6) + '/' + marker.url_name;
	
	var links = $('#countryMapViewer_markerInfo_links');
	links.append('<li><a href="'+url_details+'.html">View details</a></li>');
	links.append('<li><a href="'+url_details+'/map.html">View itinerary</a></li>');
	links.append('<li><a href="'+url_details+'/reviews.html">View reviews</a></li>');
	links.append('<li><a href="'+url_details+'/dates.html">View dates and availability</a></li>');
	
	markerInfo.fadeTo(250, 1);
}

countryMapViewer.markerInfoClose = function(){
	$('#countryMapViewer_markerInfo').fadeTo(250, 0, function(){
		$(this).remove();
	});
}

countryMapViewer.loadMapMarkers = function(){
	
	$.ajax({
		type: "GET",
		url: countryMapViewer.ajaxUrl,
		data: 'mode=getCountryMarkers&country=' + countryMapViewer.countryId,
		success: function(xml){
			
			$('#countryMapViewer_toolbar_inner').css('display','block');
			
			var map = $(xml).find('map:first');
			
			countryMapViewer.lat = parseFloat(map.attr('lat'));
			countryMapViewer.lng = parseFloat(map.attr('lng'));
			countryMapViewer.zoom = parseInt(map.attr('zoom'));
			
			$(xml).find('marker').each(function(){
				
				var key = countryMapViewer.markers.length;
				countryMapViewer.markers[key] = new Object();
				var marker = countryMapViewer.markers[key];
				
				marker.key = key;
				marker.trip = $(this).attr('trip');
				marker.name = $(this).attr('name');
				marker.url_name = $(this).attr('url_name');
				marker.country = $(this).attr('country');
				marker.html = $(this).text();
				marker.image = $(this).attr('image');
				
				marker.lat = parseFloat($(this).attr('lat'));
				marker.lng = parseFloat($(this).attr('lng'));
				
				marker.grade = $(this).attr('grade');
				marker.activity = $(this).attr('activity');
				
				if(marker.lat != 0 && marker.lng != 0){
					
					$('#countryMapViewer_activity_'+marker.activity).css('display', 'block');
					
					// Needs to be re-activated when grades are assigned to treks
					//$('.countryMapViewer_severity_'+marker.grade).css('display', 'block');
				}
				
			});
			
			// Preload marker images to avoid IE problems
			$('#countryMapViewer_activities img').each(function(){
				var src = $(this).attr('src');
				src = src.replace('/on/','/off/');
				$('<img>').attr('src', src);
			});
			
			countryMapViewer.attachGmap();
			
		}
	});
	
}

countryMapViewer.includeCSS = function(){
	var headID = document.getElementsByTagName("head")[0];         
	var cssNode = document.createElement('link');
	cssNode.type = 'text/css';
	cssNode.rel = 'stylesheet';
	cssNode.href = '/scripts/countryMapEditor/viewer.css';
	cssNode.media = 'screen';
	headID.appendChild(cssNode);
}
