/***** Geocoding ***/
var geocoder;
var vmGeocShapeList = new VMShapeList();

function singleGeocode(){    
    var addr = document.getElementById("txtAddr").value;
    //alert (addr);
    
    if (addr ==""){
        return;
    }
    
    var geocoder = new Geocoder(map);
    //var zoomTo = document.getElementById ("geocdZoomTo").checked;
    //geocoder.setZoomToCollection(zoomTo);
    var addrs = new Array();
    addrs[0] = addr;
    geocoder.runBatchGeocode(addrs);
}


function batchGeocode(){       
    var addrsBox = document.getElementById("txtAddrs");
    var addrs = txtAreaToArray(addrsBox.value);
    if (addrs ==""){
        return;
    }
    addrsBox.value = ""; 
    
    
    geocoder = new Geocoder(map,"txtAddrs", "txtGeocodeResult");
    var iconPath = getIconPath();    
    
    //var zoomTo = document.getElementById ("geocdZoomTo").checked;
    //geocoder.setZoomToCollection(zoomTo);
    
    geocoder.setIconURL(iconPath);    
    
    geocoder.setSiteName(getSiteName());
    
   
    
    geocoder.runBatchGeocode(addrs);
    
}

function getIconPath(){
    var inputs = document.getElementById("BatchGecodePanel").getElementsByTagName("input");
    var plot = "";
    var path = "";
    for (var i = 0; i<inputs.length; i++){
        var input = inputs[i];
       
        if (input.name == "RdPlot" & input.checked ==true){
            plot = input.value;
        }
        if (input.name == "upload_color" & input.checked ==true){
            path = input.value;
        }
    }
    if (plot =="rdPlotYes"){
        return path;
    }else {
        return null;
    }
}

function getSiteName(){
    return document.getElementById("txtSiteName").value;
}

function txtAreaToArray(t){	    
    	return t.split(/[\n\r]+/);
}


/************** Geocoder class */
function Geocoder( theMap, notFoundTxtBoxId, resultBoxId){
	this.find = find;
	this.findCallBack = findCallBack;
	this.txtAreaToArray = txtAreaToArray;
	this.setZoomToCollection = setZoomToCollection;
	this.setIconURL = setIconURL;
	this.setSiteName = setSiteName;
	this.updateBound = updateBound;
	this.zoomToBound = zoomToBound;
	
	this.runBatchGeocode = runBatchGeocode;
	this.getShapes = getShapes;
	
	var zoomToCollection = true;
	var iconURL = "Img/upload_red.png";	
	var siteName = "";
	
	var input = "";
	var current = 0;
	var addrs = null;
	var shapes = new VMShapeCollection(theMap);
	var maxLat = -9999;
	var minLat = 9999;
	var maxLng = -9999;
	var minLng = 9999;
	
	var seperator = "\t";
	var result = "Input" + seperator + "MatchedAddress" + seperator + "Latitude" + seperator + "Longitude";
	var txtSave = "";
	function zoomToBound(){
	    map.SetMapView(new Array( new VELatLong(maxLat, minLng), new VELatLong(minLat, maxLng)));
	    if (map.GetZoomLevel() > 12){
	        map.SetZoomLevel(12);
	    }
	}
	function updateBound(lat, lng){
	    if (lat > maxLat){
	        maxLat = lat;
	    }
	    if (lat < minLat){
	        minLat = lat;
	    }
	    if (lng > maxLng){
	        maxLng = lng;
	    }
	    if (lng < minLng){
	        minLng = lng;
	    }
	}
	function getShapes(){
	    return shapes.getShapes();
	}
	function setZoomToCollection(b){
	    zoomToCollection = b;
	}
	function setIconURL(path){
	    iconURL = path;
	}
	function setSiteName(name){
	    siteName = name;
	}
	
	function hasNext(){
	    if (!addrs) {
	        return false;
	    }
	    return (current < (addrs.length));
	}
	
	function runBatchGeocode(theAddrs){
	    current = 0;
	    addrs = theAddrs;
	    txtSave = "";
	    find (null, addrs[current], true);
	    
	}
	
	//Note: finCallBack function is not re-entrance. So can NOT loop to call this funtion repeatly
	// if loop, the findCallBack function of the previous call will be overwritten by the next call
	function find(what, where, defaultAmbig){	    
	    current++;
	    displayMsgBox("Geocoding...", where);
	    input = where;
        var findType = null;
        var shapeLayer = null;
        var startIndex = 0;
        var numberOfResults = 20;
        var showResults = false;
        var createResults = false;

        var useDefaultDisambiguation =  defaultAmbig;	//use the default popup to select a from disambiguation list
        var setBestMapView = false;			//zoom in to place found      
        try {  
            theMap.Find(what, where, findType, shapeLayer, startIndex, numberOfResults, showResults, createResults, useDefaultDisambiguation, setBestMapView, findCallBack );
        }catch (ex){
            hideMsgBox();
        }
	}
	
	
	function findCallBack(shapeLayer, findResults, places, hasMore, e){
	    try {
	    
	    if (!places | places.length < 1) {
	        alert ("Can NOT geocode:\n" +input); 
	        if (notFoundTxtBoxId){
	            
	            var notFoundBox = document.getElementById(notFoundTxtBoxId);
	            
	            if (notFoundBox.value ==""){
	                notFoundBox.value = input;
	            } else {
	                notFoundBox.value = notFoundBox.value + "\n" + input;
	            }
	        } 
	    }else {
	         
	        for (var i = 0; i < places.length; i++){
			    var lat = places[i].LatLong.Latitude;
			    var lng = places[i].LatLong.Longitude;
			    
			    updateBound(lat,lng);
			    
			    lat = cutOffDecimal(lat, 6);
			    lng = cutOffDecimal(lng, 6);
			    var matchedAddr = places[i].Name;
    			
			    var des = "<BR><B>Input</B>: " + input;
			    des = des + "<BR><B>Site name</B>: " + siteName;
			    des = des + "<BR><B>Matched address</B>: " + matchedAddr;
			    //uncomment below lines to display lat lng
			    //des = des + "<BR><B>Latitude</B>: " + lat;
			    //des = des + "<BR><B>Longitude</B>: " + lng;
			    //shapes.addPoint(lat, lng, "Gecoded Site", des, iconURL );
			    
			    var wkt = veLatLng2WKT(places[i].LatLong);
			    var id = randomString(10);
			   
			    //addShape(theId, theName, theDetails, theWKT, theVEShapeType, theAppShapeType)			    
			    var shape = new VMShape(id, matchedAddr, des,wkt, VEShapeType.Pushpin, iconURL);
			    shape.setIcon(iconURL);
			    if (iconURL){ 
			        shape.showShape();
			    }
			    vmShapeList.addShapeObj(shape);
			    
			    //format the txt for saving
			    var wkt = veLatLng2WKT(places[i].LatLong);
			    
			    //txtSave = txtSave + id + "|" + matchedAddr + "|" + des + "|" + iconURL + "|" + wkt + "\n";        
			    
			    
			    if (resultBoxId){
			        result = result + "\n" + input + seperator + matchedAddr + seperator + lat + seperator + lng;
			    }
			    var deli = "\t";
			    txtSave = txtSave + "\n" +  id + deli + siteName + deli + matchedAddr + deli + des+  deli + iconURL + deli+ wkt + deli + input;
			    //txtSave = txtSave + "," + input + deli + matchedAddr + deli+ lat + deli +  lng +  deli + id +  deli + wkt;
			    //txtSave = txtSave + "\n" + input + seperator + matchedAddr + seperator + lat + seperator +  lng +  seperator + id + wkt;
		    }
		    
		   
		}
		
		//continue to find if has more address
		if (hasNext()){		    
		    find (null, addrs[current], true);	        
		}else {
		    //if added to the map
		    
		    zoomToCollection = document.getElementById ("geocdZoomTo").checked;
		    if ((zoomToCollection ==true) & (maxLat != -9999)){
		        zoomToBound();
			    
		    }
		    //if result is added to the box
		    if (resultBoxId){
		        document.getElementById(resultBoxId).value = result;		        
		        document.getElementById("txtGeocResultSave").value = escapeString(txtSave);		        
		    }
		    
		    hideMsgBox();
		    
		    //show the geocding panel
		    
		}
		
		}catch (ex){
	        hideMsgBox();
	    }
	}
	
	
	
}  //end geocoder class

function saveGeocode(){
    /*
    var shapes = geocoder.getShapes();
    
    alert (shapes.length);
    var txt = "";
    for (var i = 0; i < shapes.length; i++){
        var shape = shapes[i];
        var title = shape.GetTitle();
        var des = shape.GetDescription();
        var latLng = shape.GetPoints()[0];
        var icon = shape.GetCustomIcon().Image;
        var id = randomString(10);
        txt = txt + id + "|" + title + "|" + des + "|" + icon + "|" + latLng.Latitude + "|" + latLng.Longitude + "\n";        
    }
    document.getElementById("txtGeocResultSave").value = txt;
    */
}