var ilcl_route_planned = false;
var ilcl_color2 = "";

function SetCookie(cookieName,cookieValue,nDays) {
 var today = new Date();
 var expire = new Date();
 if (nDays==null || nDays==0) nDays=1;
 expire.setTime(today.getTime() + 3600000*24*nDays);
 document.cookie = cookieName+"="+escape(cookieValue)
                 + ";expires="+expire.toGMTString();
}


function getQuery(ji) {
	hu = window.location.search.substring(1);
	gy = hu.split("&");
	for (i=0;i<gy.length;i++) {
		ft = gy[i].split("=");
			if (ft[0] == ji) {
				return unescape(ft[1]);
			}
	}
	return false;
}


var country = 'NL';
var ilcl_country = 'NL';
var lang = 'nl';

if (getQuery('companyName')) {
	var ilcl_companyName = getQuery('companyName');
	var ilcl_addressLine1 = getQuery('addressLine1');
	var ilcl_addressLine2 = getQuery('addressLine2');
	var ilcl_destination = getQuery('dest');
	var ilcl_rest = getQuery('rest');
	if (ilcl_rest.indexOf("false") < 0) {
		ilcl_rest = ilcl_rest.replace(/,NL/, "");
	} 
	var ilcl_rwidth = getQuery('w');
	var ilcl_rheight = getQuery('h');
	var ilcl_color = getQuery('clr');
	
}



var closestZip = ilcl_addressLine2;
var curAdres = ''
var curZip = ilcl_companyName;
var map = null;
var mainShape = null;
var myToLoc = null;
var curDest = "";
var ypos = '';
var xpos = ''; 
var index = 0;  
var numResults = 5;
   

   
   
function FindResult(layer, resultsArray, places, hasMore, veErrorMessage)
{
		var ll = map.GetCenter();
		ypos = ll.Latitude;
      	xpos = ll.Longitude;
 	
 		map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);
		map.Hide3DNavigationControl();
		//map.ClearInfoBoxStyles();
		map.SetMouseWheelZoomToCenter(false);

		myToLoc = new VELatLong(ypos/60,xpos/60);
		
      var mainShape = new VEShapeLayer();
      map.AddShapeLayer(mainShape);

		txtTitle = ilcl_companyName + "<br>" + ilcl_addressLine1 + "<br>" + ilcl_addressLine2;
		AddPin(mainShape,ypos,xpos,txtTitle);
		
		document.getElementById("MSVE_navAction_RoadMapStyle").innerHTML = "Kaart";
		document.getElementById("MSVE_navAction_AerialMapStyle").innerHTML = "Satelliet";
		document.getElementById("MSVE_obliqueNotifyText").innerHTML = "Bekijk in birds eye view";
		document.getElementById("MSVE_navAction_RoadMapStyle").setAttribute("title", "Kaart weergeven");
		document.getElementById("MSVE_navAction_AerialMapStyle").setAttribute("title", "Satellietbeelden weergeven");
		document.getElementById("MSVE_navAction_toggleGlyphWrapper").setAttribute("title", "Menu inklappen");
		//document.getElementById("MSVE_obliqueCompassContainer").setAttribute("title", "Verander de richting");
		document.getElementById("MSVE_navAction_tinyZoomBar_plus").setAttribute("title", "Inzoomen");
		document.getElementById("MSVE_navAction_tinyZoomBar_minus").setAttribute("title", "Uitzoomen");
		document.getElementById("MSVE_navAction_ccw").setAttribute("title", "roteer naar links");
		document.getElementById("MSVE_navAction_cw").setAttribute("title", "roteer naar rechts");
		document.getElementById("Compass").setAttribute("title", "Beweeg in elke richting");

		if(ilcl_destination) {
			getRoute(getQuery('dest'))	
		}	
}
   
function GetMap() {
	curAdres = ilcl_addressLine1 + "<br />" + ilcl_addressLine2;
    map = new VEMap('myMap');

    //map.AttachEvent("oninitmode", mapLoad);
	//map.SetCenterAndZoom(new VELatLong(ypos/60,xpos/60), 16);

	map.LoadMap();
	map.Find(null,ilcl_addressLine1 + ',' + ilcl_addressLine2 + ',' + ilcl_rest,null,null,index,numResults,true,true,true,true,FindResult);
	map.SetZoomLevel(10);
	
}


function getRoute(dest) {
	if (!dest) {
		txtFrom = document.getElementById('ilcl_fr').value;
	} else {
		txtFrom = dest;	
	}
	
	curDest = txtFrom;
	var Routeoptions = new VERouteOptions;
   	Routeoptions.DrawRoute = true;
   	Routeoptions.SetBestMapView = true;
   	Routeoptions.RouteCallback = showDirections;
   	Routeoptions.DistanceUnit = VERouteDistanceUnit.Kilometer;
   	Routeoptions.ShowDisambiguation = false;
   	Routeoptions.UseMWS = false;
	map.GetDirections([txtFrom, new VELatLong(ypos,xpos)], Routeoptions);
}


function GetCenterLatLong() {
    //Check if in Birdseye or Oblique Map Style
    if (map.GetMapStyle() == VEMapStyle.Birdseye || map.GetMapStyle() == VEMapStyle.BirdseyeHybrid)
    {
        //IN Birdseye or Oblique Map Style
        //Get the BirdseyeScene being displayed
        var birdseyeScene = map.GetBirdseyeScene();


        //Get approximate center coordinate of the map
        var x = birdseyeScene.GetWidth() / 2;
        var y = birdseyeScene.GetHeight() / 2;

        // Get the Lat/Long 
        var center = birdseyeScene.PixelToLatLong(new VEPixel(x,y), map.GetZoomLevel());

        // Convert the BirdseyeScene LatLong to a normal LatLong we can use
        return (new _xy1).Decode(center);
    }
    else
    {
        // NOT in Birdseye or Oblique Map Style
        return map.GetCenter();
    }
} 

function DisplayCenter()
{
    var center = GetCenterLatLong(); 
    alert("Latitude: " + center.Latitude + "\nLongitude: " + center.Longitude);
}

function AddPin(mainShape,myLat,myLong,txtTitle) {
	icon = "<span><img src='http://www.ilocal.nl/widgets/routeplanner/images/nrsmap.gif'></span>";
	var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(ypos,xpos));
	shape.SetCustomIcon(icon);
	shape.SetTitle(txtTitle);
	mainShape.AddShape(shape);
}

function showDirections(route){
 var legs = route.RouteLegs;
    if(!ilcl_destination) {
    	var turns = "<table width='" + (ilcl_rwidth - 37) + "'>";
   	} else { 
    	var turns = "<table width='745'>";
    }
    var leg = null;
    var turnNum = 0;
    var totalDistance = 0;
    var totalTime = 0;
    var customIcon = "<img src=http://www.ilocal.nl/widgets/routeplanner/images/spacer.gif>";


    legs[0].Itinerary.Items[0].Shape.SetCustomIcon(customIcon);
    legs[legs.length-1].Itinerary.Items[legs[legs.length-1].Itinerary.Items.length-1].Shape.SetCustomIcon(customIcon);

    for(var i = 0; i < legs.length; i++){
		leg = legs[i];
        var turn = null;
        var legDistance = null;
        var legTime = null;
        var distanceIncrement = 0;

        for(var j = 0; j < leg.Itinerary.Items.length; j ++){
            turnNum++;
			turn = leg.Itinerary.Items[j];
			legDistance = turn.Distance;
			legTime = turn.Time;
			totalDistance += legDistance;
            totalTime += legTime;

            var showDistance = legDistance;
            if (showDistance < 1) {
            	showDistance = showDistance.toFixed(2) * 1000 + " m";
            } else {
            	showDistance = showDistance.toFixed(1) + " km";
            }
				
				if (j % 2) {
				txtClass = '';
				tmpstyle = "";
				} else {
				tmpstyle = "background-color:" + ilcl_color2 + ";";
				txtClass = 'row';
				}

            
			if(j==0) {
				turn.Shape.SetTitle("<b>Begin:</b>");
				turn.Shape.SetDescription(turn.Text.replace(/Vertrek uit   vanaf/g, "Vertrek vanaf"));
				turns += "<tr class='" + txtClass + "'><td style='" + tmpstyle + "'></td><td class='description' style='" + tmpstyle + "'><strong>"+turn.Text+"</strong></td><td align='right' style='" + tmpstyle + "'>Totale afstand</td></tr>";
			} else if(j==leg.Itinerary.Items.length-1) {
				turn.Shape.SetTitle("<b>Einde:</b>");
				turn.Shape.SetDescription("<b><font size=2>"+curAdres+"</font></b>"+"<br>"+ilcl_companyName);
				turns += "<tr class='" + txtClass + "'><td style='" + tmpstyle + "'></td><td class='description' style='" + tmpstyle + "'><strong>"+unescape(ilcl_companyName.replace(/<br>/,", "))+"</strong></td><td style='" + tmpstyle + "'></td></tr>";
			} else {
				turn.Shape.SetTitle("<b>Stap</b>"+(j)+"<b>:</b>");//j need to change if we have more via points.
				turns += "<tr class='" + txtClass + "'><td class='nr' style='" + tmpstyle + ";color:#000000'>"+j+".</td><td class='description' style='" + tmpstyle + "'>"+turn.Text+" ("+showDistance+")</td><td align='right' style='" + tmpstyle + "'>"+totalDistance.toFixed(1)+" km</td></tr>";
			}
		}
	}
	
	turns += "</table>";
	totalTime = totalTime/60;
	turns += "";
    turns += "<p><b>Totale afstand: </b>" + totalDistance.toFixed(1) + " km</p>";
    if(totalTime >= 60){
    	turns += "<p><b>Totale tijd: </b>" + Math.floor(totalTime/60) + " uur " + Math.ceil(totalTime%60) + " min</p>";
    }
    else{
    	turns += "<p><b>Totale tijd: </b>" + Math.ceil(totalTime) + " min</p>";
    }

    setDirections(turns);
}

function setDirections(directionInfo){
	
	map.SetZoomLevel(map.GetZoomLevel()+1);
	
	//ilcl_route_select()
	document.getElementById('route_description').innerHTML = directionInfo;
	
	ilcl_route_planned = true;
	
	
	if(ilcl_destination) {
		window.print();	
	}
}



var pclick = false;
function ilcl_setHeight(w,h) {
	//alert('ck');
	
	ilcl_map_obj = document.getElementById('myMap');
	ilcl_route_obj = document.getElementById('route_description');
	ilcl_print_obj = document.getElementById('route_printbutton');
	
	rmapwidth = w - 22;
	rmapheight = h - 90;

	ilcl_map_obj.style.width = (rmapwidth) + 'px';
	ilcl_map_obj.style.height = (rmapheight) + 'px';
	
	ilcl_route_obj.style.width = (rmapwidth+1) + 'px';
	ilcl_route_obj.style.height = (rmapheight-4) + 'px';
	ilcl_route_obj.style.marginTop = '-' + (rmapheight-20) + 'px';
	
	ilcl_print_obj.style.width = (rmapwidth+1) + 'px';
	ilcl_print_obj.style.marginTop = '-' + (rmapheight+1) + 'px';
	
}

function ilcl_map_select() {
	document.getElementById("route_description").style.display = 'none';
	document.getElementById("route_printbutton").style.display = 'none';
	document.getElementById("ilcl_button1").className = 'ilcl_button ilcl_button_selected';
	document.getElementById("ilcl_button2").className = 'ilcl_button';;

}

function ilcl_route_select() {
	if (ilcl_route_planned) {	
		document.getElementById("route_description").style.display = 'block';
		document.getElementById("route_printbutton").style.display = 'block';
		document.getElementById("ilcl_button2").className = 'ilcl_button ilcl_button_selected';
		document.getElementById("ilcl_button1").className = 'ilcl_button';
	} else {
		alert('Plan uw route door eerst uw vertrekpunt in te vullen');	
	}
}


function HexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function HexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function HexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}

function ilcl_colors() {
	clr_r = HexToR(ilcl_color);
	clr_g = HexToG(ilcl_color);
	clr_b = HexToB(ilcl_color);
	//str = "rgb(" + clr_r + "," + clr_g + "," + clr_b + ");";
	clr_r = (clr_r) + Math.round((255 - clr_r) * (80 / 100));
	clr_g = (clr_g) + Math.round((255 - clr_g) * (80 / 100));
	clr_b = (clr_b) + Math.round((255 - clr_b) * (80 / 100));
	ilcl_color2 = "rgb(" + clr_r + "," + clr_g + "," + clr_b + ");";
}

function ilcl_init() {
	ilcl_colors();
	ilcl_setHeight(ilcl_rwidth,ilcl_rheight);
	document.body.style.backgroundColor = ilcl_color;
	document.getElementById('ilcl_wdgt_table').style.backgroundColor = ilcl_color;
	GetMap(); 
}


