﻿var FindPathArray = new Array();
var PlaceStatusArray = new Array();
var PlaceToFindPathArray = new Array();
var PathPolylineArray = new Array();
var PlaceArray = new Array(0,0);
var currentIndex = -1;
var currentSub  = -1;
var currentFindtype = 0;
var isFinding = false;
var isChanging = false;
var isFPObjDragging = false;
var selectedPoly = null;
var currentStep = null;
var toFirstFlag = false;
function GetXmlHttpObject(handler)
{
	var objXmlHttp = null;
	if(navigator.userAgent.indexOf("Opera")>=0)
	{
		alert("Does not working in opera");
		return;
	}
	if(navigator.userAgent.indexOf("MSIE")>=0)
	{
		var strName = "Msxml2.XMLHTTP";
		if(navigator.appVersion.indexOf("MSIE 5.5")>=0)
		{
			strName = "Microsoft.XMLHTTP";
		}
	try{
		objXmlHttp = new ActiveXObject(strName);
		objXmlHttp.onreadystatechange = handler;
		return objXmlHttp;
		}
		catch(e) 
		
		{
			alert("Error. Scripting for ActiveX might be disabled") ;
			return ;
		}
	}
	if(navigator.userAgent.indexOf("Mozilla")>=0)
	{
		objXmlHttp = new XMLHttpRequest();
		objXmlHttp.onload = handler;
		objXmlHttp.onerror = handler;
		return objXmlHttp;
	}
};

function AddPlace()
{
    var index = PlaceArray.length;
    if(index > 25) return;
    var pathdiv = document.getElementById('findpath_div');
    var content = "";
    content +=  "<table width=100% border=0 cellspacing=0 cellpadding=0 style=\"overflow:auto; \">";
    content +=  "<tr><td align=right height=30 width=9%><img src=images/place_"+index+".gif></td><td align=left width=80%><input style=\"border: 1px solid rgb(153, 153, 153); background: rgb(255, 255, 255) url(images/helptimduong.gif) no-repeat scroll left center; width: 270px; margin-left: 5px; height: 17px; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; font-size:9pt;\" value='' onkeydown=\"SearchPlaceEnter(event,this)\" onchange=\"ChangeContent(this)\" onfocus=\"OnforcusTextBoxAB(this)\" onblur=\"OnblurTextBoxAB(this)\" type=\"text\"></td><td align=left width=11%><img style=\"cursor: pointer; margin-left: 2px;\" src=images/delete.gif onclick=\"ClickRemovePlaceButton(this)\" title=\"Xóa vị trí này\"></td>";
    content +=  "</tr>";
    content +=  "</table>";
    var direction = VUtil.CreateDivElement("direction" + index, "", "", "", "", "relative", "visible", content);
    pathdiv.appendChild(direction);
    var guide = VUtil.CreateDivElement("guide" + index, "", "", "", "", "relative", "visible", "");
    pathdiv.appendChild(guide);
    var buffer = VUtil.CreateDivElement("buffer" + index, "", "", "100%", "5px", "relative", "visible", "");
    pathdiv.appendChild(buffer);
    PlaceArray.push(0);
    
};

function AddPlaceToFind(latlng, text)
{
    var index = PlaceToFindPathArray.length;
    if(toFirstFlag == true)
    {
        toFirstFlag = false;
        index--;
    }
    if(PlaceToFindPathArray.length == 0)
    {
        index++;
        toFirstFlag = true;
    }
    if(index > 25 || isFinding == true) return;
    if(text == undefined)
        text = latlng.toString();
    var pathdiv = document.getElementById('findpath_div').childNodes[0];
    var direction = document.getElementById('direction'+index);
    var icon = new VIcon("images/place_map_"+index+".gif");
    icon.iconSize = new VSize(26, 29);
    var marker = new VMarker(latlng,icon);
    map.addOverlay(marker);
    marker.enableDragging();
    marker.sid = index+",0";
    marker.type = FPMARKEROBJ;
    VEvent.addListener(marker,'dragend',function(mk){
            isFPObjDragging = false;
            UpdateShortestPath(mk.sid);
        });
    VEvent.addListener(marker,'dragging',function(mk){
            isFPObjDragging = true;
            if (mkD != null)
            {
                map.removeOverlay(mkD);
                mkD = null;
            }
            ChangeShortestPath(mk.sid);
        });
    direction.childNodes[0].rows[0].cells[1].childNodes[0].value = text;
    OnforcusTextBoxAB(direction.childNodes[0].rows[0].cells[1].childNodes[0]);
    FindPathArray.push(1);
    PlaceStatusArray.push(1);
    var arr = new Array();
    arr.push(marker);
    PlaceToFindPathArray.push(arr);
    arr = new Array();
    arr.push(0);
    PathPolylineArray.push(arr);
    PlaceArray[index] = 1;
    if(PlaceToFindPathArray.length > 1)
        AddPlace();
    FindShortestPath(index+","+0,0,1);
};

function AddPlaceFromFind(latlng, text)
{
    var index = 0;
    if(index > 25 || isFinding == true) return;
    //if(PlaceToFindPathArray.length > 0 && latlng.equals(PlaceToFindPathArray[0][0].getLatLng())) return;
    if(text == undefined)
        text = latlng.toString();
    var pathdiv = document.getElementById('findpath_div');
    var icon = new VIcon("images/place_map_0.gif");
    icon.iconSize = new VSize(26, 29);
    var marker = new VMarker(latlng,icon);
    map.addOverlay(marker);
    marker.enableDragging();
    marker.sid = "0,0";
    marker.type = FPMARKEROBJ;
    VEvent.addListener(marker,'dragend',function(mk){
            isFPObjDragging = false;
            UpdateShortestPath(mk.sid);
        });
    VEvent.addListener(marker,'dragging',function(mk){
            isFPObjDragging = true;
            if (mkD != null)
            {
                map.removeOverlay(mkD);
                mkD = null;
            }
            ChangeShortestPath(mk.sid);
        });
    if(toFirstFlag == true)
    {
        toFirstFlag = false;
        var direction = document.getElementById('direction'+0);
        direction.childNodes[0].rows[0].cells[1].childNodes[0].value = text;
        OnforcusTextBoxAB(direction.childNodes[0].rows[0].cells[1].childNodes[0]);
        FindPathArray.push(0);
	    PlaceStatusArray.push(0);
	    PlaceArray[0] = 1;
	    var arr = new Array();
        arr.push(marker);
	    PlaceToFindPathArray.push(arr);
	    arr = new Array();
        arr.push(0);
        PathPolylineArray.push(arr);
        FindPathArray.reverse();
        PlaceStatusArray.reverse();
        PlaceToFindPathArray.reverse();
        AddPlace();
        FindShortestPath("0,0",0,1);
        return;
    }
    if(PlaceArray[0] == 0)
    {
        var direction = document.getElementById("direction0");
        direction.childNodes[0].rows[0].cells[1].childNodes[0].value = text;
        OnforcusTextBoxAB(direction.childNodes[0].rows[0].cells[1].childNodes[0]);
        FindPathArray.push(0);
	    PlaceStatusArray.push(0);
	    PlaceArray[0] = 1;
	    var arr = new Array();
        arr.push(marker);
	    PlaceToFindPathArray.push(arr);
	    arr = new Array();
        arr.push(0);
        PathPolylineArray.push(arr);
	    return;
    };
    for(var i=PlaceArray.length-1; i >= 0; i--)
    {
        var direction = document.getElementById("direction"+i);
        var guide = document.getElementById("guide"+i);
        var buffer = document.getElementById("buffer"+i);
        direction.childNodes[0].rows[0].cells[0].innerHTML = '<img src=images/place_'+(i+1)+'.gif />';
        direction.id = "direction"+(i+1);
        guide.id = "guide"+(i+1);
        buffer.id = "buffer"+(i+1);
        var ic = new VIcon("images/place_map_"+(i+1)+".gif");
        if(i < PlaceToFindPathArray.length)
        {
            for(var j=0; j<PlaceToFindPathArray[i].length; j++)
                PlaceToFindPathArray[i][j].sid = i+1+","+j;
            for(var j=0; j<PathPolylineArray[i].length; j++)
                PathPolylineArray[i][j].sid = (i+1)+","+j;
            PlaceToFindPathArray[i][0].setIcon(ic);
        }
    }
    FindPathArray.push(0);
	PlaceStatusArray.push(0);
	PlaceArray.push(0);
	PlaceToFindPathArray.push(marker);
	PathPolylineArray.push(new Array());
	for(var i=PlaceArray.length-1; i> 0; i--)
	{
	    if(i < PlaceToFindPathArray.length)
	    {
	        FindPathArray[i] = FindPathArray[i-1];
	        PlaceStatusArray[i] = PlaceStatusArray[i-1];
	        PlaceToFindPathArray[i] = PlaceToFindPathArray[i-1];
	        PathPolylineArray[i] = PathPolylineArray[i-1];
	     }
	     PlaceArray[i] = PlaceArray[i-1];
	}
	FindPathArray[0] = 0;
	PlaceStatusArray[0] = 1;
	var arr = new Array();
    arr.push(marker);
	PlaceToFindPathArray[0] = arr;
	arr = new Array();
    arr.push(0);
	PathPolylineArray[0] = arr;
	PlaceArray[0]= 1;
	var content = "";
    content +=  "<table width=100% border=0 cellspacing=0 cellpadding=0 style=\"overflow:auto; \">";
    content +=  "<tr><td align=right height=30 width=9%><img src=images/place_0.gif></td><td align=left width=82%><input style=\"border: 1px solid rgb(153, 153, 153); background: rgb(255, 255, 255) no-repeat scroll left center; width: 270px; margin-left: 5px; height: 17px; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; font-size:9pt;\" onkeydown=\"SearchPlaceEnter(event,this)\" onchange=\"ChangeContent(this)\" onfocus=\"OnforcusTextBoxAB(this)\" onblur=\"OnblurTextBoxAB(this)\" type=\"text\" value='"+text+"'></td><td align=left width=9%><img style=\"cursor: pointer; margin-left: 2px;\" src=images/delete.gif onclick=\"ClickRemovePlaceButton(this)\" title=\"Xóa vị trí này\"></td>";
    content +=  "</tr>";
    content +=  "</table>";
    var direction = VUtil.CreateDivElement("direction0", "", "", "", "", "relative", "visible", content);
    pathdiv.insertBefore(direction,document.getElementById('direction1'));
    var guide = VUtil.CreateDivElement("guide0", "", "", "", "", "relative", "visible", "");
    pathdiv.insertBefore(guide,document.getElementById('direction1'));
    var buffer = VUtil.CreateDivElement("buffer0", "", "", "100%", "5px", "relative", "visible", "");
    pathdiv.insertBefore(buffer,document.getElementById('direction1'));
	FindShortestPath("0,0",0,1);
};

function ClickRemovePlaceButton(element)
{
    /*var pathdiv = document.getElementById('findpath_div');
    var did = element.parentNode.parentNode.parentNode.parentNode.parentNode.id;
    var index = parseInt(did.substring(9,did.length));
    RemovePlace(index+",0");
    if(toFirstFlag == true)
        return;*/
    var pathdiv = document.getElementById('findpath_div');
    var did = element.parentNode.parentNode.parentNode.parentNode.parentNode.id;
    var index = parseInt(did.substring(9,did.length));
    var sid = index+",0";
    var tarr = sid.split(",");
    var index1  = parseInt(tarr[0]);
    var sub  = parseInt(tarr[1]);
    RemovePlace(index+",0");
    if(toFirstFlag == true)
        return;

};

function RemovePlace(sid, opts)
{   
    map.closeInfoWindow();
    var pathdiv = document.getElementById('findpath_div');
    var tarr = sid.split(",");
    var index  = parseInt(tarr[0]);
    var sub  = parseInt(tarr[1]);
    if(toFirstFlag == true && index == 1)
    {
        toFirstFlag = false;
        map.removeOverlay(PlaceToFindPathArray[0][0]);
        FindPathArray = new Array();
        PlaceStatusArray = new Array();
        PlaceToFindPathArray = new Array();
        PathPolylineArray = new Array();
        PlaceArray = new Array(0,0);
        var direction = document.getElementById("direction1");
        direction.childNodes[0].rows[0].cells[1].childNodes[0].value = "";
        OnblurTextBoxAB(direction.childNodes[0].rows[0].cells[1].childNodes[0]);
        return;
    }
    if(PlaceArray[index] == 0) return;
    if(sub > 0)
    {
        map.removeOverlay(PathPolylineArray[index][sub]);
        map.removeOverlay(PlaceToFindPathArray[index][sub]);
        for(var i=sub; i < PlaceToFindPathArray[index].length-1; i++)
        {
            PathPolylineArray[index][i] = PathPolylineArray[index][i+1];
            PathPolylineArray[index][i].sid = index+","+i;
            PlaceToFindPathArray[index][i] = PlaceToFindPathArray[index][i+1];
            PlaceToFindPathArray[index][i].sid = index+","+i;
        }
        PathPolylineArray[index].pop();
        PlaceToFindPathArray[index].pop();
        vbdmap.RemoveDirectionPlaces(GetPolylineOrder(index)+sub,1);
        FindShortestPath(index+",0",1,0,1);
        return;
    }
    if(opts != 1)
    {
    
        if(index == 0 && PlaceToFindPathArray.length > 1)
            vbdmap.RemoveDirectionPlaces(0,GetPolylineOrder(index+1));
        else if(index == PlaceToFindPathArray.length-1 && index > 0)
            vbdmap.RemoveDirectionPlaces(GetPolylineOrder(index-1), GetPolylineOrder(index)-GetPolylineOrder(index-1));
        else
            vbdmap.RemoveDirectionPlaces(GetPolylineOrder(index-1), GetPolylineOrder(index+1)-GetPolylineOrder(index-1)-1);
    }
    if(index > 0)
    {
        for(var i=PlaceToFindPathArray[index-1].length - 1; i >= 0; i--)
        {
            map.removeOverlay(PathPolylineArray[index-1][i]);
            PathPolylineArray[index-1].pop();
            if(i>0)
            {
                
                map.removeOverlay(PlaceToFindPathArray[index-1][i]);
                PlaceToFindPathArray[index-1].pop();
             }
        }
    }
    if(index < PlaceToFindPathArray.length - 1)
    {
        for(var i=PlaceToFindPathArray[index].length - 1; i >= 0; i--)
        {
            map.removeOverlay(PathPolylineArray[index][i]);
            PathPolylineArray[index].pop();
            map.removeOverlay(PlaceToFindPathArray[index][i]);
            PlaceToFindPathArray[index].pop();
        }
        
    }
    else if(index == PlaceToFindPathArray.length - 1)
    {
        map.removeOverlay(PlaceToFindPathArray[index][0]);
        PlaceToFindPathArray[index].pop();
    }
    if(PlaceArray.length == 2)
    {
        prev_selectedResAB_Text = "";
        PlaceArray[index] = 0;
        var direction = document.getElementById("direction0");
        direction.childNodes[0].rows[0].cells[1].childNodes[0].value = "";
        OnblurTextBoxAB(direction.childNodes[0].rows[0].cells[1].childNodes[0]);
    }
    else
    {
        var tindex = index;
        if(index == PlaceToFindPathArray.length - 1)
            tindex= index - 1;
        var direction = document.getElementById('direction'+index);
        var guide = document.getElementById('guide'+index);
        var buffer = document.getElementById('buffer'+index);
        pathdiv.removeChild(direction);
        pathdiv.removeChild(guide);
        pathdiv.removeChild(buffer);
        direction = document.getElementById('direction'+index);
        guide = document.getElementById('guide'+tindex);
        if(guide != null)
            guide.innerHTML = "";
        buffer = document.getElementById('buffer'+index);
    }
    
    for(var i=index; i< PlaceArray.length; i++)
    {
        var direction = document.getElementById('direction'+i);
        var guide = document.getElementById('guide'+i);
        var buffer = document.getElementById('buffer'+i);
        if(i >= index && PlaceArray.length > 2 && direction != null)
        {
            direction.childNodes[0].rows[0].cells[0].innerHTML = '<img src=images/place_'+(i-1)+'.gif />';
            direction.id = "direction"+(i-1);
            guide.id = "guide"+(i-1);
            buffer.id = "buffer"+(i-1);
        }
        if(i < PlaceToFindPathArray.length)
        {
            FindPathArray[i] = FindPathArray[i+1];
            PlaceStatusArray[i] = PlaceStatusArray[i+1];
            var ic = new VIcon("images/place_map_"+(i-1)+".gif");
            if(i != index)
                PlaceToFindPathArray[i][0].setIcon(ic);
            for(var j=0; j<PlaceToFindPathArray[i].length; j++)
                PlaceToFindPathArray[i][j].sid = (i-1)+","+j;
            for(var j=0; j<PathPolylineArray[i].length; j++)
                PathPolylineArray[i][j].sid = (i-1)+","+j;
            PlaceToFindPathArray[i] = PlaceToFindPathArray[i+1];
            PathPolylineArray[i] = PathPolylineArray[i+1];
            
        }
        //PlaceArray[i] = PlaceArray[i+1];
        if(PlaceArray[i+1] != undefined)
            PlaceArray[i] = PlaceArray[i+1];
        else
            PlaceArray[i] = 0;

    }
    FindPathArray.pop();
    PlaceStatusArray.pop();
    PlaceToFindPathArray.pop();
    PathPolylineArray.pop();
    if(PlaceArray.length > 2)
        PlaceArray.pop();
    if(index == 0 || index == PlaceToFindPathArray.length) 
    {
        if(PlaceToFindPathArray.length == 2)
            document.getElementById('tdreverse').style.display = '';
        else
            document.getElementById('tdreverse').style.display = 'none';
        GetTotalDistance();
    }
    else
        FindShortestPath(index-1+","+0,0,0);
};

function FromHereClick(pt)
{
    AddPlaceFromFind(pt);
    
    closeContextMenu();
};

function ToHereClick(pt)
{
    AddPlaceToFind(pt);
    closeContextMenu();
};

function GetPolylineOrder(index)
{
    var order = 0;
    for(var i=0; i < index; i++)
        order += PlaceToFindPathArray[i].length;
    return order;
};

function UpdateShortestPath(sid)
{
    var tarr = sid.split(",");
    var index  = parseInt(tarr[0]);
    var sub  = parseInt(tarr[1]);
    if(PlaceToFindPathArray.length < 2 || isFinding == true) return;
    currentIndex = index;
    currentSub = sub;
    var direction = document.getElementById('direction'+index);
    direction.childNodes[0].rows[0].cells[1].childNodes[0].value = PlaceToFindPathArray[index][0].getLatLng().toString();
    FindShortestPath(index+","+sub,0,0);
};

function FindShortestPath(sid, opt, isInsert, isRemove)
{
    var tarr = sid.split(",");
    var index  = parseInt(tarr[0]);
    var sub  = parseInt(tarr[1]);
    if(PlaceToFindPathArray.length < 2) return;
    currentIndex = index;
    currentSub = sub;
    if(index < 0 || index > PlaceToFindPathArray.length-1)  return;
    var vehicle = document.getElementById('vehicle').value;
    var findstring = "";
    var imode=1000;
    if(opt == 1)
    {
        currentFindtype = 1;
        for(var i = 0; i <= sub; i++)
            findstring += PlaceToFindPathArray[index][i].getPoint().longitude + "," + PlaceToFindPathArray[index][i].getPoint().latitude + ",";
        if(mkD != null)
            findstring += mkD.getPoint().longitude + "," + mkD.getPoint().latitude  + ",";
        for(var i=sub+1; i<PlaceToFindPathArray[index].length; i++)
            findstring += PlaceToFindPathArray[index][i].getPoint().longitude + "," + PlaceToFindPathArray[index][i].getPoint().latitude + ",";
        findstring +=  PlaceToFindPathArray[index+1][0].getPoint().longitude + "," + PlaceToFindPathArray[index+1][0].getPoint().latitude;
        imode = PlaceToFindPathArray[index].length + 2;
    }
    else
    {
        currentFindtype = 0;
        if(index > 0 && sub == 0)
        {
            for(var i=0; i< PlaceToFindPathArray[index-1].length; i++)
                findstring += PlaceToFindPathArray[index-1][i].getPoint().longitude + "," + PlaceToFindPathArray[index-1][i].getPoint().latitude + ",";
            imode = PlaceToFindPathArray[index-1].length;
        }
        for(var i=0; i< PlaceToFindPathArray[index].length; i++)
        {
            findstring += PlaceToFindPathArray[index][i].getPoint().longitude + "," + PlaceToFindPathArray[index][i].getPoint().latitude + ",";

        }
        if(index < PlaceToFindPathArray.length - 1)
            findstring +=  PlaceToFindPathArray[index+1][0].getPoint().longitude + "," + PlaceToFindPathArray[index+1][0].getPoint().latitude;
    }
    var level = map.getLevel();
    var bound = map.getDirectionBounds();
    var order = GetPolylineOrder(currentIndex);
    if(currentIndex == PlaceToFindPathArray.length - 1 || (currentIndex > 0 && sub == 0 && isInsert == 0 && isRemove != 1))
        order = GetPolylineOrder(currentIndex-1);
    //debugger;
	vbdmap.FindShortestPath(findstring, vehicle, imode, 0, 1,level, bound.getNorthWest().longitude,  bound.getNorthWest().latitude, bound.getSouthEast().longitude,  bound.getSouthEast().latitude, currentFindtype ,order, currentSub, isInsert, FindShortestPathChange);
	isFinding = true;
	showBusyDiv("");
};


function FindShortestPathChange(str)
{
    //debugger;
    if (str.error != null || str.value == null)
        return;
	var strarr = str.value;
	var ic, opts;
	directionLatLng = map.getCenter();
	var a = strarr[0][0];
	var b = a[0].toString();
	
	if(b.indexOf('e')>=0)
	{
	    //alert(PathPolylineArray);
	    isFinding = false;
	    GetPathDirection();
	    return;
	}
	if(currentFindtype == 1)
	{
	    //Ha gion
	    for(var i = 0; i< strarr.length ; i++)
	    {
	        var pl = new VPolyline(strarr[i],"green",3,"",1.0);
	        if(PathPolylineArray[currentIndex][i] != 0 && PathPolylineArray[currentIndex][i] != null)
	        {
	            map.removeOverlay(PathPolylineArray[currentIndex][i]);
	            PathPolylineArray[currentIndex][i] = pl;
	        }    
	        else
	            PathPolylineArray[currentIndex].push(pl)
	        pl.sid = currentIndex+","+(i);
	        map.addOverlay(pl);
	        if(i > 0)
	        {
	            var latlng = new VLatLng(pl.getVertex(0).latitude, pl.getVertex(0).longitude);
	            var mk = PlaceToFindPathArray[currentIndex][i];
	            ic = new VIcon('images/circle.gif');
	            ic.iconSize = new VSize(10, 10);
	            opts = new VMarkerOptions(ic);
	            opts.offset = new VSize(5, 5);
	            
	            if(mk == null)
	            {
	                mk = new VMarker(latlng,opts);
	                mk.type = FPMARKEROBJ;
	                PlaceToFindPathArray[currentIndex].push(mk);
	                map.addOverlay(mk);
	            }
	            mk.sid = currentIndex+","+(i);
	            mk.setPoint(latlng);
	            mk.enableDragging();
	            VEvent.addListener(mk, "dragend", function(rmk){
	                    isFPObjDragging = false;
	                    FindShortestPath(rmk.sid,1,0);
	                });
	            VEvent.addListener(mk, "dragging", function(rmk){
	                    isFPObjDragging = true;
	                    if (mkD != null)
                        {
                            map.removeOverlay(mkD);
                            mkD = null;
                        }
	                    ChangeShortestPath(rmk.sid);
	                });
	        };
	        
	        VEvent.addListener(pl, 'mousemove', function(pt, eI, rpl){ 
	            if (!isFPObjDragging)
	            {
	                ic = new VIcon('images/circle.gif');
	                ic.iconSize = new VSize(10, 10);
	                if (mkD != null)
	                {
	                    map.removeOverlay(mkD);
	                    mkD = null;
	                }
    	            
	                var ptV = map.fromLatLngToDivPixel(pt);
			        var ptStartV = map.fromLatLngToDivPixel(rpl.latlngs[0][0]);
	                var nLines = rpl.latlngs.length;
	                var nPoints = rpl.latlngs[nLines - 1].length;
	                var ptEndV = map.fromLatLngToDivPixel(rpl.latlngs[nLines - 1][nPoints - 1]);
    	            
	                if (VUtil.Distance(ptV.x, ptV.y, ptStartV.x, ptStartV.y) > 150 && VUtil.Distance(ptV.x, ptV.y, ptEndV.x, ptEndV.y) > 150)
			        {
	                    opts = new VMarkerOptions(ic);
	                    opts.offset = new VSize(5, 5);
	                    mkD = new VMarker(pt, opts);
	                    mkD.sid = rpl.sid;
	                    selectedPoly = rpl.sid;
	                    map.addOverlay(mkD);
	                    mkD.enableDragging();
        	            
	                    VEvent.addListener(mkD, 'mousemove', function(obj, pt){
	                            var arrPts = rpl.latlngs;
			                    var arrRet = new Array();
			                    VUtil.ClosestPointPolylines(pt.longitude, pt.latitude, arrPts, arrRet);
			                    var ptCl = arrRet[0];
    			                
			                    var ptClV = map.fromLatLngToDivPixel(ptCl);
			                    var ptStartV = map.fromLatLngToDivPixel(rpl.latlngs[0][0]);
				                var nLines = rpl.latlngs.length;
				                var nPoints = rpl.latlngs[nLines - 1].length;
				                var ptEndV = map.fromLatLngToDivPixel(rpl.latlngs[nLines - 1][nPoints - 1]);
			                    if (VUtil.Distance(ptClV.x, ptClV.y, ptStartV.x, ptStartV.y) > 150 && VUtil.Distance(ptClV.x, ptClV.y, ptEndV.x, ptEndV.y) > 150)
			                        mkD.setPoint(ptCl);
	                        });
        	            
	                    VEvent.addListener(mkD, "dragend", function(){
	                            isFPObjDragging = false;
	                            FindShortestPath(mkD.sid, 1, 1);
	                        });
	                    VEvent.addListener(mkD, "dragging", function(){
	                            isFPObjDragging = true;
	                            ChangeShortestPath(mkD.sid, 1);
	                        });
	                }
	            }
	        });
	    }
	    isFinding = false;
	    isChanging = false;
	    GetPathDirection();
	    return;
	};
	var i = 0;
	if(currentSub > 0)
	{
	    for(var j=0; j<PathPolylineArray[currentIndex].length; j++)
	        PathPolylineArray[currentIndex][j].setLatLngs(strarr[j]);
	    isFinding = false;
	    isChanging = false;
	    GetPathDirection();
	    return;
	}
	if(currentIndex > 0 && strarr != null)
	{
	    for(var j=0; j < PlaceToFindPathArray[currentIndex-1].length ; j++)
	    {
	        var pl = new VPolyline(strarr[i],"green",3,"",1.0);
	        if(PathPolylineArray[currentIndex-1][j]!= 0 && PathPolylineArray[currentIndex-1][j] != null)
	            map.removeOverlay(PathPolylineArray[currentIndex-1][j]);
	        PathPolylineArray[currentIndex-1][j] = pl;
	        pl.sid = currentIndex - 1 + "," + currentSub;
	        map.addOverlay(pl);
	        VEvent.addListener(pl, 'mousemove', function(pt, eI, rpl){
	                if (!isFPObjDragging)
	                {
	                    var ic = new VIcon('images/circle.gif');
	                    ic.iconSize = new VSize(10, 10);
	                    if (mkD != null)
	                    {
	                        map.removeOverlay(mkD);
	                        mkD = null;
	                    }
    	                
	                    var ptV = map.fromLatLngToDivPixel(pt);
			            var ptStartV = map.fromLatLngToDivPixel(rpl.latlngs[0][0]);
		                var nLines = rpl.latlngs.length;
		                var nPoints = rpl.latlngs[nLines - 1].length;
		                var ptEndV = map.fromLatLngToDivPixel(rpl.latlngs[nLines - 1][nPoints - 1]);
    	                
	                    if (VUtil.Distance(ptV.x, ptV.y, ptStartV.x, ptStartV.y) > 150 && VUtil.Distance(ptV.x, ptV.y, ptEndV.x, ptEndV.y) > 150)
			            {
	                        var opts = new VMarkerOptions(ic);
	                        opts.offset = new VSize(5, 5);
	                        mkD = new VMarker(pt, opts);
	                        mkD.sid = rpl.sid;
	                        selectedPoly = rpl.sid;
	                        map.addOverlay(mkD);
	                        mkD.enableDragging();
                	        
	                        VEvent.addListener(mkD, 'mousemove', function(obj, pt){
	                                    var arrPts = rpl.latlngs;
			                            var arrRet = new Array();
			                            VUtil.ClosestPointPolylines(pt.longitude, pt.latitude, arrPts, arrRet);
			                            var ptCl = arrRet[0];
    			                        
			                            var ptClV = map.fromLatLngToDivPixel(ptCl);
			                            var ptStartV = map.fromLatLngToDivPixel(rpl.latlngs[0][0]);
				                        var nLines = rpl.latlngs.length;
				                        var nPoints = rpl.latlngs[nLines - 1].length;
				                        var ptEndV = map.fromLatLngToDivPixel(rpl.latlngs[nLines - 1][nPoints - 1]);
			                            if (VUtil.Distance(ptClV.x, ptClV.y, ptStartV.x, ptStartV.y) > 150 && VUtil.Distance(ptClV.x, ptClV.y, ptEndV.x, ptEndV.y) > 150)
			                                mkD.setPoint(ptCl);
	                                });
                	        
	                        VEvent.addListener(mkD, "dragend", function(){
	                                isFPObjDragging = false;
	                                FindShortestPath(mkD.sid, 1,1);
	                            });
	                        VEvent.addListener(mkD, "dragging", function(){
	                                isFPObjDragging = true;
                	                ChangeShortestPath(mkD.sid, 1);
	                            });
	                    }
	                }
	            });
    	    
	        i++;
	        var temp = new VLatLng(pl.getVertex(0).latitude, pl.getVertex(0).longitude);
	        PlaceToFindPathArray[currentIndex-1][j].setPoint(temp);
	        temp = new VLatLng(pl.getVertex(pl.getVertexCount()-1).latitude, pl.getVertex(pl.getVertexCount()-1).longitude);
	        PlaceToFindPathArray[currentIndex][0].setPoint(temp);
	    }   
	}
	if(currentIndex < PlaceToFindPathArray.length - 1)
	{
	    for(var j=0; j<PlaceToFindPathArray[currentIndex].length ; j++)
	    {
	        var pl = new VPolyline(strarr[i],"green",3,"",1.0);
	        if(PathPolylineArray[currentIndex][j] != 0  && PathPolylineArray[currentIndex][j] != null)
	            map.removeOverlay(PathPolylineArray[currentIndex][j]);
	        PathPolylineArray[currentIndex][j] = pl;
	        pl.sid = currentIndex+","+j;
	        map.addOverlay(pl);
	        VEvent.addListener(pl, 'mousemove', function(pt, eI, rpl){
	                if (!isFPObjDragging)
	                {
                        var ic = new VIcon('images/circle.gif');
                        ic.iconSize = new VSize(10, 10);
                        if (mkD != null)
                        {
                            map.removeOverlay(mkD);
                            mkD = null;
                        }
                        
                        var ptV = map.fromLatLngToDivPixel(pt);
			            var ptStartV = map.fromLatLngToDivPixel(rpl.latlngs[0][0]);
		                var nLines = rpl.latlngs.length;
		                var nPoints = rpl.latlngs[nLines - 1].length;
		                var ptEndV = map.fromLatLngToDivPixel(rpl.latlngs[nLines - 1][nPoints - 1]);
                        
                        if (VUtil.Distance(ptV.x, ptV.y, ptStartV.x, ptStartV.y) > 150 && VUtil.Distance(ptV.x, ptV.y, ptEndV.x, ptEndV.y) > 150)
			            {
                            var opts = new VMarkerOptions(ic);
                            opts.offset = new VSize(5, 5);
                            mkD = new VMarker(pt, opts);
                            mkD.sid = rpl.sid;
                            selectedPoly = rpl.sid;
                            map.addOverlay(mkD);
                            mkD.enableDragging();
            	            
                            VEvent.addListener(mkD, 'mousemove', function(obj, pt){
                                    var arrPts = rpl.latlngs;
		                            var arrRet = new Array();
		                            VUtil.ClosestPointPolylines(pt.longitude, pt.latitude, arrPts, arrRet);
		                            var ptCl = arrRet[0];
    		                        
		                            var ptClV = map.fromLatLngToDivPixel(ptCl);
			                        var ptStartV = map.fromLatLngToDivPixel(rpl.latlngs[0][0]);
				                    var nLines = rpl.latlngs.length;
				                    var nPoints = rpl.latlngs[nLines - 1].length;
				                    var ptEndV = map.fromLatLngToDivPixel(rpl.latlngs[nLines - 1][nPoints - 1]);
			                        if (VUtil.Distance(ptClV.x, ptClV.y, ptStartV.x, ptStartV.y) > 150 && VUtil.Distance(ptClV.x, ptClV.y, ptEndV.x, ptEndV.y) > 150)
		                                mkD.setPoint(ptCl);
                                });
            	            
                            VEvent.addListener(mkD, "dragend", function(){
                                    isFPObjDragging = false;
                                    FindShortestPath(mkD.sid, 1,1);
                                });
                            VEvent.addListener(mkD, "dragging", function(){
                                    isFPObjDragging = true;
                	                ChangeShortestPath(mkD.sid, 1);
                                });
                        }
                    }
	            });
	        i++;
	        var temp = new VLatLng(pl.getVertex(0).latitude, pl.getVertex(0).longitude);
	        PlaceToFindPathArray[currentIndex][j].setPoint(temp);
	        temp = new VLatLng(pl.getVertex(pl.getVertexCount()-1).latitude, pl.getVertex(pl.getVertexCount()-1).longitude);
	        PlaceToFindPathArray[currentIndex+1][0].setPoint(temp);
		}    
	}
	
	GetPathDirection();
};

function GetPathDirection()
{
	vbdmap.GetDirection(GetPathDirectionChange);
};

function GetPathDirectionChange(ret)
{
    if (ret.error != null)
        return;
    ChangeFunctionType(GLOBAL_FINDPATH_FUNCTION);
	var string = ret.value.toString();
	var resultarray = string.split("newsectiontable");
	var i = 0;
	hideBusyDiv("");
	if(currentIndex > PlaceToFindPathArray.length - 1)  return;
	if(currentFindtype == 1)
	{
	    document.getElementById('guide'+(currentIndex)).innerHTML = resultarray[0];
        //map.removeOverlay(PathPolylineArray[index-1][0]);
        //PathPolylineArray[index-1].pop();
	    return;
	};
	if(currentIndex > 0)
    {
        document.getElementById('guide'+(currentIndex-1)).innerHTML = resultarray[i];
        //map.removeOverlay(PathPolylineArray[index-1][0]);
        i++;
    };
    if(currentIndex < PlaceToFindPathArray.length - 1)
    {
        document.getElementById('guide'+(currentIndex)).innerHTML = resultarray[i].substring(resultarray[i].indexOf("<TABLE"));
        /*for(var i = 0 ; i<=currentIndex;i++)
        {
            for(var j = 0 ; j< PlaceToFindPathArray[currentIndex].length; j++)
            {
                map.removeOverlay(PathPolylineArray[i][j]);
                
            }
            PlaceToFindPathArray.pop();    
        }
        //for(var i = 0 ; i<PlaceToFindPathArray.length-1;i++)
        PlaceToFindPathArray.pop(); */   
    };
    GetTotalDistance();
	isFinding = false;
	isChanging = false;
};

function ChangeShortestPath(sid, opt)
{
    var tarr = sid.split(",");
    var index  = parseInt(tarr[0]);
    var sub  = parseInt(tarr[1]);
    if(PlaceToFindPathArray.length < 2 || isChanging == true || isFinding == true) return;
    currentIndex = index;
    currentSub = sub;
    if(index < 0 || index > PlaceToFindPathArray.length-1)  return;
    var vehicle = document.getElementById('vehicle').value;
    var findstring = "";
    var imode=0;
    if(opt == 1)
    {
        imode = 1;
        currentFindtype = 1;
        findstring += PlaceToFindPathArray[index][sub].getPoint().longitude + "," + PlaceToFindPathArray[index][sub].getPoint().latitude + ",";
        findstring += mkD.getPoint().longitude + "," + mkD.getPoint().latitude;
        if(sub < PlaceToFindPathArray[index].length - 1)
            findstring += "," + PlaceToFindPathArray[index][sub+1].getPoint().longitude + "," + PlaceToFindPathArray[index][sub+1].getPoint().latitude;
        else
            findstring +=  "," + PlaceToFindPathArray[index+1][0].getPoint().longitude + "," + PlaceToFindPathArray[index+1][0].getPoint().latitude;
    }
    else
    {
        currentFindtype = 0;
        if(index > 0 && sub == 0)
            findstring += PlaceToFindPathArray[index-1][PlaceToFindPathArray[index-1].length-1].getPoint().longitude + "," + PlaceToFindPathArray[index-1][PlaceToFindPathArray[index-1].length-1].getPoint().latitude + ",";
        else if(sub > 0)
            findstring += PlaceToFindPathArray[index][sub-1].getPoint().longitude + "," + PlaceToFindPathArray[index][sub-1].getPoint().latitude + ",";
        findstring += PlaceToFindPathArray[index][sub].getPoint().longitude + "," + PlaceToFindPathArray[index][sub].getPoint().latitude;
        if(index < PlaceToFindPathArray.length - 1 && sub >= PlaceToFindPathArray[index].length - 1 )
            findstring +=  "," + PlaceToFindPathArray[index+1][0].getPoint().longitude + "," + PlaceToFindPathArray[index+1][0].getPoint().latitude;
        else if( sub < PlaceToFindPathArray[index].length - 1)
            findstring += "," + PlaceToFindPathArray[index][sub+1].getPoint().longitude + "," + PlaceToFindPathArray[index][sub+1].getPoint().latitude;
    }
    
    var level = map.getLevel();
    var bound = map.getDirectionBounds();
    
	vbdmap.FindShortestPath(findstring, vehicle, imode, 1, imode,level, bound.getNorthWest().longitude,  bound.getNorthWest().latitude, bound.getSouthEast().longitude,  bound.getSouthEast().latitude,-1,-1,-1,-1, ChangeShortestPathChange);
	//vbdmap.FindShortestPath(findstring, vehicle, imode, 1, imode,ChangeShortestPathChange);
	isChanging = true;
};

function ChangeShortestPathChange(str)
{
    
    if (str.error != null)
        return;
    var strarr = str.value;
    
    if(strarr == null || strarr[0] == null || strarr.length < 1 || isFinding == true) return;
    var b = strarr[0].toString();
    if(b.indexOf('e') >= 0) return;
    if(currentFindtype == 1)
    {
        for(var i = 0; i<strarr[1].length; i++)
            strarr[0].push(strarr[1][i]);
        strarr.pop();
        
        PathPolylineArray[currentIndex][currentSub].setLatLngs(strarr[0]);
        isChanging = false;
        return;
    }
    var i = 0;
    if(currentIndex > 0 && currentSub == 0)
    {
        //window.status = PlaceToFindPathArray[currentIndex][0].getPoint();
        if(PathPolylineArray[currentIndex-1].length == 0) 
        {
            isChanging = false;
            return;
        }
        if(PathPolylineArray[currentIndex-1][PathPolylineArray[currentIndex-1].length-1] == 0)
        {
            isChanging = false;
            return;
        }
        PathPolylineArray[currentIndex-1][PathPolylineArray[currentIndex-1].length-1].setLatLngs(strarr[0]);
        i++;
    }
    else if(currentSub > 0)
    {
        PathPolylineArray[currentIndex][currentSub-1].setLatLngs(strarr[0]);
        i++;
    }
    if(currentIndex < PlaceToFindPathArray.length - 1)
    {
        var b = strarr[i].toString();
        if(b.indexOf('e') >= 0)
        {
           isChanging = false;
            return;
        }
        PathPolylineArray[currentIndex][currentSub].setLatLngs(strarr[i]);
    }
    isChanging = false;
};

function GetDirectionLatLngs()
{
    if(PlaceToFindPathArray.length < 2) return;
    var level = map.getLevel();
    var bound = map.getDirectionBounds();
    vbdmap.GetDirectionLatLngs(level, bound.getNorthWest().longitude,  bound.getNorthWest().latitude, bound.getSouthEast().longitude,  bound.getSouthEast().latitude, GetDirectionLatLngsChange);
};

function GetDirectionLatLngsChange(str)
{
    if (str.error != null)
        return;
    var retarr = str.value;
    var z=0;
    var b = retarr[z][0][0].toString();
    if(b.indexOf('e')>=0) return;
    b = retarr[z][0].toString();
    if(b.indexOf('e')>=0) return;
    b = retarr[z].toString();
    if(b.indexOf('e')>=0) return;
    for(var i= 0 ; i < PlaceToFindPathArray.length; i++)
    {
        for(var j=0; j<PlaceToFindPathArray[i].length ; j++)
        {
            PathPolylineArray[i][j].setLatLngs(retarr[z]);
            z++;
        }
        if(z >= retarr.length)
            break;
    }
    directionLatLng = map.getCenter();
    directionLevel = map.getLevel();
};

function CloseDirection(element)
{
    if(element == undefined || element.parentNode   == undefined)
        element = this;
    var tid = element.parentNode.parentNode.parentNode.parentNode.id;  
    element.innerHTML = "<img src=images/mo.gif style=\"margin-right:6px; \" />";
    element.onclick = OpenDirection;
    var index = parseInt(tid.substring(5,tid.length));
    CloseSubDirection(index);
};

function CloseSubDirection(index)
{
    var guidediv = document.getElementById('guide'+index);
    var i = 0;
    var j = 0;
    for(i=0; i<guidediv.childNodes.length; i++)
    {
        if(guidediv.childNodes[i].tagName == "TABLE")
            j++;
        if(j == 2)
            break;
    };
        guidediv.childNodes[i].style.display = 'none';
};

function OverDirectionGuide(obj, from, to)
{
    if(curElement != obj)
        ChangeBgColor(obj,'#eff9e0');
};

function OutDirectionGuide(obj)
{
    if(curElement != obj)
        ChangeBgColor(obj,'#ffffff');
};

function OpenDirection()
{
    var element = this;
    var tid = element.parentNode.parentNode.parentNode.parentNode.id;  
    element.innerHTML = "<img src=images/dong.gif style=\"margin-right:6px; \" />";
    element.onclick = CloseDirection;
    var index = parseInt(tid.substring(5,tid.length));
    OpenSubDirection(index);
};

function OpenSubDirection(index)
{
    var guidediv = document.getElementById('guide'+index);
    var i = 0;
    var j = 0;
    for(i=0; i<guidediv.childNodes.length; i++)
    {
        if(guidediv.childNodes[i].tagName == "TABLE")
            j++;
        if(j == 2)
            break;
    };
    guidediv.childNodes[i].style.display = '';
};

function SearchPlaceEnter(e,element)
{
	var key;
	if(document.all)
		key = event.keyCode;
	else
		key = e.keyCode;
	if(key == 13)
	{	
		var did = element.parentNode.parentNode.parentNode.parentNode.parentNode.id;
		var index = parseInt(did.substring(9,did.length));
		PlaceStatusArray[index] = 1;
		if(CheckInputDatatype(element.value) == 'coor')
		    CheckCoorInput(index, element.value);
		else
		    SearchPlace(index, element.value);
	}
};

function ChangeContent(element)
{
    var did = element.parentNode.parentNode.parentNode.parentNode.parentNode.id;
    var index = parseInt(did.substring(9,did.length));
    PlaceStatusArray[index] = 0;
};

function CheckInputDatatype(str)
{
    var coor = str.split(",");
    
    if(coor.length == 2 && !isNaN(parseFloat(coor[0])) && !isNaN(parseFloat(coor[1])))
        return 'coor';
    else
        return 'string';
};

function CheckCoorInput(index, coorstr)
{
    var coor = coorstr.split(',');
    var latlng = new VLatLng(parseFloat(coor[1]), parseFloat(coor[0]));
    if(PlaceToFindPathArray[index] == null)
    {
        if(index == PlaceToFindPathArray.length)
            AddPlaceToFind(latlng);
    }
    else
    {
        PlaceToFindPathArray[index][0].setPoint(latlng);
        FindShortestPath(index+",0",0,0);
    }
};
var curElement = null;
function GetRoadFromShortestPath(element)
{
    //var temp = element.cells[1].innerHTML.split('- đi');
    var parentid = element.parentNode.parentNode.parentNode.id;
    var sectionid = parseInt(parentid.substring(5, parentid.length));
    if(element.id == "") return; 
    var sarr = element.id.split("_");
    var partid = parseFloat(sarr[0]);
    var start = parseFloat(sarr[1]);
    
    if(element.cells[1] != null)
        var temp = element.cells[1].innerHTML;
    if(element.cells[2] != null);
        var temp1 = element.cells[2].innerHTML;
    var str = new Array();
    str[str.length] = "<table width=270px border=0 cellspacing=0 cellpadding=0 style=\"margin-left:3px; margin-top:3px;\">";
    str[str.length] = "<tr align=left><td>";
    str[str.length] = temp;
    str[str.length] = "<span class=blue></span><br /><br />";
    str[str.length] = "Đoạn đường đi: "+temp1+"<br /><a style=\"color:#cc6600;cursor:pointer; margin-top:10px;\" onmouseover=\"ChangeTextColor(this,'#558800')\" onmouseout=\"ChangeTextColor(this,'#cc6600')\" onclick='ShowPreviousStep()'>Bước trước đó</a> <span style=\"color:#cc6600;\">|</span> <a style=\"color:#cc6600;cursor:pointer;\" onmouseover=\"ChangeTextColor(this,'#558800')\" onmouseout=\"ChangeTextColor(this,'#cc6600')\" onclick='ShowNextStep()'>Bước tiếp theo</a><img src=images/spacer.gif width=10 height=20 align=absmiddle /><br /><br />";
    /*str[str.length] = '<tr>';
    str[str.length] = "<td align=\"left\" colspan=\"2\">Tìm dịch vụ ở gần địa điểm này.<br/> <span style=\"color:#999999;\">VD: khách sạn.&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Bán kính (m)</span></td></tr>";
    str[str.length] = "<tr><td><input id=shortestpathsearchnearby  onkeydown=\"SearchNearByLucenceEnter(event)\" type=text style=\"font-size:11px; width:155px; height:16px; border:1px #999999 solid; margin-top:7px; margin-bottom:7px; margin-right:5px;\" /><input id=shortestpathsearchnearby_radius value=\"100\" onkeydown=\"SearchNearByLucenceEnter(event)\" type=text style=\"font-size:11px; width:50px; height:16px; border:1px #999999 solid; margin-top:7px; margin-bottom:7px; margin-right:5px;\" /><img src=images/tim.gif  width=45px height=19px align=absbottom style=\"cursor:pointer; border:1px #83c327 solid; margin-bottom:7px;\" onclick='SearchNearByLucenceExt(null,null,null,1,null)' onmouseover=\"ChangeBorderColor(this,'#f4c201')\" onmouseout=\"ChangeBorderColor(this,'#83c327')\" />";
    str[str.length] = '</td></tr>';*/
    str[str.length] = '</tr></table>';
    var parentid = element.parentNode.parentNode.parentNode.id;
    var sectionid = parseInt(parentid.substring(5, parentid.length));
    var sarr = element.id.split("_");
    var partid = parseFloat(sarr[0]);
    var start = parseFloat(sarr[1]);
    if(sectionid >= 0)
    {        
        var latlng = new VLatLng(start, partid);
        currentStep = element;
        var l = map.getLevel();
        if(l < 12) 
            l = 12;
        map.setCenter(latlng,l);
        map.openInfoWindow(latlng, str.join(""));
        if(curElement != null)
            ChangeBgColor(curElement,'#ffffff');
        curElement = element;
        ChangeBgColor(element,'#E0EDF9');
    }
    //document.getElementById('shortestpathsearchnearby').focus();
    
};

function ShowPreviousStep()
{
    var element = currentStep.parentNode.rows[currentStep.rowIndex-1];
    if(element != undefined)
        GetRoadFromShortestPath(element);
};

function ShowNextStep()
{
    var element = currentStep.parentNode.rows[currentStep.rowIndex+1];
    if(element != undefined)
        GetRoadFromShortestPath(element);
};

function SearchNearByLucence(keyword, nPage)
{
    if(currentStep.parentNode == null) return;
    var parentid = currentStep.parentNode.parentNode.parentNode.id;
    var sectionid = parseInt(parentid.substring(5, parentid.length));
    if (keyword!=null)
    { 
        if (document.getElementById('shortestpathsearchnearby')!=null)
            document.getElementById('shortestpathsearchnearby').value = keyword;
        
    }
    else if (keyword == null)
        keyword = document.getElementById('shortestpathsearchnearby').value;
    
    var arr = "";
    for(var i=0; i<PlaceToFindPathArray[sectionid].length; i++)
    {
        arr += PlaceToFindPathArray[sectionid][i].getLatLng().longitude + "," + PlaceToFindPathArray[sectionid][i].getLatLng().latitude + ",";
    };
    arr += PlaceToFindPathArray[sectionid+1][0].getLatLng().longitude + "," + PlaceToFindPathArray[sectionid+1][0].getLatLng().latitude;
    vbdmap.SearchNearByPolyline(arr, keyword, nPage, SearchNearByLucenceChange);    
    FillQueryToTextBox(keyword+" trên đoạn đường "+GetNodeName(sectionid));
};
function SearchNearByLucenceExt(section, keyword, what, nPage, radius)
{    
    var sectionid; 
    var s="";   
    showBusyDiv("");
    if (section==null)
    {        
        if (currentStep!=null)
        {            
            if(currentStep.parentNode == null) return;
            var parentid = currentStep.parentNode.parentNode.parentNode.id;
            sectionid = parseInt(parentid.substring(5, parentid.length));
            s = "Đoạn đường "+GetNodeName(sectionid);
        }
        else
        {            
            //s = document.getElementById('businesswhere').value;
            if (s.toLowerCase().indexOf("đoạn đường ")==0 || s.toLowerCase().indexOf("doan duong ")==0)
            {                                
                s = s.substring(11);
                s = s.replace(/^\s+|\s+$/g, '') ;
                sectionid = GetSectionId(s.substring(0,1));
                s = "Đoạn đường "+s;
            }   
        }
    }
    else
        sectionid = section;        
    if (sectionid >= PlaceToFindPathArray.length-1)
    {
        hideBusyDiv();
        alert("Không tồn tại đoạn đường bạn yêu cầu");
        ClearResult();
        return;
    }
    if (keyword!=null)
    { 
        if (document.getElementById('shortestpathsearchnearby')!=null)
            document.getElementById('shortestpathsearchnearby').value = keyword;
        
    }
    else if (keyword == null)
    {
        keyword = document.getElementById('shortestpathsearchnearby').value;
        what = "";
    }
    if (radius == null)
    {
        radius = document.getElementById('shortestpathsearchnearby_radius').value;
        if (isNaN(radius))
            radius = 100;
    }
    /* var arr = new Array();    
    for(var i=0; i<PlaceToFindPathArray[sectionid].length; i++)
    {
        //arr += PlaceToFindPathArray[sectionid][i].getLatLng().longitude + "," + PlaceToFindPathArray[sectionid][i].getLatLng().latitude + ",";
        for(var j=0; j < PathPolylineArray[sectionid][i].getVertexCount(); j++)
            arr[arr.length] = PathPolylineArray[sectionid][i].getVertex(j).longitude + "," +  PathPolylineArray[sectionid][i].getVertex(j).latitude + ",";
    };
    arr[arr.length] = PlaceToFindPathArray[sectionid+1][0].getLatLng().longitude + "," + PlaceToFindPathArray[sectionid+1][0].getLatLng().latitude;
    */
    FillQueryToTextBox(keyword+" trên đoạn đường "+GetNodeName(sectionid));
    /*if (s=="")
        s = document.getElementById('businesswhere').value;*/
    s = s.toLowerCase().replace('doan duong','đoạn đường');
    var s1 = s.substring(11).toUpperCase();
    s = s.substring(0,11)+' '+s1;
    s = s.replace(/^\s+|\s+$/g, '');
    vbdmap.SearchNearByPolyline(GetPolylineOrder(sectionid),PlaceToFindPathArray[sectionid].length, keyword, what, s, nPage, radius, SearchNearByLucenceChange);
};

function SearchNearByPointExt(objectName, objectAddress, lng, lat, keyword, what, nPage, radius)
{                
    showBusyDiv("");
    if (keyword!=null)
    { 
        if (document.getElementById('searchnearbypoint')!=null)
            document.getElementById('searchnearbypoint').value = keyword;
        
    }
    else if (keyword == null)
        keyword = document.getElementById('searchnearbypoint').value;
    if (radius!=null)
    { 
        if (document.getElementById('searchnearbypoint_radius')!=null)
            document.getElementById('searchnearbypoint_radius').value = radius;
        
    }
    else if (radius == null)
        radius = document.getElementById('searchnearbypoint_radius').value;
    if (isNaN(radius))
        radius = 2000.0;
    // Remove <B>, </B>
    var literal = "<B>";
    var replacement = "";
    var re = new RegExp(literal,"g");
    objectName = objectName.replace(re, replacement);
    literal = "</B>";
    re = new RegExp(literal,"g");
    objectName = objectName.replace(re, replacement);        
    // End remove
    if (objectAddress!="")
        FillQueryToTextBox(keyword+" gần "+objectName+", "+objectAddress);
    else
        FillQueryToTextBox(keyword+" gần "+objectName);
    vbdmap.SearchNearByPoint(keyword, what, objectName, objectAddress, lng, lat, radius, nPage, SearchNearByPointChange);
};

// Du`ng tam
function GetNodeName(id)
{    
    switch(id)
    {
        case 0:
            return 'A->B';
            break;
        case 1:
            return 'B->C';
            break;
        case 2:
            return 'C->D';
            break;
        case 3:
            return 'D->E';
            break;
        case 4:
            return 'E->F';
            break;
        case 5:
            return 'F->G';
            break;
        case 6:
            return 'G->H';
            break;
        case 7:
            return 'H->I';
            break;
        case 8:
            return 'I->J';
            break;
        case 9:
            return 'J->K';
            break;
        case 10:
            return 'K->L';
            break;
        case 11:
            return 'L->M';
            break;     
        case 12:
            return 'M->N';
            break;
        case 13:
            return 'N->O';
            break;
        case 14:
            return 'O->P';
            break;
        case 15:
            return 'P->Q';
            break;
        case 16:
            return 'Q->R';
            break;
        case 17:
            return 'R->S';
            break;
        case 18:
            return 'S->T';
            break;
        case 19:
            return 'T->U';
            break;
        case 20:
            return 'U->V';
            break;
        case 21:
            return 'V->W';
            break;     
        case 22:
            return 'W->X';
            break;
        case 23:
            return 'X->Y';
            break;
        case 24:
            return 'Y->Z';
            break;        
    }
}
// Du`ng tam
function GetSectionId(s)
{    
    if(s == null)
        return;
        
    switch(s.toUpperCase())
    {
        case 'A':
            return 0;
            break;
        case 'B':
            return 1;
            break;
        case 'C':
            return 2;
            break;
        case 'D':
            return 3;
            break;
        case 'E':
            return 4;
            break;
        case 'F':
            return 5;
            break;
        case 'G':
            return 6;
            break;
        case 'H':
            return 7;
            break;
        case 'I':
            return 8;
            break;
        case 'J':
            return 9;
            break;
        case 'K':
            return 10;
            break;
        case 'L':
            return 11;
            break;     
        case 'M':
            return 12;
            break;
        case 'N':
            return 13;
            break;
        case 'O':
            return 14;
            break;
        case 'P':
            return 15;
            break;
        case 'Q':
            return 16;
            break;
        case 'R':
            return 17;
            break;
        case 'S':
            return 18;
            break;
        case 'T':
            return 19;
            break;
        case 'U':
            return 20;
            break;
        case 'V':
            return 21;
            break;     
        case 'W':
            return 22;
            break;
        case 'X':
            return 23;
            break;
        case 'Y':
            return 24;
            break;
        case 'Z':
            return 25;
            break;  
    }
}
function SearchNearByLucenceChange(dss)
{
    if (dss.error != null)
        return;
    hideBusyDiv();
    map.closeInfoWindow();
    currentStep = null;
    dsResultData = dss.value;
	var info = new Array();
	if ((null != dsResultData)  && ("object" == typeof(dsResultData)))
	{   
        ClearSearchMapResult();
        DeletePlaceTable();
        var length = dsResultData.Tables[0].Rows.length;
        var nHitSize = dsResultData.Tables[1].Rows[0].HitSize;
        var key = dsResultData.Tables[1].Rows[0].Key;
        
        var nSumOfPage = parseInt((nHitSize + PAGE_ROWS - 1) / PAGE_ROWS);
        var nPageShow = nSumOfPage>PAGE_SHOW?PAGE_SHOW:nSumOfPage;
        var nCurPage = dsResultData.Tables[1].Rows[0].PageIdx;
        var lx = dsResultData.Tables[1].Rows[0].Lx;
        var ly = dsResultData.Tables[1].Rows[0].Ly;
        var rx = dsResultData.Tables[1].Rows[0].Rx;
        var ry = dsResultData.Tables[1].Rows[0].Ry;
        var searchType = dsResultData.Tables[1].Rows[0].SearchType;
        var suggestedKey = dsResultData.Tables[1].Rows[0].SuggestedKey;
        var selectedRadius = dsResultData.Tables[1].Rows[0].Radius;
        var what = dsResultData.Tables[1].Rows[0].What;
        var nStartResIdx = (nCurPage - 1) * PAGE_ROWS + 1;
        var nEndResIdx = nStartResIdx + PAGE_ROWS - 1 > nHitSize?nHitSize:nStartResIdx + PAGE_ROWS - 1;
        info[info.length] = "<table id=TablePlace width=100% border=0 cellspacing=0 cellpadding=0 style=\"overflow:auto;\">";
        
        if (nHitSize > 0)
        {           
            if (dsResultData.Tables[1].Rows[0].IsLonLat)
                info[info.length] = "<tr><td height=20px align=left valign=middle style=\"font-size:11px;\">Tọa độ: <b>"+key+"</b></td></tr>";
            else if (dsResultData.Tables[1].Rows[0].IsAddress)
            {
                if (nHitSize > 1)
                    info[info.length] = "<tr><td height=20px align=left valign=middle style=\"font-size:11px;\">Kết quả từ <b>"+nStartResIdx+"-"+ nEndResIdx +"</b> trong số <b>"+nHitSize+"</b> cho địa chỉ <b>"+key+"</b></td></tr>";                            
                else
                    info[info.length] = "<tr><td height=20px align=left valign=middle style=\"font-size:11px;\">Kết quả tìm kiếm cho địa chỉ <b>"+key+"</b></td></tr>";    
            }
            else
            {                
                if (suggestedKey!="")
                {
                    info[info.length] = "<tr>";
                    if (current_searchtype == GLOBAL_SEARCH_MAP)
                        info[info.length] = "<td height=20px align=left valign=middle style=\"font-size:11px;\"><span style=\"color:#FF0000; font-size:12px;\">Có phải bạn muốn tìm: </span><b><span style=\"color:#006699\"><a style=\"text-decoration:underline; cursor:pointer; font-size:12px;\" id=\"dym\" onclick=\"SearchNearByLucenceExt(null, '"+suggestedKey+"','',"+nCurPage+","+selectedRadius+")\">"+suggestedKey+"</a></span>?</b><br/><br/><br/>";                
                    if (current_searchtype == GLOBAL_SEARCH_BUSINESS)
                        info[info.length] = "<td height=20px align=left valign=middle style=\"font-size:11px;\"><span style=\"color:#FF0000; font-size:12px;\">Có phải bạn muốn tìm: </span><b><span style=\"color:#006699\"><a style=\"text-decoration:underline; cursor:pointer; font-size:12px;\" id=\"dym\" onclick=\"SearchNearByLucenceExt(null, '"+suggestedKey+"','',"+nCurPage+","+selectedRadius+")\">"+suggestedKey+"</a></span>?</b><br/><br/><br/>";                
                    if (current_searchtype == GLOBAL_SEARCH_ADDRESS)
                        info[info.length] = "<td height=20px align=left valign=middle style=\"font-size:11px;\"><span style=\"color:#FF0000; font-size:12px;\">Có phải bạn muốn tìm: </span><b><span style=\"color:#006699\"><a style=\"text-decoration:underline; cursor:pointer; font-size:12px;\" id=\"dym\" onclick=\"SearchNearByLucenceExt(null, '"+suggestedKey+"','',"+nCurPage+","+selectedRadius+")\">"+suggestedKey+"</a></span>?</b><br/><br/><br/>";                
                    if (nHitSize > 1)
                        info[info.length] = "Kết quả từ <b>"+nStartResIdx+"-"+ nEndResIdx +"</b> trong số <b>"+nHitSize+"</b> cho <b>"+key+"</b></td></tr>";
                    else
                        info[info.length] = "Kết quả tìm kiếm cho <b>"+key+"</b></td></tr>";
                    info[info.length] = "</tr>";                     
                }
                else
                {
                    if (nHitSize > 1)
                    {
                        info[info.length] = "<tr><td height=20px align=left valign=middle style=\"font-size:11px;\">Kết quả từ <b>"+nStartResIdx+"-"+ nEndResIdx +"</b> trong số <b>"+nHitSize+"</b> cho <b>"+key+"</b> dọc theo <b>"+dsResultData.Tables[1].Rows[0].Where+"</b> trong phạm vi <b>"+ selectedRadius+"(m)</b></td></tr>";                        
                    }
                    else
                        info[info.length] = "<tr><td height=20px align=left valign=middle style=\"font-size:11px;\">Kết quả tìm kiếm cho <b>"+key+"</b> dọc theo <b>"+dsResultData.Tables[1].Rows[0].Where+"</b> trong phạm vi <b>"+selectedRadius+"(m)</b></td></tr>";                    
                }                                
            }
        }
        else
        {            
            if (dsResultData.Tables[1].Rows[0].IsLonLat)
                info[info.length] = "<tr><td height=20px align=left valign=middle style=\"font-size:11px;\">Không xác định được tọa độ: <b>"+key+"</b></td></tr>";
            else if (dsResultData.Tables[1].Rows[0].IsAddress)
                info[info.length] = "<tr><td height=20px align=left valign=middle style=\"font-size:11px;\">Không tìm thấy địa chỉ <b>"+key+"</b><br /><br />&nbspĐề xuất:<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src=\"vbd_images/dot.gif\" width=\"8\" height=\"8\"/> Xin bạn chắc chắn đã viết đúng địa chỉ.<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src=\"vbd_images/dot.gif\" width=\"8\" height=\"8\"/> Nếu bạn viết tắt, hãy thử không viết tắt.</td></tr>";                            
            else
            {                
                info[info.length] = "<tr>";
                if (suggestedKey!="")
                {
                    if (current_searchtype == GLOBAL_SEARCH_MAP)
                        info[info.length] = "<td height=20px align=left valign=middle style=\"font-size:11px;\"><span style=\"color:#FF0000; font-size:12px;\">Có phải bạn muốn tìm: </span><b><span style=\"color:#006699\"><a style=\"text-decoration:underline; cursor:pointer; font-size:12px;\" id=\"dym\" onclick=\"SearchNearByLucenceExt(null, '"+suggestedKey+"','',"+nCurPage+","+selectedRadius+")\">"+suggestedKey+"</a></span>?</b><br/><br/><br/>";                
                    if (current_searchtype == GLOBAL_SEARCH_BUSINESS)
                        info[info.length] = "<td height=20px align=left valign=middle style=\"font-size:11px;\"><span style=\"color:#FF0000; font-size:12px;\">Có phải bạn muốn tìm: </span><b><span style=\"color:#006699\"><a style=\"text-decoration:underline; cursor:pointer; font-size:12px;\" id=\"dym\" onclick=\"SearchNearByLucenceExt(null, '"+suggestedKey+"','',"+nCurPage+","+selectedRadius+")\">"+suggestedKey+"</a></span>?</b><br/><br/><br/>";                
                    if (current_searchtype == GLOBAL_SEARCH_ADDRESS)
                        info[info.length] = "<td height=20px align=left valign=middle style=\"font-size:11px;\"><span style=\"color:#FF0000; font-size:12px;\">Có phải bạn muốn tìm: </span><b><span style=\"color:#006699\"><a style=\"text-decoration:underline; cursor:pointer; font-size:12px;\" id=\"dym\" onclick=\"SearchNearByLucenceExt(null, '"+suggestedKey+"','',"+nCurPage+","+selectedRadius+")\">"+suggestedKey+"</a></span>?</b><br/><br/><br/>";                
                    info[info.length] = "Không tìm thấy dữ liệu liên quan đến <b>"+key+"</b> dọc theo <b>"+dsResultData.Tables[1].Rows[0].Where+"</b><br /><br />&nbspĐề xuất:<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src=\"vbd_images/dot.gif\" width=\"8\" height=\"8\"/> Xin bạn chắc chắn đã viết đúng chính tả.<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src=\"vbd_images/dot.gif\" width=\"8\" height=\"8\"/> Nếu bạn viết tắt, hãy thử không viết tắt.<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src=\"vbd_images/dot.gif\" width=\"8\" height=\"8\" /> Hãy thử dùng các từ khóa khác có nghĩa tương tự.<br /></td>";
                }
                else
                {
                    info[info.length] = "<td height=20px align=left valign=middle style=\"font-size:11px;\">Không tìm thấy dữ liệu liên quan đến <b>"+key+"</b> dọc theo <b>"+dsResultData.Tables[1].Rows[0].Where+"</b><br /><br />&nbspĐề xuất:<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src=\"vbd_images/dot.gif\" width=\"8\" height=\"8\"/> Xin bạn chắc chắn đã viết đúng chính tả.<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src=\"vbd_images/dot.gif\" width=\"8\" height=\"8\"/> Nếu bạn viết tắt, hãy thử không viết tắt.<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src=\"vbd_images/dot.gif\" width=\"8\" height=\"8\" /> Hãy thử dùng các từ khóa khác có nghĩa tương tự.<br /></td>";
                }
                info[info.length] = "</tr>";                
            }
        }
        for(var i=0; i<length; i++)
        {
            if (dsResultData.Tables[0].Rows[i].Address != dsResultData.Tables[0].Rows[i].Name && dsResultData.Tables[0].Rows[i].Address!="")
                info[info.length] = ResultItemHTML(i+1, dsResultData.Tables[0].Rows[i].Latitude, dsResultData.Tables[0].Rows[i].Longitude, dsResultData.Tables[0].Rows[i].Name+', '+dsResultData.Tables[0].Rows[i].Address);
            else
                info[info.length] = ResultItemHTML(i+1, dsResultData.Tables[0].Rows[i].Latitude, dsResultData.Tables[0].Rows[i].Longitude, dsResultData.Tables[0].Rows[i].Name);
            var latlng = new VLatLng(dsResultData.Tables[0].Rows[i].Latitude,dsResultData.Tables[0].Rows[i].Longitude);
            var icon = new VIcon(dsResultData.Tables[0].Rows[i].Logo);
            icon.iconSize = new VSize(26,29);
            var mopt = new VMarkerOptions(icon);
            var marker = new VMarker(latlng,mopt);
            marker.order = i + 1;
            marker.type = MARKER_POI;
            map.addOverlay(marker);
            arrSearchMapResult.push(marker);
            VEvent.addListener(marker, 'mouseover', function(mk)
            {
                var element = document.getElementById("resultItem_"+mk.order);
                ResultEntryMouseOver(element);
            }
            );
            VEvent.addListener(marker, 'mouseout', function(mk)
            {
                var element = document.getElementById("resultItem_"+mk.order);
                ResultEntryMouseOut(element);
            }
            );
        }
        if (nSumOfPage == 1 && nHitSize <= PAGE_ROWS)
        {
            info[info.length] = "</table>";
      	    ChangeFunctionType(GLOBAL_SEARCH_FUNCTION);
            document.getElementById('searchresult_div').innerHTML	= info.join("");
	        if (nHitSize > 0)
	            map.setCenter(new VLatLng(dsResultData.Tables[1].Rows[0].CenterLat,dsResultData.Tables[1].Rows[0].CenterLng),dsResultData.Tables[1].Rows[0].Level);
	        //hideBusyDiv();
	        return;
        }
        // Paging - Phan trang
        info[info.length] = "<tr><td height=10px></td></tr>";
        info[info.length] = "<tr><td align=\"center\" valign=\"middle\">";
        info[info.length] = "<table border=\"0\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\">";
        info[info.length] = "<tr>";    
                     
        if (nCurPage > 1)
        {
            info[info.length] = "<td align=\"center\" valign=\"middle\" class=\"paging\" style=\"cursor:pointer;\" onmouseover=\"ChangeBorderColor(this,'#66cc00')\" onmouseout=\"ChangeBorderColor(this,'#cccccc')\" onclick=\"SearchNearByLucenceExt(null, '"+key+"','"+what+"',"+1+","+selectedRadius+")\" >Đầu</td>";
            info[info.length] = "<td class=\"paging_space\"></td>";
            info[info.length] = "<td align=\"center\" valign=\"middle\" style=\"width:14px; height:14px;\"><img src=\"images/backpage.gif\" onmouseover=\"ChangeImageSrc(this,'images/backpage_over.gif')\" onmouseout=\"ChangeImageSrc(this,'images/backpage.gif')\" onclick=\"SearchNearByLucenceExt(null, '"+key+"','"+what+"',"+(nCurPage-1)+","+selectedRadius+")\" style=\"cursor:pointer;\" alt=\"Trang trước\" /></td>";
            info[info.length] = "<td class=\"paging_space\"></td>";    
        }
        var number;        
        var delta = 0;
        for (var i=0;i<nPageShow;i++)
        {
             number = nCurPage - DELTA_FROM_CENTER + i;
             if (number <= 0)
                delta = DELTA_FROM_CENTER + 1 - nCurPage;
             if (number > nSumOfPage)
             {
                break;
             }
             number += delta;   
             if (number == nCurPage)
                 info[info.length] = "<td align=\"center\" valign=\"middle\" class=\"paging_active\" ><b>" + number + "</b></td>";   
             else       
                info[info.length] = "<td align=\"center\" valign=\"middle\" class=\"paging\" style=\"cursor:pointer;\" onmouseover=\"ChangeBorderColor(this,'#66cc00')\" onmouseout=\"ChangeBorderColor(this,'#cccccc')\" onclick=\"SearchNearByLucenceExt(null, '"+key+"','"+what+"',"+number+","+selectedRadius+")\">" + number + "</td>";
             info[info.length] = "<td class=\"paging_space\"></td>";
        }
        if (nCurPage < nSumOfPage)
        {
            info[info.length] = "<td align=\"center\" valign=\"middle\" style=\"width:14px; height:14px;\"><img src=\"images/nextpage.gif\" onmouseover=\"ChangeImageSrc(this,'images/nextpage_over.gif')\" onmouseout=\"ChangeImageSrc(this,'images/nextpage.gif')\" onclick=\"SearchNearByLucenceExt(null, '"+key+"','"+what+"',"+(nCurPage+1)+","+selectedRadius+")\" style=\"cursor:pointer;\" alt=\"Trang tiếp\" /></td>";            
            info[info.length] = "<td class=\"paging_space\"></td>";
            info[info.length] = "<td align=\"center\" valign=\"middle\" class=\"paging\" style=\"cursor:pointer;\" onmouseover=\"ChangeBorderColor(this,'#66cc00')\" onmouseout=\"ChangeBorderColor(this,'#cccccc')\" onclick=\"SearchNearByLucenceExt(null, '"+key+"','"+what+"',"+nSumOfPage+","+selectedRadius+")\" >Cuối</td>";
        }                      
        info[info.length] = "</tr>";
        info[info.length] = "</table>";
        info[info.length] = "</td></tr>";
        info[info.length] = "<tr><td height=10px></td></tr>";
        // End Paging
        info[info.length] = "</table>";
      	ChangeFunctionType(GLOBAL_SEARCH_FUNCTION);
        document.getElementById('searchresult_div').innerHTML	= info.join("");
	    if (nHitSize > 0)
	        map.setCenter(new VLatLng(dsResultData.Tables[1].Rows[0].CenterLat,dsResultData.Tables[1].Rows[0].CenterLng),dsResultData.Tables[1].Rows[0].Level);    
	}	
	//hideBusyDiv();
};

function SearchNearByPointChange(dss)
{
    if (dss.error != null)
        return;
    hideBusyDiv();
    map.closeInfoWindow();
    dsResultData = dss.value;
	var info = new Array();
	if ((null != dsResultData)  && ("object" == typeof(dsResultData)))
	{   
        ClearSearchMapResult();
        DeletePlaceTable();
        var length = dsResultData.Tables[0].Rows.length;
        var nHitSize = dsResultData.Tables[1].Rows[0].HitSize;
        var key = dsResultData.Tables[1].Rows[0].Key;
        
        var nSumOfPage = parseInt((nHitSize + PAGE_ROWS - 1) / PAGE_ROWS);
        var nPageShow = nSumOfPage>PAGE_SHOW?PAGE_SHOW:nSumOfPage;
        var nCurPage = dsResultData.Tables[1].Rows[0].PageIdx;
        var lx = dsResultData.Tables[1].Rows[0].Lx;
        var ly = dsResultData.Tables[1].Rows[0].Ly;
        var rx = dsResultData.Tables[1].Rows[0].Rx;
        var ry = dsResultData.Tables[1].Rows[0].Ry;
        var searchType = dsResultData.Tables[1].Rows[0].SearchType;
        var suggestedKey = dsResultData.Tables[1].Rows[0].SuggestedKey;
        
        var selectedName = dsResultData.Tables[0].Rows[length-1].Name;
        var selectedAddress = dsResultData.Tables[0].Rows[length-1].Address;
        var selectedLng = dsResultData.Tables[0].Rows[length-1].Longitude;
        var selectedLat = dsResultData.Tables[0].Rows[length-1].Latitude;
        var selectedRadius = dsResultData.Tables[1].Rows[0].Radius;
        var selectedWhere;
        if (selectedAddress!="")
            selectedWhere = selectedName + ", " + selectedAddress;
        else
            selectedWhere = selectedName;
        var what = dsResultData.Tables[1].Rows[0].What;
        var nStartResIdx = (nCurPage - 1) * PAGE_ROWS + 1;
        var nEndResIdx = nStartResIdx + PAGE_ROWS - 1 > nHitSize?nHitSize:nStartResIdx + PAGE_ROWS - 1;
        info[info.length] = "<table id=TablePlace width=100% border=0 cellspacing=0 cellpadding=0 style=\"overflow:auto;\">";
        
        if (nHitSize > 0)
        {           
            if (dsResultData.Tables[1].Rows[0].IsLonLat)
                info[info.length] = "<tr><td height=20px align=left valign=middle style=\"font-size:11px;\">Tọa độ: <b>"+key+"</b></td></tr>";
            else if (dsResultData.Tables[1].Rows[0].IsAddress)
            {
                if (nHitSize > 1)
                    info[info.length] = "<tr><td height=20px align=left valign=middle style=\"font-size:11px;\">Kết quả từ <b>"+nStartResIdx+"-"+ nEndResIdx +"</b> trong số <b>"+nHitSize+"</b> cho địa chỉ <b>"+key+"</b></td></tr>";                            
                else
                    info[info.length] = "<tr><td height=20px align=left valign=middle style=\"font-size:11px;\">Kết quả tìm kiếm cho địa chỉ <b>"+key+"</b></td></tr>";    
            }
            else
            {                
                if (suggestedKey!="")
                {
                    info[info.length] = "<tr>";
                    if (current_searchtype == GLOBAL_SEARCH_MAP)
                        info[info.length] = "<td height=20px align=left valign=middle style=\"font-size:11px;\"><span style=\"color:#FF0000; font-size:12px;\">Có phải bạn muốn tìm: </span><b><span style=\"color:#006699\"><a style=\"text-decoration:underline; cursor:pointer; font-size:12px;\" id=\"dym\" onclick=\"SearchNearByPointExt('"+selectedName+"','"+selectedAddress+"','"+selectedLng+"','"+selectedLat+"','"+suggestedKey+"','',"+nCurPage+","+selectedRadius+")\">"+suggestedKey+"</a></span>?</b><br/><br/><br/>";                
                    if (current_searchtype == GLOBAL_SEARCH_BUSINESS)
                        info[info.length] = "<td height=20px align=left valign=middle style=\"font-size:11px;\"><span style=\"color:#FF0000; font-size:12px;\">Có phải bạn muốn tìm: </span><b><span style=\"color:#006699\"><a style=\"text-decoration:underline; cursor:pointer; font-size:12px;\" id=\"dym\" onclick=\"SearchNearByPointExt('"+selectedName+"','"+selectedAddress+"','"+selectedLng+"','"+selectedLat+"','"+suggestedKey+"','',"+nCurPage+","+selectedRadius+")\">"+suggestedKey+"</a></span>?</b><br/><br/><br/>";                
                    if (current_searchtype == GLOBAL_SEARCH_ADDRESS)
                        info[info.length] = "<td height=20px align=left valign=middle style=\"font-size:11px;\"><span style=\"color:#FF0000; font-size:12px;\">Có phải bạn muốn tìm: </span><b><span style=\"color:#006699\"><a style=\"text-decoration:underline; cursor:pointer; font-size:12px;\" id=\"dym\" onclick=\"SearchNearByPointExt('"+selectedName+"','"+selectedAddress+"','"+selectedLng+"','"+selectedLat+"','"+suggestedKey+"','',"+nCurPage+","+selectedRadius+")\">"+suggestedKey+"</a></span>?</b><br/><br/><br/>";                
                    if (nHitSize > 1)
                        info[info.length] = "Kết quả từ <b>"+nStartResIdx+"-"+ nEndResIdx +"</b> trong số <b>"+nHitSize+"</b> cho <b>"+key+"</b></td></tr>";
                    else
                        info[info.length] = "Kết quả tìm kiếm cho <b>"+key+"</b></td></tr>";
                    info[info.length] = "</tr>";                     
                }
                else
                {
                    if (nHitSize > 1)
                        info[info.length] = "<tr><td height=20px align=left valign=middle style=\"font-size:11px;\">Kết quả từ <b>"+nStartResIdx+"-"+ nEndResIdx +"</b> trong số <b>"+nHitSize+"</b> cho <b>"+key+"</b> ở gần <b>"+selectedWhere+"</b> trong phạm vi <b>"+selectedRadius+"(m)</b></td></tr>";
                    else
                        info[info.length] = "<tr><td height=20px align=left valign=middle style=\"font-size:11px;\">Kết quả tìm kiếm cho <b>"+key+"</b> ở gần <b>"+selectedWhere+"</b> trong phạm vi <b>"+selectedRadius+"(m)</b></td></tr>";                    
                }                                
            }
        }
        else
        {            
            if (dsResultData.Tables[1].Rows[0].IsLonLat)
                info[info.length] = "<tr><td height=20px align=left valign=middle style=\"font-size:11px;\">Không xác định được tọa độ: <b>"+key+"</b></td></tr>";
            else if (dsResultData.Tables[1].Rows[0].IsAddress)
                info[info.length] = "<tr><td height=20px align=left valign=middle style=\"font-size:11px;\">Không tìm thấy địa chỉ <b>"+key+"</b><br /><br />&nbspĐề xuất:<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src=\"vbd_images/dot.gif\" width=\"8\" height=\"8\"/> Xin bạn chắc chắn đã viết đúng địa chỉ.<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src=\"vbd_images/dot.gif\" width=\"8\" height=\"8\"/> Nếu bạn viết tắt, hãy thử không viết tắt.</td></tr>";                            
            else
            {                
                info[info.length] = "<tr>";
                if (suggestedKey!="")
                {
                    if (current_searchtype == GLOBAL_SEARCH_MAP)
                        info[info.length] = "<td height=20px align=left valign=middle style=\"font-size:11px;\"><span style=\"color:#FF0000; font-size:12px;\">Có phải bạn muốn tìm: </span><b><span style=\"color:#006699\"><a style=\"text-decoration:underline; cursor:pointer; font-size:12px;\" id=\"dym\" onclick=\"SearchNearByPointExt('"+selectedName+"','"+selectedAddress+"','"+selectedLng+"','"+selectedLat+"','"+suggestedKey+"','',"+nCurPage+","+selectedRadius+")\">"+suggestedKey+"</a></span>?</b><br/><br/><br/>";                
                    if (current_searchtype == GLOBAL_SEARCH_BUSINESS)
                        info[info.length] = "<td height=20px align=left valign=middle style=\"font-size:11px;\"><span style=\"color:#FF0000; font-size:12px;\">Có phải bạn muốn tìm: </span><b><span style=\"color:#006699\"><a style=\"text-decoration:underline; cursor:pointer; font-size:12px;\" id=\"dym\" onclick=\"SearchNearByPointExt('"+selectedName+"','"+selectedAddress+"','"+selectedLng+"','"+selectedLat+"','"+suggestedKey+"','',"+nCurPage+","+selectedRadius+")\">"+suggestedKey+"</a></span>?</b><br/><br/><br/>";                
                    if (current_searchtype == GLOBAL_SEARCH_ADDRESS)
                        info[info.length] = "<td height=20px align=left valign=middle style=\"font-size:11px;\"><span style=\"color:#FF0000; font-size:12px;\">Có phải bạn muốn tìm: </span><b><span style=\"color:#006699\"><a style=\"text-decoration:underline; cursor:pointer; font-size:12px;\" id=\"dym\" onclick=\"SearchNearByPointExt('"+selectedName+"','"+selectedAddress+"','"+selectedLng+"','"+selectedLat+"','"+suggestedKey+"','',"+nCurPage+","+selectedRadius+")\">"+suggestedKey+"</a></span>?</b><br/><br/><br/>";                
                    info[info.length] = "Không tìm thấy dữ liệu liên quan đến <b>"+key+"</b> ở gần <b>"+selectedWhere+"</b><br /><br />&nbspĐề xuất:<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src=\"vbd_images/dot.gif\" width=\"8\" height=\"8\"/> Xin bạn chắc chắn đã viết đúng chính tả.<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src=\"vbd_images/dot.gif\" width=\"8\" height=\"8\"/> Nếu bạn viết tắt, hãy thử không viết tắt.<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src=\"vbd_images/dot.gif\" width=\"8\" height=\"8\" /> Hãy thử dùng các từ khóa khác có nghĩa tương tự.<br /></td>";
                }
                else
                {
                    info[info.length] = "<td height=20px align=left valign=middle style=\"font-size:11px;\">Không tìm thấy dữ liệu liên quan đến <b>"+key+"</b> ở gần <b>"+selectedWhere+"</b><br /><br />&nbspĐề xuất:<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src=\"vbd_images/dot.gif\" width=\"8\" height=\"8\"/> Xin bạn chắc chắn đã viết đúng chính tả.<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src=\"vbd_images/dot.gif\" width=\"8\" height=\"8\"/> Nếu bạn viết tắt, hãy thử không viết tắt.<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src=\"vbd_images/dot.gif\" width=\"8\" height=\"8\" /> Hãy thử dùng các từ khóa khác có nghĩa tương tự.<br /></td>";
                }
                info[info.length] = "</tr>";                
            }
        }
        var latlng;
        var icon;
        var mopt;
        var marker;
        var i=0;
        for(i=0; i<length-1; i++)
        {
            if (dsResultData.Tables[0].Rows[i].Address != dsResultData.Tables[0].Rows[i].Name && dsResultData.Tables[0].Rows[i].Address!="")
                info[info.length] = ResultItemHTML(i+1, dsResultData.Tables[0].Rows[i].Latitude, dsResultData.Tables[0].Rows[i].Longitude, dsResultData.Tables[0].Rows[i].Name+', '+dsResultData.Tables[0].Rows[i].Address);
            else
                info[info.length] = ResultItemHTML(i+1, dsResultData.Tables[0].Rows[i].Latitude, dsResultData.Tables[0].Rows[i].Longitude, dsResultData.Tables[0].Rows[i].Name);
            latlng = new VLatLng(dsResultData.Tables[0].Rows[i].Latitude,dsResultData.Tables[0].Rows[i].Longitude);
            icon = new VIcon(dsResultData.Tables[0].Rows[i].Logo);
            icon.iconSize = new VSize(26,29);
            mopt = new VMarkerOptions(icon);
            marker = new VMarker(latlng,mopt);
            marker.order = i + 1;
            marker.type = MARKER_POI;
            map.addOverlay(marker);
            arrSearchMapResult.push(marker);
            VEvent.addListener(marker, 'mouseover', function(mk)
            {
                var element = document.getElementById("resultItem_"+mk.order);
                ResultEntryMouseOver(element);
            }
            );
            VEvent.addListener(marker, 'mouseout', function(mk)
            {
                var element = document.getElementById("resultItem_"+mk.order);
                ResultEntryMouseOut(element);
            }
            );
        }        
        // Add Marker for center point
        latlng = new VLatLng(dsResultData.Tables[0].Rows[i].Latitude,dsResultData.Tables[0].Rows[i].Longitude);
        icon = new VIcon(dsResultData.Tables[0].Rows[i].Logo);        
        icon.iconSize = new VSize(32,32);
        mopt = new VMarkerOptions(icon);
        marker = new VMarker(latlng,mopt);
        marker.order = i + 1;
        marker.type = MARKER_POI;
        map.addOverlay(marker);
        arrSearchMapResult.push(marker);        
        // End
        if (nSumOfPage == 1 && nHitSize <= PAGE_ROWS)
        {
            info[info.length] = "</table>";
      	    ChangeFunctionType(GLOBAL_SEARCH_FUNCTION);
            document.getElementById('searchresult_div').innerHTML	= info.join("");
	        if (nHitSize > 0)
	            map.setCenter(new VLatLng(dsResultData.Tables[1].Rows[0].CenterLat,dsResultData.Tables[1].Rows[0].CenterLng),dsResultData.Tables[1].Rows[0].Level);
	        //hideBusyDiv();
	        document.getElementById('clearResultText').style.display = 'block';
	        return;
        }
        // Paging - Phan trang
        info[info.length] = "<tr><td height=10px></td></tr>";
        info[info.length] = "<tr><td align=\"center\" valign=\"middle\">";
        info[info.length] = "<table border=\"0\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\">";
        info[info.length] = "<tr>";    
                     
        if (nCurPage > 1)
        {
            info[info.length] = "<td align=\"center\" valign=\"middle\" class=\"paging\" style=\"cursor:pointer;\" onmouseover=\"ChangeBorderColor(this,'#66cc00')\" onmouseout=\"ChangeBorderColor(this,'#cccccc')\" onclick=\"SearchNearByPointExt('"+selectedName+"','"+selectedAddress+"','"+selectedLng+"','"+selectedLat+"','"+key+"','"+what+"',1,"+selectedRadius+")\" >Đầu</td>";
            info[info.length] = "<td class=\"paging_space\"></td>";
            info[info.length] = "<td align=\"center\" valign=\"middle\" style=\"width:14px; height:14px;\"><img src=\"images/backpage.gif\" onmouseover=\"ChangeImageSrc(this,'images/backpage_over.gif')\" onmouseout=\"ChangeImageSrc(this,'images/backpage.gif')\" onclick=\"SearchNearByPointExt('"+selectedName+"','"+selectedAddress+"','"+selectedLng+"','"+selectedLat+"','"+key+"','"+what+"',"+(nCurPage-1)+","+selectedRadius+")\" style=\"cursor:pointer;\" alt=\"Trang trước\" /></td>";
            info[info.length] = "<td class=\"paging_space\"></td>";    
        }
        var number;        
        var delta = 0;
        for (var i=0;i<nPageShow;i++)
        {
             number = nCurPage - DELTA_FROM_CENTER + i;
             if (number <= 0)
                delta = DELTA_FROM_CENTER + 1 - nCurPage;
             if (number > nSumOfPage)
             {
                break;
             }
             number += delta;   
             if (number == nCurPage)
                 info[info.length] = "<td align=\"center\" valign=\"middle\" class=\"paging_active\" ><b>" + number + "</b></td>";   
             else       
                info[info.length] = "<td align=\"center\" valign=\"middle\" class=\"paging\" style=\"cursor:pointer;\" onmouseover=\"ChangeBorderColor(this,'#66cc00')\" onmouseout=\"ChangeBorderColor(this,'#cccccc')\" onclick=\"SearchNearByPointExt('"+selectedName+"','"+selectedAddress+"','"+selectedLng+"','"+selectedLat+"','"+key+"','"+what+"',"+number+","+selectedRadius+")\">" + number + "</td>";
             info[info.length] = "<td class=\"paging_space\"></td>";
        }
        if (nCurPage < nSumOfPage)
        {
            info[info.length] = "<td align=\"center\" valign=\"middle\" style=\"width:14px; height:14px;\"><img src=\"images/nextpage.gif\" onmouseover=\"ChangeImageSrc(this,'images/nextpage_over.gif')\" onmouseout=\"ChangeImageSrc(this,'images/nextpage.gif')\" onclick=\"SearchNearByPointExt('"+selectedName+"','"+selectedAddress+"','"+selectedLng+"','"+selectedLat+"','"+key+"','"+what+"',"+(nCurPage+1)+","+selectedRadius+")\" style=\"cursor:pointer;\" alt=\"Trang tiếp\" /></td>";            
            info[info.length] = "<td class=\"paging_space\"></td>";
            info[info.length] = "<td align=\"center\" valign=\"middle\" class=\"paging\" style=\"cursor:pointer;\" onmouseover=\"ChangeBorderColor(this,'#66cc00')\" onmouseout=\"ChangeBorderColor(this,'#cccccc')\" onclick=\"SearchNearByPointExt('"+selectedName+"','"+selectedAddress+"','"+selectedLng+"','"+selectedLat+"','"+key+"','"+what+"',"+nSumOfPage+","+selectedRadius+")\" >Cuối</td>";
        }                      
        info[info.length] = "</tr>";
        info[info.length] = "</table>";
        info[info.length] = "</td></tr>";
        info[info.length] = "<tr><td height=10px></td></tr>";
        // End Paging
        info[info.length] = "</table>";
      	ChangeFunctionType(GLOBAL_SEARCH_FUNCTION);
        document.getElementById('searchresult_div').innerHTML	= info.join("");
	    if (nHitSize > 0)
	        map.setCenter(new VLatLng(dsResultData.Tables[1].Rows[0].CenterLat,dsResultData.Tables[1].Rows[0].CenterLng),dsResultData.Tables[1].Rows[0].Level);    
	}	
	//hideBusyDiv();
	document.getElementById('clearResultText').style.display = 'block';
};

function SearchNearByLucenceEnter(e, stid)
{
	var key;
	if(document.all)
		key = event.keyCode;
	else
		key = e.keyCode;
	if(key == 13)
	{	
		SearchNearByLucenceExt(stid,null,null,1,null);
	}
};

function SearchNearByPointEnter(e, objectName, objectAddress, lng, lat, keyword, radius)
{
	var key;
	if(document.all)
		key = event.keyCode;
	else
		key = e.keyCode;
	if(key == 13)
	{	
	    SearchNearByPointExt(objectName, objectAddress, lng, lat, keyword, "", 1, radius);
	}
};

function ShowSearchNearByShortestPath(element)
{
    var parentid = element.parentNode.parentNode.parentNode.parentNode.parentNode.id;
    var sectionid = parseInt(parentid.substring(5, parentid.length));
    var str = new Array();
    str[str.length] = "<table width=270px border=0 cellspacing=0 cellpadding=0 style=\"margin-left:3px; margin-top:3px;\">";
    str[str.length] = "<tr align=left><td>";      
    str[str.length] = " Tìm dịch vụ trên đường đi.<br/> <span style=\"color:#999999;\">VD: ủy ban.&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Bán kính (m)</span></td></tr>";
    str[str.length] = "<tr><td><input id=shortestpathsearchnearby  onkeydown=\"SearchNearByLucenceEnter(event,"+sectionid+")\" type=text style=\"font-size:11px; width:155px; height:16px; border:1px #999999 solid; margin-top:7px; margin-bottom:7px; margin-right:5px;\" /><input id=shortestpathsearchnearby_radius value=\"2000\"  onkeydown=\"SearchNearByLucenceEnter(event,"+sectionid+")\" type=text style=\"font-size:11px; width:50px; height:16px; border:1px #999999 solid; margin-top:7px; margin-bottom:7px; margin-right:5px;\" /><img src=images/tim.gif  width=45px height=19px align=absbottom style=\"cursor:pointer; border:1px #83c327 solid; margin-bottom:7px;\" onclick='SearchNearByLucenceExt("+sectionid+",null,null,1,null)' onmouseover=\"ChangeBorderColor(this,'#f4c201')\" onmouseout=\"ChangeBorderColor(this,'#83c327')\" /></td>";
    str[str.length] = " </tr></table>";
    if(sectionid >= 0)
    {
        var latlng = PathPolylineArray[sectionid][0].getVertex(0);
        currentStep = element;
        map.openInfoWindow(latlng, str.join(""));
    }
    document.getElementById('shortestpathsearchnearby').focus();
};  

function FindReverseDirection()
{
    if(PlaceToFindPathArray.length != 2) return;
    var direction = document.getElementById("direction0");
    var a = direction.childNodes[0].rows[0].cells[1].childNodes[0].value;
    direction = document.getElementById("direction1");
    var b = direction.childNodes[0].rows[0].cells[1].childNodes[0].value;
    var pa = PlaceToFindPathArray[0][0].getLatLng();
    var pb = PlaceToFindPathArray[1][0].getLatLng();
    ClearResult();
    AddPlaceFromFind(pb,b);
    AddPlaceToFind(pa,a);
};

/*function GetTotalDistance()
{
    if(PlaceToFindPathArray.length <= 2)
    {
        if(PlaceToFindPathArray.length > 0)
            document.getElementById('guide'+(PlaceToFindPathArray.length - 1)).innerHTML = "";
        return;
    }
    var totaldistance = 0;
	for(var i = 0; i< PlaceToFindPathArray.length-1; i++)
    {
        tb = document.getElementById('guide'+i).childNodes[0].rows[0].cells[1];
        if(tb != null)
        {
            var tstring = tb.innerHTML;
            tstring = tstring.substring(tstring.indexOf('Chiều dài (')+11,tstring.indexOf('m)'));
            if(tstring.indexOf('k') > -1)
                totaldistance += parseFloat(tstring.substring(0,tstring.length-1))*1000;
            else
                totaldistance += parseFloat(tstring.substring(0,tstring.length-1));
        }
        
    }
    var totalstring = "";
    if(totaldistance > 1000)
        totalstring = parseFloat(parseInt(totaldistance)/1000).toString() + " km";
    else
        totalstring = parseFloat(totaldistance).toString() + " m";
    
    document.getElementById('guide'+(PlaceToFindPathArray.length - 1)).innerHTML = "<B> <a style='margin-left:5px'>Tổng chiều dài : "+totalstring+"</a></B>";
}*/
function GetTotalDistance()
{
    if(PlaceToFindPathArray.length <= 2)
    {
        if(PlaceToFindPathArray.length > 0)
            document.getElementById('guide'+(PlaceToFindPathArray.length - 1)).innerHTML = "";
        return;
    }
   
    var totaldistance = 0;
    for(var i = 0; i< PlaceToFindPathArray.length-1; i++)
    {
        var Html = document.getElementById('guide'+i).innerHTML;
        var pattern = /(Chiều dài:|Length:)(.*?)m/g;
        Html = Html.match(pattern)[0];
        
        if (nLanguage == 0)
            Html = Html.substring(Html.indexOf('Chiều dài: ') + 11,Html.indexOf('m'));
        else
            Html = Html.substring(Html.indexOf('Length: ') + 8,Html.indexOf('m'));
            
        if(Html.indexOf('k') > -1)
            totaldistance += parseFloat(Html.substring(0,Html.length-1))*1000;
        else
            totaldistance += parseFloat(Html.substring(0,Html.length-1));
    }
    var totalstring = "";
    if(totaldistance > 1000)
        totalstring = parseFloat(parseInt(totaldistance)/1000).toString() + " km";
    else
        totalstring = parseFloat(totaldistance).toString() + " m";
    document.getElementById('guide'+(PlaceToFindPathArray.length - 1)).innerHTML = "<B> <a style='margin-left:5px'>Tổng chiều dài : "+totalstring+"</a></B>";
}