$(document).ready(function(){
	
	$('#roadMap, #tripMeta').html('');

	var 
		mm = Microsoft.Maps,
		map = new mm.Map(document.getElementById("roadMap"), {
			credentials:"ArQmo7ojoU4kwB5ZsgpGuO5B0UfIO8BpSeIhmYSo5hw2XYQIeQEua-cOqoLmy9SM", 
			width:100, 
			height:100, 
			center: new mm.Location(46.60, 2.46),
			enableClickableLogo: false,
			enableSearchLogo: false,
			showDashboard: false,
			showMapTypeSelector: false,
			tileBuffer: 3
		});
		
	$('#roadTrip').bind('resizeArea', function(){
		$('.map', this)
			.width(
				$(window).width() - 18 - $('#roadTrip .meta').outerWidth()
			)
			.height(
				$('#roadTrip .meta').height()
			);
		var viewOpts = {
			width: $('#roadTrip .map').width(),
			height: $('#roadTrip .map').height(),
			bounds: Microsoft.Maps.LocationRect.fromCorners(new Microsoft.Maps.Location(52.32, -1.43), new Microsoft.Maps.Location(43.2, 7.7))
		};
		map.setView(viewOpts);
	}).trigger('resizeArea');
	
	$(window).resize(function(){
		$('#roadTrip').trigger('resizeArea');
	});
	
	$.ajax({
		dataType:'json',	
		url: '/wp-content/custom/js/franceroadtrip/tripdata.js',
		success: function(data){
						
			$('#tripMeta').append('<ul>');
			
			for(var i=0; i<data.length; i++){
				$('#tripMeta ul').append('<li color="'+data[i].color+'" rel="'+data[i].route+'"><h3><span style="float:left; border:1px solid #000; height:10px; width:10px; display:block; margin:3px 8px 0 0; background:rgba('+data[i].color+')"></span><span style="float:left;">'+data[i].title+'</span><span class="clearme"></div></h3><p>'+data[i].description+'</p>');
			}
			$('#roadTrip').trigger('resizeArea');
			
			$('#tripMeta ul li').each(function(){
				$.ajax({
					dataType:'jsonp',
					jsonp:'jsonp',	
					url: $(this).attr('rel'),
					extra: $(this).attr('rel'),
					success: function(result){
						var rel = this.extra;
						var elem = $('#tripMeta li[rel="'+rel+'"]');
						var col = elem.attr('color').split(',');
						
						if (result &&
							   result.resourceSets &&
							   result.resourceSets.length > 0 &&
							   result.resourceSets[0].resources &&
							   result.resourceSets[0].resources.length > 0) {
							
							$(elem).append('<p><em>'+( parseFloat(result.resourceSets[0].resources[0].travelDistance).toFixed(1) )+' km</em></p>');
							$('#roadTrip').trigger('resizeArea');
							
							/*display the line */
							var routeline = result.resourceSets[0].resources[0].routePath.line;
							var routepoints = new Array();
						     
							for (var i = 0; i < routeline.coordinates.length; i++) {
								routepoints[i]=new mm.Location(routeline.coordinates[i][0], routeline.coordinates[i][1]);
							}
						     								
							// Draw the route on the map
							 var routeshape = new mm.Polyline(routepoints, {strokeColor:new mm.Color(col[3],col[0],col[1],col[2])});
							map.entities.push(routeshape);
								   
						}
					}
				});
			});
			
		}
		
	});
	
});
