var map;
var LocationSearchHandler="/_layouts/VirtualEarth/LocationSearch.ashx";
var DisplayPopup = "/_layouts/VirtualEarth/DisplayPopup.ashx";
var _listid;
var _webid;
var _titlefield;
var _descfield;
var tmpPushpinTitle;
var findIcon;
var iconLoc; 

function VEWebPart_LoadMap(divid, latitude, longitue, zoom, type, listid, webid, titlefield, descfield, showsearchbox, distanceunit) {   
    // Show the map and hook up events
    map = new VEMap(divid);
    map.SetDashboardSize(VEDashboardSize.Tiny);
    map.LoadMap(new VELatLong(51.882483, 4.532979 ), zoom , type ,false);
    map.AttachEvent("onchangeview", view_Changed);
    
    map.SetScaleBarDistanceUnit(distanceunit);
        
    _listid = listid;
    _webid=webid;
    _titlefield = titlefield;
    _descfield = descfield;
    
    if (showsearchbox) {
        ShowSearchBox();
        }
        
    view_Changed();

          //Cancel the normal hover
          map.AttachEvent("onmouseover", Map_OnMouseOver); 
          
          // Get a OnClick
          map.AttachEvent("onclick", Map_OnClick); 
}

      function Map_OnMouseOver(e) {
            if (e.elementID)
            {
                return true;
            }
      }
      
      function Map_OnClick(e) {

            if (e.elementID) {
                if (document.getElementById("VEWebPart_Popup")) {
                    wp_closePopup(e);
                }
		else {
		    ShowPopup(e);
		}
            }
	    else {
                
            var myControl = document.getElementById("VEWebPart_Popup");

          if (myControl != null) {
                map.DeleteControl(myControl);
          }

	   }
      }

      function ShowPopup(e) {
          var shape = map.GetShapeByID(e.elementID);
          var el = document.createElement("div");
          el.id = "VEWebPart_Popup";
          
      	  shape.SetCustomIcon("<img src=\"/_layouts/images/woonbronportal/pin_red.gif\" />");
	      iconLoc = shape.GetIconAnchor();
	        
          el.style.width = "340px";
          el.style.height = "178px";
	  
	      el.style.left = e.mapX-70+"px"
	      el.style.top = e.mapY-178+"px";

          var strHtml = "<div id=\"mappopup\"><img id=\"mappopuploading\" src=\"/_layouts/images/woonbronportal/loading.gif\" /></div><div id=\"mappopupbottom\"></div>";   
          el.innerHTML = strHtml;
          map.AddControl(el);


var latlong = window.escape(shape.GetIconAnchor());
load(DisplayPopup + "?slatlon=" + latlong + "&listid=" + _listid + "&webid=" + _webid, "mappopup");
	    //function () {
	    //  var latlong = window.escape(shape.GetIconAnchor());
	    //    $("#mappopup").load(DisplayPopup + "?slatlon=" + latlong + "&listid=" + _listid + "&webid=" + _webid);
	    //});

      }
              
      function wp_closePopup(e) {
	  var shape = map.GetShapeByID(e.elementID);
	  shape.SetCustomIcon("<img src=\"/_layouts/images/woonbronportal/pin_green.gif\" />");
      iconLoc = 0; 
          var myControl = document.getElementById("VEWebPart_Popup");

          if (myControl != null) {
                map.DeleteControl(myControl);
          }
       }

function view_Changed()  {
    var view = map.GetMapView();
    var geoRSSUrl = LocationSearchHandler + "?hlat=" + view.TopLeftLatLong.Latitude + "&llng=" + view.TopLeftLatLong.Longitude + "&llat=" + view.BottomRightLatLong.Latitude  + "&hlng=" + view.BottomRightLatLong.Longitude + "&titlefld=" + _titlefield + "&listid=" + _listid + "&webid=" + _webid;
    geoRSSUrl = geoRSSUrl + "&" + (new Date()).getTime();
    if (_descfield != "") {
        geoRSSUrl = geoRSSUrl + "&descfld=" + _descfield;
    }
            
    LoadGeoRSS(geoRSSUrl);
}

function LoadGeoRSS(url) {   
    var l = new VEShapeLayer();
    var veLayerSpec = new VEShapeSourceSpecification(VEDataType.GeoRSS, url, l);
    map.ImportShapeLayerData(veLayerSpec, onFeedLoad, 0);
}

function onFeedLoad(shapeLayer) {
    for (i=0; i < shapeLayer.GetShapeCount(); i++) {
		var s = shapeLayer.GetShapeByIndex(i);
		
        var varX = window.escape(s.GetIconAnchor());
        var varY = window.escape(window.iconLoc);
	      
	      if (varX == varY){
	      	s.SetCustomIcon("<img src=\"/_layouts/images/woonbronportal/pin_red.gif\" />");
	      }
	      else {
		    s.SetCustomIcon("<img src=\"/_layouts/images/woonbronportal/pin_green.gif\" />");
	      }
	}
	
    var resultsdiv = document.getElementById('VEWebPart_SearchResults');
    if (resultsdiv) {
        if ( resultsdiv.hasChildNodes() ) {
            while ( resultsdiv.childNodes.length >= 1 )  {
                resultsdiv.removeChild( resultsdiv.firstChild );       
            } 
        }
        
        for (i=0; i < shapeLayer.GetShapeCount(); i++) {
            var shape = shapeLayer.GetShapeByIndex(i);
            if (shape.GetTitle() != "dummy")  {
              var el = document.createElement("div");
              el.id="velocation_" + i;
              var strHtml =  "<span class=\"title\">" + shape.GetTitle() + "</span>";
              strHtml += "<div>" + shape.GetDescription() + "</div>";
              strHtml += "<hr />";
                            
              el.innerHTML = strHtml;
              resultsdiv.appendChild(el);
            }
        }
    }
}

function ShowSearchBox() {
    var el = document.createElement("div");
    el.id = "VEWebPart_SearchForm";
    el.style.top = 14;
    //el.style.left = GetMapWidth() - 168; // = Width of the map - width of the div - margin right
    el.style.left = 40;
    el.style.border = "1px solid gray";
    el.style.background = "#f1f7f7";
    el.style.padding = 3;
    el.style.width = "163px";
    el.style.fontSize = "10px";    
    
    var strHtml =  "Address:<br/><input type=\"text\" id=\"VEWebPart_findAddress\"><br />";
    strHtml = strHtml + "<input type=\"submit\" value=\"Search\"  id=\"VWebPart_AddressSearchSubmit\" onclick=\"VEWebPart_FindAddress(); return false;\">";
            
    el.innerHTML = strHtml;
    map.AddControl(el);   
}

function VEWebPart_FindAddress() {
    var address = document.getElementById('VEWebPart_findAddress').value;
    tmpPushpinTitle = address;
    
    try {            
        map.Find(null, address, null, null, null, null, true, true, true, true, onLocationFound);         
    }         
    catch(e) {            
        alert(e.message);         
    }
}

function onLocationFound(layer, resultsArray, places, hasMore, veErrorMessage) {
    var latlon;
    
    latlon = places[0].LatLong;
    if (findIcon)
        map.DeleteShape(findIcon);
    
    findIcon = new VEShape(VEShapeType.Pushpin, latlon);    
    findIcon.SetTitle(tmpPushpinTitle);
    findIcon.SetCustomIcon("/_layouts/images/ewr206l.gif");
    map.AddShape(findIcon);
    map.SetZoomLevel(12);
}

function GetMapWidth() {
    var view = map.GetMapView();
    var bottomright = view.BottomRightLatLong;
            
    return map.LatLongToPixel(bottomright).x;
}

function GetMapHeight() {
    var view = map.GetMapView();
    var bottomright = view.BottomRightLatLong;
            
    return map.LatLongToPixel(bottomright).y;
}

function ahah(url, target) {
  if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    req = new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (req != undefined) {
    req.onreadystatechange = function() {ahahDone(url, target);};
    req.open("GET", url, true);
    req.send("");
  }
}  

function ahahDone(url, target) {
  if (req.readyState == 4) { // only if req is "loaded"
    if (req.status == 200) { // only if "OK"
      document.getElementById(target).innerHTML = req.responseText;
    } else {
      document.getElementById(target).innerHTML=" AHAH Error:\n"+ req.status + "\n" +req.statusText;
    }
  }
}

function load(name, div) {
	ahah(name,div);
	return false;
}
