
var arrPoints = new Array();
var bolProcessing = false;
var bolDoSearch = false;
var intSearchAddressIndex = 0;

function addRouteAddress () {
	$("#routing_more_addresses").append( '' + Lang.txtRouting_TO_ADDRESS + ': <input type="text" class="routing_addresses" value="" style="width: 223px;" /><br />');
    $("#tab4").height($("#tab4_nav").height() + 40);
}

function doRouting () {
	if (arrPoints.length > 0)
	{                 
		var arrP = new Array();                   
		for (var n=0; n<arrPoints.length; n++)
		{
			if (arrPoints[n].X > 0)
			{
				map.route_window.AddWayPoint(n, arrPoints[n].X, arrPoints[n].Y);
				arrP.push({x:arrPoints[n].X, y:arrPoints[n].Y});
			}
			
		}
		map.route_window.DoRoute();
		map.route_window.ShowRouteWindow();
		
		map.ShowPoints(arrP, 1);
	}
}

function route_addresses() {
	if (bolProcessing === false)
	{
		arrPoints = new Array();
		map.route_window.Clear();
		bolProcessing = true;
		$(".routing_addresses").each(function(intIndex){
			arrPoints.push({strAddress: $(this).val(), X:null, Y:null, bolSearched: false});
		});
		
		intSearchAddressIndex = 0;
		
		findAddress(arrPoints[0].strAddress);
		
	}
	else
	{
		alert("Please wait!");
	}
}

function findAddress(strAddress)
{
	map.search_control.SearchAddress(strAddress, addressSearchResponse);
}

function addressSearchResponse()
{
	
	var row = null;
	if (kijs_apdz_viet != null && kijs_apdz_viet.total > 0)
	{
		row = kijs_apdz_viet.data[0];
	}
	else if (kijs_nature != null && (kijs_nature.hills.total > 0 || kijs_nature.lakes.total > 0 || kijs_nature.rivers.total > 0))
	{
		if (kijs_nature.hills.total > 0)
		{
			row = kijs_nature.hills.data[0];
		}
		else if (kijs_nature.lakes.total > 0)
		{
			row = kijs_nature.lakes.data[0];
		}
		else if (kijs_nature.rivers.total > 0)
		{
			row = kijs_nature.rivers.data[0];
		}
	}
	else if (kijs_address != null && kijs_address.length > 0)
	{
		row = kijs_address[0];
	}

	if (row != null)
	{
		arrPoints[intSearchAddressIndex].X = row.x;
		arrPoints[intSearchAddressIndex].Y = row.y;
		arrPoints[intSearchAddressIndex].bolSearched = true;
	}
	else
	{
		arrPoints[intSearchAddressIndex].X = 0;
		arrPoints[intSearchAddressIndex].Y = 0;
		arrPoints[intSearchAddressIndex].bolSearched = true;
	}
	
	intSearchAddressIndex++
	if (intSearchAddressIndex == arrPoints.length)
	{
		doRouting();
		bolProcessing = false;
	}
	else
	{
		findAddress(arrPoints[intSearchAddressIndex].strAddress);
	}
	
}
