var map = null;				//The VEMap
var ShapeLayer          = null;		//ShapeLayer for adding Pushpins
var isLoading = false;      // Checks if there is currently an Ajax post processing
var SelectedProvider = null;
var ObjectPinMapping = new Array();     // Mapping between PushPinsand RealEstates
var InfoBoxOpen = false;            // Checks if the Infobox is currently open (toggled via resultlist buttons)
var ResultListPins = new Array();   // document Elements for the Pins in the Result List
var debugEnabled = false;

/**********************
* Set the Focus on Austria -> automatically calls Zoom!
***********************/
function FocusOnAustria()
{
	map.SetCenter(new VELatLong(47.47266286861341, 12.700195312499988));
	map.SetZoomLevel(6);
}

/*
* Helper Method for the PushPinMappings for the ResutlIst
*/
function NameValueCollection(inpName, inpValue, index)
{
	this.Name = inpName;
	this.Value = inpValue;
	this.Index = index;
}		

/*
* Initializes the MapControl
*/
function GetMap()
{  
    if(debugEnabled)
        ShowDebugContainer();
        
    ShowInfo("Initialisiere Karte...");
	map = new VEMap('GEOMap');	
	
	// Work around for Firefox 2.0 - VE drawing bug
    // See http://www.viavirtualearth.com/Wiki/Firefox2.ashx for details
    // TODO: Check if nessacary
    var ffv = 0;
    var ffn = "Firefox/"
    var ffp = navigator.userAgent.indexOf(ffn);
    if (ffp != -1) ffv = parseFloat(navigator.userAgent.substring(ffp + ffn.length));    
    if (ffv >= 1.5) Msn.Drawing.Graphic.CreateGraphic=function(f,b) { return new Msn.Drawing.SVGGraphic(f,b) }
    
    
    map.SetDashboardSize(VEDashboardSize.Medium);	// Version 5 and Higher Only
    map.onLoadMap = LoadedMap;
    map.LoadMap(GetStartPosition(), //Austria
            GetStartZoom(),					//Zoom level
            VEMapStyle.Road,	//Map style
            false,				//No Static Map -> we want to Zoom
            VEMapMode.Mode2D,	//Initially 2d
            true);				//Show the 3d Tab
            
	ShapeLayer = new VEShapeLayer();
	map.AddShapeLayer(ShapeLayer);
	
    map.AttachEvent("onchangeview", ChangedView);    	    
	
    /*if(MapViewSpec != null)			//If hes From the IDS
    {			
		map.SetMapView(MapViewSpec);		
		GotBack = true;			//GotBack defines if he got back from the Detail Page
    }*/
    
    map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);
    
    // Set Birds Eye Notification Invisible
    if(document.getElementById('MSVE_obliqueNotification') != null)
        document.getElementById('MSVE_obliqueNotification').style.visibility="hidden";       
    
    AsyncPost(GetUrl());
}
/*
* Nessecary for correctly displaying BirdsEye View Scene
*/
function LoadedMap()
{
  map.SetShapesAccuracy(VEShapeAccuracy.Pushpin);
}
/*
* Initializes the Starting Position of the Map
*/
function GetStartPosition()
{   

    if(typeof(StartLatitude) != 'undefined' && typeof(StartLongitude) != 'undefined')
        return new VELatLong(parseFloat(StartLatitude), parseFloat(StartLongitude)); 	
    else
        return new VELatLong(47.47266286861341, 12.700195312499988)
    /*
    // Wien:
    return new VELatLong(48.21460773683882, 16.37786865234375); 	
    */
}

/*
* Initializes the Starting Zoom of the Map
*/
function GetStartZoom()
{
    if(typeof(StartZoom) != 'undefined')
        return StartZoom;
    else return 7;    
}

/*
* Starts an AJAX Request
*/
function AsyncPost(url)
{
    WriteDebug("Start Request");
	if (window.XMLHttpRequest)
	{
		xmlhttp=new XMLHttpRequest()
	}
	// code for IE
	else if (window.ActiveXObject)
	{
		xmlhttp=new ActiveXObject('MSXML2.XMLHTTP.3.0');
	}
	if (xmlhttp !=null)
	{			
		try
		{
			xmlhttp.onreadystatechange= RenderResult;		//Set the Response Method
			xmlhttp.open("GET", url, true);
			xmlhttp.send(null);				//Start the XML Http Request				
		}
		catch(e)
		{
			ShowInfo("Es ist ein Fehler beim Laden der Immobilien aufgetreten.");
		}
	}
	else
	{
		ShowInfo("Ihr Browser unterstützt diese Funktionalität nicht!");		
	}	
}

/*
* Occurs on panning / zooming the Map
*/
function ChangedView()
{
    if(!isLoading)
    {
	    ShowInfo("Immobilien werden geladen...");
	    
	    var v = map.GetMapView();	    
	    isLoading = true;
	    AsyncPost(GetUrl());
	    
	    GotBack  = false;	
	}
}

/*
* Gets the Current Path
*/
function GetPath()
{
    var lastInd = location.href.lastIndexOf("/");
    return location.href.substr(0, lastInd) +"/";
}

/*
* Gets the Url for the Search
*/
function GetUrl()
{   
	var FeedUrl = GetPath() + "feed.geo";	
	var v = map.GetMapView();	 					
	
	if(map.GetMapStyle() == "b")
	{
	    var be = map.GetBirdseyeScene();
        v = be.GetBoundingRectangle();
	}
	    
	if(location.search.length == 0)
	{
	    FeedUrl += "?";
	}
	else
	    FeedUrl += location.search +"&";
	
	//Add the Map Specific parameters:	
	FeedUrl  += 'tlLat='	+ v.TopLeftLatLong.Latitude;
	FeedUrl  += '&tlLon='	+ v.TopLeftLatLong.Longitude;
	FeedUrl  += '&brlat='	+ v.BottomRightLatLong.Latitude;
	FeedUrl  += '&brLon='	+ v.BottomRightLatLong.Longitude;
	FeedUrl	 += '&imar='	+ "951;934;952;933;944;956;958;936;935;";			
	FeedUrl	 += '&Zoom='	+ map.GetZoomLevel();
	FeedUrl	 += '&dbName='	+ databasename;
	
	if(typeof(nextlink)  != 'undefined')
	    FeedUrl	 += '&nextlink='+ nextlink;
	
	if(SelectedProvider != null)
	{
		FeedUrl += "&prov=" + SelectedProvider;
	}
	
	return FeedUrl;
}

/*
* Checks if the Ajax request was OK
*/
function checkReadyState(obj)
{
  if(obj.readyState == 4)
  {		
    if(obj.status == 200)
    {    
      return true;
    }
    else
    {           
		ShowInfo("Es ist ein Fehler beim Laden der Immobilien aufgetreten!<br /> Wenn sie Internet Explorer 5 oder 6 installiert haben, stellen sie Sicher dass ActiveX erlaubt ist! ");
    }
  }
}

/*
* Parses the AJAX XML and displays the result in the Map and the Result List
*/
function RenderResult()
{
    if(checkReadyState(xmlhttp))			//Check if The XML is OK
	{	
	    WriteDebug("Start Render");
		var response		        = xmlhttp.responseXML;		
		var pins                    = response.getElementsByTagName("PushPin");
		var realEstates             = response.getElementsByTagName("RealEstate");		
		var selectedProviderNode    = response.getElementsByTagName("SelectedProvider");
		var isDummy                 = response.getElementsByTagName("Dummy").length > 0;
		var isError                 = response.getElementsByTagName("Fehler").length > 0;
		var insecure                = response.getElementsByTagName("INSECURE");
		
		ShapeLayer.DeleteAllShapes();		//Clear Existing Pushpins
		ObjectPinMapping = new Array();
		ClearResultIndizes();
		
		//Security Graph Check
		if(document.getElementById("SecureHolder") != null)
		{
		    if(insecure.length > 0)
		    {			    
		        HideGeoProviderContainer();
		        document.getElementById("SecureHolder").style.display = "block";
		        document.getElementById("secureIMG").src = LinkBaseDir + insecure[0].firstChild.data;
		        ShowInfo("Bitte f&uuml;llen Sie die Sicherheitsabfrage aus.");		    
		        return;
		    }
		    else
		    {   
		        document.getElementById("SecureHolder").style.display ="none";
		    }
		}   
		
		if(isError) // CHeck if an Error occured
		{
		    HideGeoProviderContainer();		    
		    ShowInfo("Es ist ein Fehler beim Laden der Immobilien aufgetreten! <br /> Bitte versuchen Sie es zu einen sp&auml;teren Zeitpunkt erneut.");
		}		
		else if(isDummy)    // Check if there are too many realEstates
		{       
		    HideGeoProviderContainer();
		    ShowInfo("Zu viele Objekte, bitte verfeinern Sie Ihre Suche!");
		}
		else
		{
		    // Process the Objects:
		    
		    ShowInfo(realEstates.length +" verortbare Immobilie"+ ( realEstates.length > 1 ? "n" : "") +" gefunden");
    		
    		if(parent.document.getElementById("selectedProviderPanel") != null)
    		{
		        ShowGeoProvider(selectedProviderNode, response.getElementsByTagName("GeoProvider"));
		    }
    		
		    for(var i = 0; i < pins.length; i++)    // Parse all Pins in the Result
		    {   
		        var pinRealEstates = pins[i].getElementsByTagName("RealEstate");
		        var lat = pins[i].getElementsByTagName("lat")[0];
		        var lon = pins[i].getElementsByTagName("long")[0];
    		    
    		    var pushPinDesc = "";
    		    var isGeoProvider = false;
    		    var isCluster = pinRealEstates.length > 1;
    		    var objects = new Array();		            
		        var MinPrecision = 999;		            
		        var isResult = false;
		            
		        if(typeof(itemTemplate) !='undefined')  // Check if we have a Template
		        {   
		            if(typeof(headerTemplate) != 'undefined')   // render Header
		            {
		                var text = headerTemplate;
		                var appendText = pinRealEstates.length;
		                appendText += " Immobilie" +(pinRealEstates.length > 1 ? "n" : "");
		                
		                text = FillText(text, 'RealEstateCount', appendText);
		                
		                pushPinDesc += text;
		            }
		            
		            // Foreach RealEstate -> get text
		            for( var reInd = 0; reInd < pinRealEstates.length; reInd ++)
		            {
    		            var text = itemTemplate;       		        
    		            var cols =  pinRealEstates[reInd].childNodes;
        		        var isProvider = pinRealEstates[reInd].getElementsByTagName("KanzleiIstGeoPromoter")[0].firstChild.nodeValue == "True";
        		        var prec = pinRealEstates[reInd].getElementsByTagName("MapPointMatchedStatus")[0].firstChild.nodeValue;
        		        
        		        if(pinRealEstates[reInd].attributes.getNamedItem("IsResult").value == "1")        		        
        		            isResult = true;
        		        
        		        if(prec < MinPrecision && prec != 0)
        		            MinPrecision = prec;        		        
        		        
        		        if(isProvider)
        		            isGeoProvider = true;
        		            
    		            for(var colInd = 0; colInd < cols.length; colInd ++)    // Fill the RealEstate data
    		            {
    		                if(cols[colInd].firstChild != null)
    		                {   
    		                    if(cols[colInd].nodeName != "TrefferListenBild")
    		                    {       		                    
    		                        text = FillText(text, cols[colInd].nodeName, cols[colInd].firstChild.nodeValue);    		                		                
    		                    }
    		                    else
    		                    {   
    		                        text = FillText(text, cols[colInd].nodeName, LinkBaseDir.substring(0, LinkBaseDir.length -1) + cols[colInd].firstChild.nodeValue);    		                            		                            		                        
    		                    }
    		                }
    		                else
    		                {
    		                    if(cols[colInd].nodeName == "TrefferListenBild" && typeof(NoImageUrl) != 'undefined')    		                           		                    
    		                        text = FillText(text, cols[colInd].nodeName, NoImageUrl);    		             
    		                    else
    		                        text = FillText(text, cols[colInd].nodeName, "");
    		                }
    		            }
    		            
    		            var Regex = new RegExp("!!titel!!", "gim"); // TODO: irgendwas hats noch
    		            text = text.replace(Regex, "");            
    		            
        		        debugEnabled = true;
    		            pushPinDesc += text;
        		        
    		            if(typeof(itemSeperator) != 'undefined' && reInd < (pinRealEstates.length -1))  // Render Seperator if defined
    		            {
    		                pushPinDesc += itemSeperator;
    		            }
    		                		            
    		            objects.push(pinRealEstates[reInd].getElementsByTagName("ID")[0].firstChild.nodeValue); // Push the realestate in the current list
		            }
		            
		            if(typeof(footerTemplate) != 'undefined')   // Render footer
		            {
		                pushPinDesc += footerTemplate;
		            }
		        }  
		        
		         // Add the PushPin
	            var PinID = AddPushPin(pushPinDesc, 
	                                new VELatLong(
	                                    parseFloat(lat.firstChild.data), 
	                                    parseFloat(lon.firstChild.data)
	                                ), 
	                                i +1, 
	                                isGeoProvider, 
	                                MinPrecision, 
	                                isCluster,
	                                isResult
	                        );			       
	            
	            // Add the PushPin to the Mapping            
	            var Mapping = new NameValueCollection(PinID, objects, i+1);                 
	            ObjectPinMapping.push(Mapping);
		        
		        // Render the Items in the ResultList
                for( var reInd = 0; reInd < pinRealEstates.length; reInd ++)	
                    RenderIndex(pinRealEstates[reInd].getElementsByTagName("ID")[0].firstChild.nodeValue);   		    
		    }
		}
		WriteDebug("End Render");
		isLoading = false;
	}
	else
	{
	    isLoading = false;
	}
}

function HideGeoProviderContainer()
{
    var GeoProviderPanel = parent.document.getElementById("GeoProviderContainer")
    if(GeoProviderPanel != null)
		GeoProviderPanel.style.display="none";
}

function ShowGeoProviderContainer()
{
    var GeoProviderPanel = parent.document.getElementById("GeoProviderContainer")
    
    if(GeoProviderPanel != null)
		GeoProviderPanel.style.display="";
}

function ShowGeoProvider(selectedProviderNode, GeoProviderList)
{
    if(selectedProviderNode == null && GeoProviderList.length == 0)
    {
        HideGeoProviderContainer();
        return;
    }
    
    ShowGeoProviderContainer();
    
    if(selectedProviderNode != null && selectedProviderNode.length != 0)    // Selected GeoProvider
    {   
        if(typeof(parent.selectedProviderTemplate)  != 'undefined')
        {               
            var text = parent.selectedProviderTemplate;
            
            text = FillText(text, "Name",        selectedProviderNode[0].getElementsByTagName("Name")[0].firstChild.data);
            //TOOD: gjp handler!
            if(selectedProviderNode[0].getElementsByTagName("Image")[0].firstChild != null)
                text = FillText(text, "GeoProvider", selectedProviderNode[0].getElementsByTagName("Image")[0].firstChild.data);
            else
                itemText = FillText(itemText, "GeoProvider", LinkBaseDir +"todo.jpg");
            parent.document.getElementById("selectedProviderPanel").innerHTML = text;
        }
    }    
    else
        parent.document.getElementById("selectedProviderPanel").innerHTML = "";
	
    if(typeof(parent.geoProviderItemTemplate) !='undefined')   // Only if we have an Item template: render the GeoProviders
    {	
        var ListContainer = parent.document.getElementById("ProviderPanel");
        
        
        if(GeoProviderList.length > 0)
            ListContainer.style.display="";
        
        var text = "";
	    
	    if(typeof(parent.geoProviderHeaderTemplate) != 'undefined')
	    {   
	        text += parent.geoProviderHeaderTemplate;
	    }
	    
        for(var i = 0; i< GeoProviderList.length; i++)
        {
            var itemText = parent.geoProviderItemTemplate;
	        
            itemText = FillText(itemText, "Name", GeoProviderList[i].getElementsByTagName("Name")[0].firstChild.data);
            
            //TOOD: gjp handler!
            if(GeoProviderList[i].getElementsByTagName("Image")[0].firstChild != null)
                itemText = FillText(itemText, "GeoProvider", LinkBaseDir + GeoProviderList[i].getElementsByTagName("Image")[0].firstChild.data);
            else
                itemText = FillText(itemText, "GeoProvider", LinkBaseDir +"todo.jpg");
                
            itemText = FillText(itemText, "Nummer", "javascript:SetProvider('"+GeoProviderList[i].getElementsByTagName("Nummer")[0].firstChild.data+"');");
            text += itemText;
            
            if(typeof(geoProviderSeperatorTemplate) != 'undefined')
	        {   
	            text += geoProviderSeperatorTemplate;
	        }            
        }
        
	    if(typeof(parent.geoProviderFooterTemplate) != 'undefined')
	    {   	    
	        text += parent.geoProviderFooterTemplate;
	    }
	    
        ListContainer.innerHTML = text;
    }
}

/*
* Toggles the visability of the InfoBox
*/
function ToggleInfoBox(objectID)
{   
    if(InfoBoxOpen)
    {
        HidePin();
    }
    else
    {   
        ShowPin(objectID);
    }
}
/*
* Hides the InfoBox
*/
function HidePin()
{
    InfoBoxOpen = false;
    map.HideInfoBox();
}

/*
* Registers a span for rendering the PushPin
*/
function RegisterPinDisplay(controlID, objectID)
{   
    ResultListPins.push(new NameValueCollection(objectID, controlID, -1));        
}

/*
* Clears all Result List pushpins
*/
function ClearResultIndizes()
{
    for(var i = 0; i< ResultListPins.length; i++)
    {
        var targetID = ResultListPins[i].Value;
        if(targetID != null)
        {
            var target = document.getElementById(targetID);
            if(target != null)
                HidePin(target);
        }
    }
}

/*
* Function for hiding pins in the ResultList when they are not present in the mapControl
*/
function HidePin(pinControl)
{   
    if(pinControl != null)
    {
        pinControl.innerHTML = "";
    }
}

/*
* Renders the Index of the given RealEstate to the Assigned ResultList item
*/
function RenderIndex(objectID, latitude, longitude)
{   
    var target = null;
    for(var i = 0; i< ResultListPins.length; i++)
    {    
        if(parseInt(ResultListPins[i].Name) == parseInt(objectID))
        {               
            target = ResultListPins[i].Value;
            break;
        }
    }
    
    if(target != null)
    {   
        var ind = GetIndexForObject(objectID);
    
        if(ind != -1)
        {   
            //alert(xmlhttp.responseXML);
            var pin = xmlhttp.responseXML.getElementsByTagName("PushPin")[ind -1];
            var objects = pin.getElementsByTagName("RealEstate");
            
            for(var i = 0; i < objects.length; i++)
            {
                var id = objects[i].getElementsByTagName("ID")[0].firstChild.nodeValue;
                if(id = objectID)
                {
                    var isProvider = objects[i].getElementsByTagName("KanzleiIstGeoPromoter")[0].firstChild.nodeValue == "true";
        		    var prec       = objects[i].getElementsByTagName("MapPointMatchedStatus")[0].firstChild.nodeValue;        		            		    
                    document.getElementById(target).innerHTML = GetIconForPrecision(prec, isProvider, ind, false, true);    
                    break;
                }
            }
        }
        else
            HidePin(document.getElementById(target));
    }  
}

function MoveMapToPosition(latitude, longitude, ObjectID)
{   
    SetPosition(latitude.replace(',', '.'), longitude.replace(',', '.'), ObjectID);
}

function SetPosition(latitude, longitude, ObjectID)
{   
    HidePin();
    
    // Set the Position to the Pushpin    
    map.SetZoomLevel(14);
    map.SetCenter(new VELatLong(parseFloat(latitude), parseFloat(longitude)));
    
    while(isLoading);
    
    window.setTimeout("ShowPin("+ObjectID+");", 1000);
}

/*
* Gets the PushPin index for the given RealEstate
*/
function GetIndexForObject(objectID)
{
    var foundObject = false;
    
    for(var i = 0; i < ObjectPinMapping.length; i++)
    {
        var PinID = ObjectPinMapping[i].Name;
        var index = ObjectPinMapping[i].Index;
        
        for(var j = 0; j < ObjectPinMapping[i].Value.length; j++)
        {    
            if(parseInt(ObjectPinMapping[i].Value[j]) == parseInt(objectID))
            {   
                foundObject = true;
                break;
            }
        }
        
        if(foundObject)
            return index;
    }
    
    return -1;
}

/*
* Shows a Pushpin Infobox
*/
function ShowPin(objectID)
{   
    var foundObject = false;    
    
    for(var i = 0; i < ObjectPinMapping.length; i++)
    {
        var PinID   = ObjectPinMapping[i].Name;
        var objects = ObjectPinMapping[i].Value;
        
        for(var j = 0; j < objects.length; j++)
        {   
            if(objects[j] == objectID)
            {   
                foundObject = true;
                break;
            }
        }
        
        if(foundObject)
        {   
            var Shape = ShapeLayer.GetShapeByID(PinID);                                                
	        map.ShowInfoBox(Shape);
	        InfoBoxOpen = true;
            break;
        }
    }        
}

/*
* Returns the HTML Code for the given object
*/
function GetIconForPrecision(Precision, isGeoProvider, index, isCluster, isResult)
{   
    var className = "";
	var ie = document.all && !window.opera
	
	if(ie)				//Works only if the ClassName ends with IE!
		className += "IE";
		
	if(isCluster)   // is a Clustered Pin
	    return "<div class=\"" + (isResult ? "Res_" : "") +"UnPreciseIcon\" id=\"icon_"+index+"\"><div class=\"buttonText\">"+ (index > 0 ? index : "") +"</div></div>";
	if(isGeoProvider)   // IsGeoProvider
		return "<div class=\""+ (isResult ? "Res_" : "") +"GEOIcon\" id=\"icon_"+index+"\"><div class=\"buttonText\">"+(index > 0 ? index : "") +"</div></div>";;
		
	if(parseInt(Precision) < 5)	// Is Unprecise
		return "<div class=\"" + (isResult ? "Res_" : "") +"UnPreciseIcon\" id=\"icon_"+index+"\"><div class=\"buttonText\">"+(index > 0 ? index : "") +"</div></div>";
	else        // Is Precise
		return "<div class=\"" + (isResult ? "Res_" : "") +"PreciseIcon\" id=\"icon_"+index+"\"><div class=\"buttonText\">"+(index > 0 ? index : "") +"</div></div>";
}
 
 /*
 * Sets the Current GeoProvider
 */
function SetProvider(Nummer)
{
    GeoSearchFrame.SelectedProvider = Nummer;   
    GeoSearchFrame.AsyncPost(GeoSearchFrame.GetUrl()); 
}
/*
* Un Sets the Current GeoProvider
*/
function UnSetProvider()
{
    GeoSearchFrame.SelectedProvider = null;
    GeoSearchFrame.AsyncPost(GeoSearchFrame.GetUrl());
}
/*
* Adds a Pushpin to the MapCOntrol
*/
function AddPushPin(description, LatLong, index, isGeoProvider, Precision, isCluster, isResult)
{   
    var shape = new VEShape(VEShapeType.Pushpin, [LatLong]);         //Set the icon         
	var icon = GetIconForPrecision(Precision, isGeoProvider, index, isCluster, isResult);
	
	if(icon != null && icon != "")
	    shape.SetCustomIcon(icon);                  
	    
	if(description != "")
	{
		shape.SetDescription(description);                  
	}
	
	//Add the shape the the map    		
	ShapeLayer.AddShape(shape);		
	return shape.GetID();
}
/*
* Fills the ItemTemplate with the given parameters
*/
function FillText(text, tagname, value)
{        
    var Regex = new RegExp("!!" + tagname +"!!", "gim");
    
    return text.replace(Regex, value);            
}

/**********************************
* Sends the Inputted Security Graph Infos to the Server
***********************************/
function ResetSecurityGraph()
{
    var inputedText = document.getElementById("securityInput").value;
    var givenImage  = document.getElementById("secureIMG").src;
        
    AsyncPost(GetUrl() +"&secureInput=" + inputedText +"&secureIMG=" + givenImage);    
    document.getElementById("securityInput").value = "";
}

/*
* Shows an Information to the User
*/
function ShowInfo(text)
{
    if(document.getElementById("veInfoDiv") != null)
    {
        document.getElementById("veInfoDiv").innerHTML = text;
    }   
}

function ShowDebugContainer()
{
    if(document.getElementById("veDebugContainer") != null)
    {
        document.getElementById("veDebugContainer").style.display="";
    }
}

function WriteDebug(Message)
{
    if(debugEnabled)
    {
        var timer = new Date();
    
        if(document.getElementById("veDebugDiv") != null)
        {
            document.getElementById("veDebugDiv").innerHTML += "<br />" + Message +" -  " +timer.getMinutes()+":"+timer.getSeconds()+":"+timer.getMilliseconds();;
        }       
    }    
}

function ClearDebug()
{
    if(document.getElementById("veDebugDiv") != null)
    {
        document.getElementById("veDebugDiv").innerHTML = "";
    }       
}

function GetDetailMap()
{   
    if(typeof(DetailViewLatitude) != 'undefined' && typeof(DetailViewLongitude) != 'undefined' && typeof(DetailViewPrecision) != 'undefined')
    {
	    map = new VEMap('GEOMap');	
    	
	    // Work around for Firefox 2.0 - VE drawing bug
        // See http://www.viavirtualearth.com/Wiki/Firefox2.ashx for details
        // TODO: Check if nessacary
        var ffv = 0;
        var ffn = "Firefox/"
        var ffp = navigator.userAgent.indexOf(ffn);
        if (ffp != -1) ffv = parseFloat(navigator.userAgent.substring(ffp + ffn.length));    
        if (ffv >= 1.5) Msn.Drawing.Graphic.CreateGraphic=function(f,b) { return new Msn.Drawing.SVGGraphic(f,b) }
        
        map.SetDashboardSize(VEDashboardSize.Medium);	// Version 5 and Higher Only
        
        map.LoadMap(new VELatLong(parseFloat(DetailViewLatitude), parseFloat(DetailViewLongitude)), // PushPin Position
                14,					//Zoom level
                VEMapStyle.Road,	//Map style
                false,				
                VEMapMode.Mode2D,
                false); 
                
        ShapeLayer = new VEShapeLayer();
	    map.AddShapeLayer(ShapeLayer);				
	    map.ClearInfoBoxStyles();						   
        map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);
        
        AddPushPin("", new VELatLong(DetailViewLatitude, DetailViewLongitude), -1, false, DetailViewPrecision, false, false);    

        map.AttachEvent('onmousedown', disableDrag);
        map.AttachEvent("onendzoom", ZoomDetailMap);
         
        // Set Birds Eye Notification Invisible
        if(document.getElementById('MSVE_obliqueNotification') != null)
            document.getElementById('MSVE_obliqueNotification').style.visibility="hidden";       
    }
}

function disableDrag(e)
{
    if(e.leftMouseButton)
    {
        return true;
    }
}

function ZoomDetailMap(event)
{
    var Zoom = map.GetZoomLevel();
    if(Zoom > 17)
    {
        map.SetZoomLevel(17);            
    }
    else if(Zoom < 11)
    {
        map.SetZoomLevel(11);
    } 
}