var _PANO_IMAGES_URL_SV = "http://maps.yellowpages.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 = 400;
infoWindowOptions.height = 280;
//    infoWindowOptions.stationary = true;

var divSVContent = null;
var AfriGISEyeCaller = "SVTowns";

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://maps.yellowpages.co.za/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");
    }
    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);

}

// Method called by FlashObject - NB! Only implement here!
function getFirstNode() {
	return strUrlFormat;
}

function initSVFlash()
{
    ClearSwf();
    var checkDiv = document.getElementById("flashObject");
    if(!checkDiv)
    {
        var bubbleDiv = document.createElement("div");
        bubbleDiv.setAttribute("id", "flashObject");
        divSVContent.appendChild(bubbleDiv);
    }
    checkDiv = null;        

	swfobject.embedSWF("EyeClient_yp.swf", "flashObject", "400", "250", "9.0.0");			

    checkDiv = document.getElementById("divDate");
    if (!checkDiv)
    {
        var divDate = document.createElement("div");
        divDate.setAttribute("id", "divDate");
        divDate.className = "TimeStamp";
        divSVContent.appendChild(divDate);
        divDate.innerHTML = "";
        if (oResults != null)
            divDate.innerHTML = "Picture taken:  " + oResults.StreetviewItem[0].TimeStamp;
    }
    else
    {
        checkDiv.innerHTML = "";
        if (oResults != null)
            checkDiv.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()
{
    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);

    defaultMarker.openInfoDisplay(divSVContent, 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());
}

function GetAfriGISEyeResult(url)
{    
    $.getJSON(url, 
        function(json)
        {
            if(AfriGISEyeCaller == "POI")
                ParsePOIResult(json);
            if(AfriGISEyeCaller == "SVTowns")
                ParseSVTownsResult(json);    
        });
}

function CentreInfoBubble(oCoord)
{
    var curZoomLevel = g_map.getZoomLevel();
    if(curZoomLevel > 15)
    {
        g_map.centreAndScale(oCoord, curZoomLevel);
    }
    else
    {            
        g_map.centreAndScale(oCoord, 16);
        curZoomLevel = 16;
    }
    var curMapSize = g_map.getSize();
    //calculation to place POI info window in the centre of the current viewable map
    var newCoord = null;
    var curWidth = curMapSize.width;
    var curHeight = curMapSize.height;
    if ((curWidth - infoWindowOptions.width) > 0 && (curHeight - infoWindowOptions.height > 0))
    {
        var newX = parseInt((curWidth - (infoWindowOptions.width + (curWidth*0.1)))/2); // add 10% to width (leftwards shift) to compensate for map controls
        var newY = parseInt((curHeight - (infoWindowOptions.height + (curHeight*0.2)))/2); // add 20% to height (downwards shift) to compensate for the bubble's stem
        newCoord = g_map.getCoordFromVisibleArea(new AGPoint(curWidth-newX, newY));
    }
    else
    {
        newCoord = g_map.getBoundingBox().getNorthEast();
    }

    g_map.centreAndScale(newCoord, curZoomLevel);
}

function ClearSwf() {
	var c = document.getElementById("flashObject");
	if(c) 
	{
		swfobject.removeSWF("flashObject");
		c=null;
	}
}
