var zoomMax = 20;
var zoomMin = 0;
var allShape = [];
var layers = [];
var layersOk = [];
var currentDest = '';
var currentStart = '';
var currentDestLatLon = '';
var map = false;
var onRolle = false;


function VE_startMap(id, lat, lng, zoom, mt, sz){

	var position = new VELatLong(lat,lng);
	map = new VEMap(id);

   if (sz){
      map.SetDashboardSize(sz);
   }

	map.LoadMap(position, zoom , mt ,false);
   var url = new String(document.location);

   if (($('#'+id).width()>410) && (url.indexOf('sanmartinobooking')==-1)){
      map.SetMapStyle(VEMapStyle.Shaded);
   }



	map.AttachEvent("onendzoom", ve_OnZoom);

//	map.AttachEvent("onclick", function(e){if (e.elementID){map.ShowInfoBox(map.GetShapeByID(e.elementID));}});
//	map.AttachEvent("onmouseover", function(e){if (e.elementID){return true}});



   var newControl = $('#MSVE_navAction_AerialMapStyle').clone().insertAfter($('#MSVE_navAction_AerialMapStyle'));
   newControl
      .click(function(){map.SetCenterAndZoom(new VELatLong(lat, lng), zoom)})
      .html('Primiero')
      .css({color:'#00ff00', fontWeight:'bold'});

//	VE_addPoly([]);

	if ($.isFunction(getHowToGet)){
		var how = getHowToGet();
		if (how != false){
			currentStart = how.from;
			currentDest = how.to;

			$('#VE_route').html('<p style="text-align:center;margin-top:10px"><img src="/media/booking/img/loader.gif"><br/>Attendere, caricamento delle indicazioni in corso...</p>');
			var options = new VERouteOptions();
			options.RouteCallback = VE_onGetRoute;
			options.DistanceUnit = VERouteDistanceUnit.Kilometer;
			options.RouteOptimize = VERouteOptimize.MinimizeTime;
			map.GetDirections([how.from, how.to], options);
		}
	}

}

// On Zoom
function ve_OnZoom(e){
	if(map.GetZoomLevel() > zoomMax) {
		map.SetZoomLevel(zoomMax);
	} else if(map.GetZoomLevel() < zoomMin) {
		map.SetZoomLevel(zoomMin);
	}
}

// Add point
function VE_addPoint(options, layerName){
	var id = (options.lat+'_'+options.lng).replace(/\./g,'');

	if (options.showGetRoute){
		options.description +=
		'<form onsubmit="return VE_getRoute(\''+$.trim(options.title)+'\',\''+id+'\', '+options.lat+','+options.lng+')"><p>'+
		'Come arrivare qui da: '+
		'<input type="text" id="VE_from_'+id+'" value="">'+
		'<input type="hidden" id="VE_to_'+id+'" value="'+options.title+'">'+
		'<input type="submit" value="Cerca">'+
		'</p></form>';
	}



	var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(options.lat,options.lng));
	shape.SetTitle(options.title);
	shape.SetDescription(options.description);
	shape.SetCustomIcon('<img src="'+options.icon+'"/>');
	layers[layerName].AddShape(shape);
	allShape[id] = shape;



}


function VE_addLayer(l){
	if ($.inArray(l, layersOk)==-1){
		layersOk.push(l);
		layers[l] = new VEShapeLayer();
		map.AddShapeLayer(layers[l]);
	}
}

function VE_addPolylines(array){
	if (array.length > 0){
		for (var i in array){
			if (typeof(array[i]) =='object'){
				VE_addLayer(array[i]['layer']);
				VE_addPolyline(array[i], array[i]['layer']);
			}
		}
	}

}

// Add points
function VE_addPoints(array){
	if (array.length > 0){
		for (var i in array){
			if (typeof(array[i]) =='object'){
				VE_addLayer(array[i]['layer']);
				VE_addPoint(array[i], array[i]['layer']);
			}
		}
	}

}

function VE_addPolyline(options, layerName){

	var id = (options.lat+'_'+options.lng).replace(/\./g,'');

	//new VELatLong(46.35815,11.77438), new VELatLong(46.35493,11.77743), new VELatLong( 46.34971, 11.78067), new VELatLong( 46.34896, 11.78327)];
	var coords=[];
	for (var i=0 ; i< options.points.length-1; i+=2){
		coords.push( new VELatLong(parseFloat(options.points[i]) ,parseFloat(options.points[i+1])) );
	}
	var shape = new VEShape(VEShapeType.Polyline, coords);


	shape.SetLineWidth(3);
	shape.SetLineColor(new VEColor( parseInt(options.color.substr(0,2), 16), parseInt(options.color.substr(2,2), 16), parseInt(options.color.substr(4,2), 16),.7));
	shape.SetTitle(options.title);
	shape.SetDescription(options.description);



	if (options.icon =='')
		shape.HideIcon();
	else
		shape.SetCustomIcon("<img src='"+options.icon+"'/>");

	layers[layerName].AddShape(shape);
	allShape[id] = shape;



}

function VE_showPoint(lat, lng, zoom){
	var id = (lat+'_'+lng).replace(/\./g,'');
	map.SetCenterAndZoom (new VELatLong(lat,lng),zoom == undefined ? zoomMax : zoom);


	setTimeout('map.ShowInfoBox(allShape["'+id+'"]);',1000);
}


function VE_getRoute(title, id, toLat, toLng){
   onRolle = false;
	currentStart = $('#VE_from_'+id).attr('value');
	currentDest = $('#VE_to_'+id).attr('value');
	currentDestLatLon = new VELatLong(toLat, toLng);

	$('#VE_route').html('<p style="text-align:center;margin-top:10px"><img src="/media/booking/img/loader.gif"><br/>Attendere, caricamento delle indicazioni in corso...</p>');
	var options = new VERouteOptions();
	options.RouteCallback = VE_onGetRoute;
	options.DistanceUnit = VERouteDistanceUnit.Kilometer;
	options.RouteOptimize = VERouteOptimize.MinimizeTime;
	map.GetDirections([currentStart, new VELatLong(toLat,toLng)], options);

	return false;
}


function VE_showRoute(from, to){
	currentStart = from;
	currentDest = to;

	var options = new VERouteOptions();
	options.RouteCallback = VE_onGetRoute;
	options.DistanceUnit = VERouteDistanceUnit.Kilometer;
	options.RouteOptimize = VERouteOptimize.MinimizeTime;
	map.GetDirections([from, to], options);
}


function VE_onGetRoute(route){
	// Unroll route

   // Se vengono da sotto rolle  faccio passare per lo schener
   if (!onRolle && (route.Distance.toFixed(1)>100) && (route.RouteLegs[0].StartLocation.Latitude  < 46.2625)){
      onRolle = true;
      var options = new VERouteOptions();
      options.RouteCallback = VE_onGetRoute;
      options.DistanceUnit = VERouteDistanceUnit.Kilometer;
      map.GetDirections([currentStart, new VELatLong(46.00145677808114,11.807160253789647), currentDestLatLon != '' ? currentDestLatLon : currentDest], options);
      return;
   }


	var legs     = route.RouteLegs;
	var turns    = "<h2>Da "+currentStart.replace(/^([a-z])|\s+([a-z])/g, function ($1) {return $1.toUpperCase();})+" a "+currentDest+"</h2>"+
                  "<p><strong>Distanza totale: " + route.Distance.toFixed(1) + " km</strong><br/>"+
                  "Le indicazioni sono generate automaticamente e potrebbero essere soggette ad errori<br /> &nbsp;</p>"+
                  "<ul class='lines'>";

	var numTurns = 0;
	var leg      = null;

	for(var i = 0; i < legs.length; i++){
		 leg = legs[i];
		 var turn = null;

		 for(var j = 0; j < leg.Itinerary.Items.length; j ++){
				turn = leg.Itinerary.Items[j];
				turns += '<li>'+
					'<a href="#VE_map" onclick="VE_showPoint('+turn.LatLong.Latitude+','+turn.LatLong.Longitude+', 17)">'+
						numTurns + '. ' +
                  turn.Text + " (" + turn.Distance.toFixed(1) + " km)"+
					"</a> " +

				"</li>";
				numTurns++;
		 }
	}
	turns+="</ul>";
	$('#VE_route').slideUp('normal', function(){
		$(this).html(turns).slideDown('normal');
	})
}


$(function(){VE_getDirections();});

function VE_getDirections(){

   if (map == false){
      setTimeout(VE_getDirections, 500);
      return;
   }

   var url = new String(document.location);


   var pos = url.indexOf('#');
   if (pos ==-1){
      return;
   }
   data = url.split('#');

   data = data[1];

   if (data == 'VE_map'){
      return;
   }



   document.location.hash = 'VE_map';

   data = url_decode(data);

   data = data.split('|');

   VE_showRoute(data[1], data[0]);





/*
         if ($this->input->post('VE_from') && $this->input->post('VE_to')){
            $from = str_replace('"',"'",$this->input->post('VE_from'));
            $to = str_replace(array('"','\\'),' ',$this->input->post('VE_to'));

            $data['head'].= '<script type="text/javascript">$(function(){VE_showRoute("'.$from.'","'.$to.'")});</script>';
         }
*/
}

	function url_decode(utftext) {
      utftext = unescape(utftext);
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

