var _PANO_IMAGES_URL_SV = "http://maps.afrigis.co.za/streetviewimages/";
var tileLayer = null;
var svDisplaying = false;
var svVisible = false;
var icon1 =  new AGIcon(null,"images/pinDrilDown.png");
icon1.iconSize = new AGSize(32,32);
icon1.iconAnchor = new AGPoint(-5,-32);
icon1.infoDisplayAnchor = new AGPoint(5,-32);
var defaultMarkerOption1 = new AGMarkerOptions();
defaultMarkerOption1.icon = icon1;
defaultMarkerOption1.draggable = true;
//defaultMarkerOption1.stationary = true;
var svtCount = 0;

var defaultMarker = null;

var pos = null;
var oResults;
var evtListenerClick = null;
var svtZoomListener = null;
var svActiveListener = null;
var prePosition = null;
var initPixel = null;

// for infoWindow
var infoWindowOptions = new AGInfoDisplayOptions();
infoWindowOptions.width = 500;
infoWindowOptions.height = 400;
//    infoWindowOptions.stationary = true;

var pnlStreetView = null;
var pnlCAD = null;
var pnlSPI = null;

var divSVContent = null;
var divCADContent = null;
var divSPIContent = null;

var panelContainer = [];

var tab_map = null;

function DisplayStreetView()
{
    //var oLatLng = new AGCoord(-28.2751829172523, 25.0430317799304);
    if(tileLayer == null)
    {        
		//g_map.centreAndScale(oLatLng, 6);
        var oDmsOptions = new AGDMSOptions();
        oDmsOptions.mapServerUrl = "http://196.35.44.6/mapserver/im.aspx";
        oDmsOptions.layers = "AG_PANO_SV_COVERAGE,AG_PANO_SV";
        oDmsOptions.styles = "Polyline_SCHEME,Point_SCHEME";
        
        oDmsOptions.transparency = 100;
        var dmsReqManager = new AGDMSRequestManager(oDmsOptions);
        
        tileLayer = new AGTileLayerOverlay(100,dmsReqManager);
        g_map.addOverlay(tileLayer);
        
        //document.getElementById('btnStreetView').innerHTML = "StreetView <img  border='0' src='images/Tick3.gif'/>";
        svDisplaying = true;
        SetStreetViewIsActive();
        AfriGISEyeCaller = "SVTowns";
        GetAfriGISEyeResult("ashx/GetJSONAfriGISEyeInfo.ashx?CallPage=GetStreetViewTownsHandler.ashx");
        
        var activeStyle ={
             'background-color' : '#F8F8F8',
             'color' : 'black',
             'border-width' : '1px',
             'border-style' : 'solid',
             'border-color' : '#6A6A36',
             'padding' : '1px',
             'font-weight' : 'bold',
             'font-style' : 'normal',
             'font-size' : '10pt',
             'width' : '100px'
             };
        
         var inactiveStyle = {
             'background-color' : '#E4E6E5',
             'color' : 'black',
             'border-width' : '1px',
             'border-style' : 'solid',
             'border-color' : '#6A6A36',
             'padding' : '0',
             'font-weight' : 'normal',
             'font-style' : 'italic',
             'font-size' : '10pt',
             'width' : '100px'
             };

         var oAGInfoDisplayPanelOptions = new AGInfoDisplayPanelOptions(activeStyle,inactiveStyle);        
         g_map.setInfoDisplayPanelOptions(oAGInfoDisplayPanelOptions);
         AGEvent.addListener(g_map.getInfoDisplay(),"onpanelchange", OnPanelChange);
         AGEvent.addListener(g_map.getInfoDisplay(),"oncloseclick", CloseInfoDisplay);                 
    }
    else
    {
        //var element = document.getElementById('btnStreetView');
        //var divSV = document.getElementById("dvBtnStreetView");
        if(!svDisplaying)
        {
            svDisplaying = true;
            SetStreetViewIsActive();
		    //g_map.centreAndScale(oLatLng, 6);
		    AfriGISEyeCaller = "SVTowns";
            GetAfriGISEyeResult("ashx/GetJSONAfriGISEyeInfo.ashx?CallPage=GetStreetViewTownsHandler.ashx");
            tileLayer.show();
            //element.innerHTML = "StreetView <img  border='0' src='images/Tick3.gif'/>";
        }
        else
        {
            svDisplaying = false;
            SetStreetViewIsActive();
            AGEvent.removeListener(svtZoomListener);
            g_map.removeGroupOverlay("SVT");
            g_map.removeGroupOverlay("svMarker");
            defaultMarker = null;
            tileLayer.hide();
            //element.innerHTML = "StreetView";
            //divSV.style.display = "none";            
        }
    }
}

LoadStreetViewItem = function(Item)
{
    //var s1 = "";
    //s1 += Item.StreetviewItem[0].AG_SV_ID;
    strUrlFormat = "";
    strUrlFormat += "1";
    strUrlFormat +=  "|" + Item.StreetviewItem[0].Latitude;
    strUrlFormat +=  "|" + Item.StreetviewItem[0].Longitude;   
    strUrlFormat +=  "|" + Item.StreetviewItem[0].Name;

    strUrlFormat +=  "|Street" //+ Item.StreetviewItem[0].Category;

    strUrlFormat +=  "|" + _PANO_IMAGES_URL_SV + Item.StreetviewItem[0].SubDir + "/" + Item.StreetviewItem[0].FileName;        // image url

    //s1 +=  "|" + 0;     //Item.NorthXOffset;    
    //s1 +=  "|" + Item.StreetviewItem[0].Neighbours.length;
    
    //firstNode = s1;
    //Called in POI_360.js
    setTimeout("initSVFlash();",0);

}

function LoadSPIContent()
{
    /*var title = document.createElement("span");
    title.innerHTML = "Click image to obtain this suburb's report";
    title.className = "SPITitle";
    divSPIContent.appendChild(title);*/
    var spiImg = document.createElement("img");
    spiImg.setAttribute("id", "spiImage");
    spiImg.setAttribute("src", "Images/SPIad_500x380.gif");
    spiImg.className = "SPIContainer";
    spiImg.onclick = SPIPopupInfo;
    divSPIContent.appendChild(spiImg);       
}

function SPIPopupInfo()
{
    
    var oCoords = defaultMarker.getCoord();
    var url = "SPISuburbReport.aspx?lat=" + oCoords.latitude() + "&lon=" + oCoords.longitude();
    window.open(url, "myWindow");        
    //alert(oCoords.longitude() + ", " + oCoords.latitude());        
}

function OnPanelChange(iIndex)
{
    if(iIndex==1)
    {
        if(tab_map == null)
        {
            oCoord = defaultMarker.getCoord();
            tab_map = new AGMap(document.getElementById("cadContent"));
            tab_map.centreAndScale(oCoord,18);
            
            var ctrlPos = new AGControlPosition( new AGPoint(10,10), AGAnchor.TOP_LEFT);
            var zoomCtrl = new AGZoomControl(8);
            tab_map.addControl(zoomCtrl,ctrlPos);
            
            var oDmsOptions = new AGDMSOptions();
            oDmsOptions.mapServerUrl = "http://ms1.afrigis.co.za/mapserver/im.aspx";
            oDmsOptions.layers = "AG_CAD_ERVEN,AG_NAD";
            oDmsOptions.styles = "Polygon_SCHEME,Point_SCHEME";
            
            oDmsOptions.transparency = 100;
            var dmsReqManager = new AGDMSRequestManager(oDmsOptions);
            
            var cadLayer = new AGTileLayerOverlay(100,dmsReqManager);
            tab_map.addOverlay(cadLayer); 
            
            var selControls = document.getElementById("selectionControlsContainerLS");
            if (!selControls)
            {
                selControls = document.createElement("div");
                selControls.setAttribute("id", "selectionControlsContainerLS");
                selControls.className = "selectionControlsContainerClass";
                var selOptions = document.createElement("select");
                selOptions.setAttribute("id", "selLayerLS");
                var infoBtn = document.createElement("input");
                infoBtn.setAttribute("id", "btnGetCoordinateLS");
                infoBtn.setAttribute("type", "button");
                infoBtn.setAttribute("value", "i");
                infoBtn.onclick = GetCoordinateFromMapClick;
                selControls.appendChild(selOptions);
                selControls.appendChild(infoBtn);
                document.body.appendChild(selControls);
            }
            
            var recordInfo = document.getElementById("recordInfoContainerLS");
            if (!recordInfo)
            {
                recordInfo = document.createElement("div");
                recordInfo.setAttribute("id", "recordInfoContainerLS");
                recordInfo.className = "recordInfoContainerClass";
                var recordAlignment = document.createElement("div");
                recordAlignment.setAttribute("id", "recordInfoAlignmentLS");
                recordAlignment.className = "recordInfoAlignmentClass";
                recordInfo.appendChild(recordAlignment);
                document.body.appendChild(recordInfo);
            }
            
            PopulateLayerDropDown();
            InitControls();           
        }
    }
}

function CloseInfoDisplay()
{
    tab_map = null;
}


function PopulateLayerDropDown() 
{           
    AddLayerToDD("selLayerLS", "Province", "AG_PROVINCES", false);
    AddLayerToDD("selLayerLS", "Town", "AG_TOWNS", false);
    AddLayerToDD("selLayerLS", "Suburb", "AG_SUBURBS", false);
    AddLayerToDD("selLayerLS", "CAD", "AG_CAD_ERVEN", false);
    AddLayerToDD("selLayerLS", "NAD", "AG_NAD", true);
    AddLayerToDD("selLayerLS", "Streets", "AG_STREETS", false);
}                    

function InitControls() 
{
    //Move the map buttons into position
    var oBtns = document.getElementById("selectionControlsContainerLS");
    var oMapContainer = document.getElementById("cadContent");
    var oRecordInfo = document.getElementById("recordInfoContainerLS");

    oMapContainer.appendChild(oBtns);
    oMapContainer.appendChild(oRecordInfo);

    //Make visible
    oBtns.style.visibility = "visible";
}

function AddLayerToDD(dropDownMenuName, displayName, layerName, isSelected) 
{
    var newOption = document.createElement("option");
    document.getElementById(dropDownMenuName).options.add(newOption);
    newOption.innerHTML = displayName;
    newOption.value = layerName;
    newOption.selected = isSelected;
}    

var singleMapClickListener = null;
function GetCoordinateFromMapClick() 
{
        //g_map.GetCoordinateFromMap(true, "GetClickedPoint");
        AGEvent.clearListeners(tab_map, "onclick");
        singleMapClickListener = AGEvent.addListener(tab_map, "onclick", function(oOverlay, coordinates){
            if(coordinates)
            {
                var latitude = coordinates.latitude();
                var longitude = coordinates.longitude();            
                var layerName = document.getElementById("selLayerLS").value;
                var selectedIndex = document.getElementById("selLayerLS").selectedIndex;             
                var layerDisplayName = document.getElementById("selLayerLS").options[selectedIndex].text;
                var oLatLng = new AGCoord(latitude, longitude);
                var pixels = tab_map.getPointFromVisibleArea(oLatLng);
                var oBoundingBox = tab_map.getBoundingBox();
                var oSouthWestCoords = oBoundingBox.getSouthWest();
                var oNorthEastCoords = oBoundingBox.getNorthEast();
                var boundingBox = oSouthWestCoords.longitude() + "," + oSouthWestCoords.latitude() + "," + oNorthEastCoords.longitude() + "," + oNorthEastCoords.latitude();
                var dimensions = tab_map.getSize();
                document.getElementById("recordInfoAlignmentLS").innerHTML = "Loading...";
                //alert((_clickedCoordinate[0].Latitude).toString() + " : " + (_clickedCoordinate[0].Longitude).toString());
                //GetJSONData("GetLayerInfo.aspx", "parseJSON", latitude, longitude, layerName);
                tab_map.removeGroupOverlay("infoMarker");
                GetJSONData("GetLayerInfo.aspx", "parseJSON", pixels.x, pixels.y, boundingBox, dimensions.width, dimensions.height, layerName);
                var oIcon = new AGIcon();
                oIcon.image = "Images/3Dpin_afrigispointofinterest32.png";
                oIcon.iconSize = new AGSize(32, 32);
                oIcon.iconAnchor = new AGPoint(-5, -32);
                var oNewMarkerOptions = new AGMarkerOptions(oIcon);
                tab_map.addOverlay(new AGMarker(oLatLng, oNewMarkerOptions), "infoMarker");
                //g_map.AddPoint("http://maps.afrigis.co.za/msjsapi/Images/3Dpin_afrigispointofinterest32.png","img1", latitude, longitude,-5,-32, layerDisplayName, "Layer info displayed on the right.");                
        }    
    });        
}

function GetJSONData(url, callBackName, iPixel, jPixel, boundingBox, width, height, layerName)
{                
    if (url.indexOf("?") > -1)
        url += "&jsonp=" 
    else
        url += "?jsonp=" 
    url += callBackName + "&";
    url += "i="
    url += iPixel.toString() + "&";
    url += "j="
    url += jPixel.toString() + "&";
    url += "bb="
    url += boundingBox + "&";
    url += "width="
    url += width + "&";
    url += "height="
    url += height + "&";
    url += "layer=";
    url += layerName + "&";
    url += new Date().getTime().toString(); // prevent caching        
    
    /*$.getJSON(_url,
            function(json)
            {
                parseJSON(json);
            }
        );*/

    var script = document.createElement("script");        
    script.setAttribute("src",url);
    script.setAttribute("type","text/javascript");                
    document.body.appendChild(script);
}        

function parseJSON(JSONText)
{
    //var JSONText = "{'layer':'AG_NAD','attributes':[{'name':'AG_NAD_ID','value':473051},{'name':'ACCURACY','value':0},{'name':'STR_NUMBER','value':4},{'name':'STR_NAME','value':'GIRDLER'},{'name':'STR_TYPE','value':'STREET'},{'name':'STREET','value':'GIRDLER STREET'},{'name':'X','value':28.247850000000000},{'name':'Y','value':-25.739040000000000},{'name':'AG_SUB_ID','value':13776},{'name':'AG_SUB_CDE','value':'000635-013776'},{'name':'SUBURB','value':'COLBYN'},{'name':'POSTCODE','value':'0083'},{'name':'AG_SGTN_ID','value':32272},{'name':'SGTOWN','value':'Colbyn'},{'name':'AG_TOWN_ID','value':635},{'name':'TOWN','value':'PRETORIA'},{'name':'AG_MUN_ID','value':228},{'name':'MUN_CODE','value':'TSH'},{'name':'S12_NAME','value':'City of Tshwane'},{'name':'MUNIC','value':'Pretoria'},{'name':'AG_PROV_ID','value':3},{'name':'PROVINCE','value':'GAUTENG'},{'name':'SOURCE','value':'Original NAD'},{'name':'UPDATED','value':'20071106'}]}";
    var obj = eval( "(" + JSONText + ")");
    //var objCloseButton = document.getElementById("recordInfoCloseBtnContainer").style.visibility = "visible";
    document.getElementById("recordInfoContainerLS").style.visibility = "visible";
    document.getElementById("recordInfoAlignmentLS").innerHTML = ConstructRecordTableHTML(obj);
} 

function ConstructRecordTableHTML(obj)
{           
    var lat = 0, lon = 0;                       
	var recTbl = "<table id=\"tblRecordInfo\">";
	recTbl += "<thead><tr class=\"recTblTitle\"><td colspan=\"2\">Layer: " + obj.layer + "<img id=\"imgCloseButton\" src=\"Images/CloseButton1.jpg\" onclick=\"CloseRecInfoClick()\"/></tr>";
	recTbl += "<tr><td class=\"nameColHead\">Name:</td><td class=\"valueColHead\">Value:</td></tr></thead>";
	//create the body
	recTbl += "<tbody>";

	//For each record value, construct table rows
	for (i = 0; i < obj.attributes.length; i++)
	{
	    if (obj.attributes[i].name == "CENTROIDX")
	    {
	        lon = parseFloat(obj.attributes[i].value);
	    }
	    if (obj.attributes[i].name == "CENTROIDY")
	    {
	        lat = parseFloat(obj.attributes[i].value);
	    }
		recTbl += "<tr><td class=\"nameCol\">" + obj.attributes[i].name + "</td><td class=\"valueCol\">" + obj.attributes[i].value + "</td></tr>";
	}

	//Close the body
	recTbl += "</tbody>";
	//close the table
	recTbl += "</table>";
	
	if (lat != 0 && lon != 0)
	{
        tab_map.removeGroupOverlay("infoMarker");
        var oLatLng = new AGCoord(lat, lon);
        var oIcon = new AGIcon();
        oIcon.image = "Images/3Dpin_afrigispointofinterest32.png";
        oIcon.iconSize = new AGSize(32, 32);
        oIcon.iconAnchor = new AGPoint(-5, -32);
        var oNewMarkerOptions = new AGMarkerOptions(oIcon);
        tab_map.addOverlay(new AGMarker(oLatLng, oNewMarkerOptions), "infoMarker");
	    
	}

	return recTbl;

}

function CloseRecInfoClick() 
{
    AGEvent.removeListener(singleMapClickListener);
    document.getElementById("recordInfoContainerLS").style.visibility = "hidden";
    document.getElementById("recordInfoAlignmentLS").innerHTML = "";
    tab_map.removeGroupOverlay("infoMarker");
}

/*function AddCADMap(oCoord)
{
    var coords = oCoord.longitude() + "," + oCoord.latitude();        
    var wmsURL = "http://maps.afrigis.co.za/mapserver/im.aspx?REQUEST=GetMapAG&VERSION=1.0.0&LAYERS=AG_PROVINCES,AG_SUBURBS,AG_STREETS,AG_CAD_ERVEN,AG_NAD&STYLES=Mapstyle3,Mapstyle1,Mapstyle3,Polygon_SCHEME,Point_SCHEME&HEIGHT=360&WIDTH=480&FORMAT=image/png&CRS=EPSG:4326&BBOX=CENTRE:" + coords + ",5000&OPTIONS=SB,CN&EXCEPTIONS=INIMAGE";
    var cadImg = document.createElement("img");
    cadImg.setAttribute("id", "cadImage");
    cadImg.setAttribute("src", wmsURL);
    cadImg.className = "CADContainer";
    cadImg.setAttribute("onclick", "CalcCoord(event)");
    divCADContent.appendChild(cadImg);   
    /*var cadMap = document.getElementById("TabMap");
	tab_map = new AGMap(cadMap);
    tab_map.centreAndScale(oCoord, 17);
    divCADContent.appendChild(cadMap);   
 	var zoomControl = new AGZoomControl(5);
	var zcPosition = new AGControlPosition(new AGPoint(5, 5), AGAnchor.TOP_LEFT);		
	tab_map.addControl(zoomControl, zcPosition);
}

function CalcCoord(ev)
{   
    var cadMap = document.getElementById("cadImage");    
    var pointClicked = AGMouseManager.getMouseOffset(ev, cadMap);
    var width, height;
    width = cadMap.clientWidth;
    height = cadMap.clientHeight;    
    var clickedCoord = PixelXYToMapCoord("27.994044,-25.915770,28.445320,-25.601530", width, height, pointClicked.x, pointClicked.y);
    var oCoord = eval(clickedCoord);
    //alert(clickedCoord);
    //alert(pointClicked.x + ", " + pointClicked.y);
}

function PixelXYToMapCoord(BoundingBox,MapWidth,MapHeight,PointX,PointY)
{
    arrBBox = BoundingBox.split(',')
    minLon = parseFloat(arrBBox[0])
    minLat = parseFloat(arrBBox[1])
    maxLon = parseFloat(arrBBox[2])
    maxLat = parseFloat(arrBBox[3])
    LonDiff = maxLon - minLon
    Latdiff = maxLat - minLat 
    xRel = PointX / MapWidth
    yRel = PointY / MapHeight
    dLon = (xRel * (LonDiff)) + minLon
    dLat = maxLat - (yRel * (Latdiff))
    return "{'Latitude:'" + dLat.toFixed(4) + "', Longitude:'" + dLon.toFixed(4) + "}";
}
/* Called in POI_360.js
function getFirstNode()
{
	return firstNode;
}
*/

/*function initSVFlash()
{
    var so = new SWFObject("EyeClient.swf", "pano", infoWindowOptions.width, infoWindowOptions.height, "9.0", "#FFFFFF");
    so.addParam("allowFullScreen","true");
    so.addParam("allowScriptAccess","always");
    so.write('flashObject');
}*/

function initSVFlash()
{
    ClearSwf();
    var checkDiv = document.getElementById("flashObject");
    if(!checkDiv)
    {
        var bubbleDiv = document.createElement("div");
        bubbleDiv.setAttribute("id", "flashObject");
        divSVContent.appendChild(bubbleDiv);
    }
    checkDiv = null;        

	var params = {
	  wmode: "opaque"
	};

	swfobject.embedSWF("EyeClient.swf", "flashObject", "500", "350", "9.0.0", "", "", params);			

    checkDiv = document.getElementById("svInfoDiv");
    if (!checkDiv)
    {
        var svInfoDiv = document.createElement("div");
        svInfoDiv.setAttribute("id", "svInfoDiv");
        svInfoDiv.className = "svInfoDiv";
        svInfoDiv.innerHTML = "";
        var divTip = document.createElement("div");
        divTip.innerHTML = "<span style='color:Red;font-weight:bold;'>Tip:</span> Rotate the picture by clicking and dragging the image or use the arrows in the compass.";
        divTip.setAttribute("id", "divTip");
        divTip.className = "svTip";
        var divDate = document.createElement("div");
        divDate.setAttribute("id", "divDate");
        divDate.className = "TimeStamp";
        svInfoDiv.appendChild(divTip);
        svInfoDiv.appendChild(divDate);
        divSVContent.appendChild(svInfoDiv);
        divDate.innerHTML = "";
        if (oResults != null)
            divDate.innerHTML = "Picture taken:  " + oResults.StreetviewItem[0].TimeStamp;
    }
    else
    {
        //checkDiv.innerHTML = "";
        var divDate = document.getElementById("divDate");
        if (oResults != null)
            divDate.innerHTML = "Picture taken:  " + oResults.StreetviewItem[0].TimeStamp;
    }
    checkDiv = null;
        
}


function CreateMarker(latitude, longitude)
{
        if(defaultMarker != null)
        {
            g_map.removeGroupOverlay("svMarker");
            defaultMarker = null;
        }            
        //g_map.centreAndScale(new AGCoord(latitude, longitude),17);            
        defaultMarker = new AGMarker(new AGCoord(latitude, longitude),defaultMarkerOption1);
        evtListenerClick = AGEvent.addListener(defaultMarker,"onmouseup",EventSelector);
        g_map.addOverlay(defaultMarker, "svMarker");
        pos = defaultMarker.getCoord();
        
        initPixel = g_map.getPointFromMap(pos);
        //SnapToPoint();
}

function EventSelector(oCoord)
{    
    g_map.disableInfoDisplay();
    //newPos = defaultMarker.getCoord();
    newPos = oCoord;
    var curentPixel = g_map.getPointFromMap(newPos);
    if(curentPixel.x == initPixel.x && curentPixel.y == initPixel.y)
    {
        CentreInfoBubble(oCoord);
        ShowBubble();
    }    
    else
    {
        pos = newPos;
        SnapToPoint(oCoord.latitude(), oCoord.longitude());
    }
}

function SnapToPoint(lat, lon)
{
    var oCoord = new AGCoord(lat, lon);
    newPos = oCoord;
    var _url = "StreetView.aspx?Type=Coord&Lat=" + lat + "&Lon=" + lon + "&Radius=0.07";
    $.getJSON(_url,
                function(json)
                {
                    RecieveStreetClosest(json);
                }
            );    
}


function ShowBubble()
{
    CloseInfoDisplay();
    g_map.enableInfoDisplay();
    
    // Load StreetView content
    divSVContent = document.getElementById("svContent");
    if(!divSVContent)
    {
        divSVContent = document.createElement("div");
        divSVContent.setAttribute("id", "svContent");        
        //divSVContent.style.backgroundColor = "#F1F1F1";        
    }
    divSVContent.innerHTML = "";    
    LoadStreetViewItem(oResults);

    if (pnlStreetView == null)
    {        
        pnlStreetView = new AGInfoDisplayPanel("StreetView", divSVContent);                
    }
    else
    {
        pnlStreetView.content = divSVContent;
    }
    
    // Load CAD content
    divCADContent = document.getElementById("cadContent");
    if(!divCADContent)
    {
        divCADContent = document.createElement("div");
        divCADContent.setAttribute("id", "cadContent");
        //divCADContent.style.backgroundColor = "#F1F1F1";
        divCADContent.style.width = "498px";
        divCADContent.style.height = "378px";
        divCADContent.style.border = "solid 1px black";
        divCADContent.style.position = "relative";
    }
    //AddCADMap(defaultMarker.getCoord());
    
    if (pnlCAD == null)
    {
        pnlCAD = new AGInfoDisplayPanel("Cadastre", divCADContent);            
    }
    else
    {
        pnlCAD.content = divCADContent;
    }
    
    // Load SPI content
    divSPIContent = document.getElementById("spiContent");
    if(!divSPIContent)
    {
        divSPIContent = document.createElement("div");
        divSPIContent.setAttribute("id", "spiContent");
        //divCADContent.style.backgroundColor = "#F1F1F1";
        divSPIContent.style.width = "500px";
        divSPIContent.style.height = "380px";
        divSPIContent.style.position = "relative";
    }
    divSPIContent.innerHTML = "";    
    LoadSPIContent();
    
    if (pnlSPI == null)
    {
        pnlSPI = new AGInfoDisplayPanel("PropertySPI", divSPIContent);            
    }
    else
    {
        pnlSPI.content = divSPIContent;
    }
        
    if (panelContainer.length == 0)
    {
        panelContainer.push(pnlStreetView);
        panelContainer.push(pnlCAD);
        panelContainer.push(pnlSPI);
    }
    
    defaultMarker.openInfoDisplayPanelsHTML(panelContainer, infoWindowOptions);
}


function RecieveStreetClosest(results)
{   
    oResults = results
    if(oResults == null)
    {
        //alert('No Data Found. Move marker to StreetView \'crumbs\'');
        if(prePosition != null)
        {
            if(defaultMarker != null)            
                defaultMarker.setCoord(prePosition);
        }
    }
    else
    {
        if(defaultMarker == null)
        {
            CreateMarker(parseFloat(oResults.StreetviewItem[0].Latitude), parseFloat(oResults.StreetviewItem[0].Longitude));
        }    
        var newLatLng = new AGCoord(parseFloat(oResults.StreetviewItem[0].Latitude), parseFloat(oResults.StreetviewItem[0].Longitude));
        defaultMarker.setCoord(newLatLng);
        pos = newLatLng;
        initPixel = g_map.getPointFromMap(pos);
        prePosition = pos;
        CentreInfoBubble(newLatLng);
        ShowBubble();
    }
}

function ParseSVTownsResult(json)
{
        if(json.result[0].Error == null)
        {
            var svAGTownIDs = new Array();
            var svTownNames = new Array();
            var svLongitude = new Array();
            var svLatitude = new Array();
            svtCount = json.result.length;
            for(var i=0; i<svtCount;i++)
            {
                svAGTownIDs[i] = json.result[i].Id;
                svTownNames[i] = json.result[i].Town;
                svLongitude[i] = json.result[i].Lon;
                svLatitude[i] = json.result[i].Lat;
                
                var oLatlng = new AGCoord(svLatitude[i], svLongitude[i]);            
                imgObj=document.createElement("div");
                imgObj.setAttribute;
                imgObj.setAttribute("id", "svtImage" + i.toString());
                imgObj.innerHTML = "<img style='cursor:pointer;' src ='Images/streetIcon2.gif' title=\"" + svTownNames[i] + "\" onclick='SnapToPoint(" + oLatlng + ");'/>";
                var myHTMLOptions = new AGHTMLOverlayOptions(new AGPoint(-8, -8));
                var myHTMLOverlay = new AGHTMLOverlay(imgObj, oLatlng, myHTMLOptions);
                g_map.addOverlay(myHTMLOverlay, "SVT");
            }
            svtZoomListener = AGEvent.addListener(g_map, "onzoomend", ChangeStreetViewVisibility);
            ChangeStreetViewVisibility(0, g_map.getZoomLevel()); //Initial call to determine display
        }
        else
        {
            alert(json.result[0].Error);
        }
}

function ChangeStreetViewVisibility(prevZoomLevel, curZoomLevel)
{
    var element;
    //var divSV = document.getElementById("dvBtnStreetView");
    if(curZoomLevel > 12)
    {
        for(var i=0;i<svtCount;i++)
        {
            element = document.getElementById("svtImage" + i.toString());
            element.className = "hideSVTowns";
            svVisible = false;
            //divSV.style.display = "";
        }
    }
    else
    {   
        g_map.removeGroupOverlay("svMarker");
        defaultMarker = null;
        for(var i=1;i<svtCount;i++)
        {
            element = document.getElementById("svtImage" + i.toString());
            element.className = "showSVTowns";
            svVisible = true;
            //divSV.style.display = "none";
        }            
    }
}

function SetStreetViewIsActive()
{
    var element = document.getElementById("dvBtnStreetView");
    if(svDisplaying)
    {
        element.className = "MapButtonsSelected";
        svActiveListener = AGEvent.addListener(g_map, "onclick", JumpToStreetPoint);
    }
    else
    {
        element.className = "MapButtons";
        AGEvent.removeListener(svActiveListener);
        svActiveListener = null;
    }        
}

function JumpToStreetPoint(oMarker, oCoord)
{
    SnapToPoint(oCoord.latitude(), oCoord.longitude());
}

