﻿//GEORSS
//http://rbrundritt.wordpress.com/2010/12/10/georss-support-for-bing-maps-v7-ajax-control/

/// <reference path="/default.aspx" />
/// <reference path="/geot.aspx" />


var startLocation = new Microsoft.Maps.Location(59.9803, 14.1705);
var layer;
var ZeroForUnauth;
var map;
//self.setTimeout("showLatestAdds()", 1);
function pageLoad() {
    //map = new Microsoft.Maps.Map(document.getElementById('startMap'), { enableClickableLogo: false, enableSearchLogo: false, showMapTypeSelector: false, credentials: 'AtVJ4fvQ0ixRyUxaCOAq6HccENdwLqRtUik90LAoDy538q5-CIaab3fxbNE8s23R', center: new Microsoft.Maps.Location(59.9803, 14.1705), zoom: 5 });
    map = new Microsoft.Maps.Map(document.getElementById('startMap'), { enableClickableLogo: false, enableSearchLogo: false, showMapTypeSelector: false, credentials: 'AnwP-2xCpJLa8B-N7v13fkrFcmNfrq41C71hDO85r2xvQLjO9Yd6GtL8UtI3bCOe', center: new Microsoft.Maps.Location(59.9803, 14.1705), zoom: 5 });
    
    //map = new VEMap("startMap");
//    map.LoadMap(startLocation, 5, VEMapStyle.Road, false, VEMapMode.Mode2D, false);
//    map.HideScalebar();
    //map.ShowMiniMa(390, 260);
//    //map.AttachEvent("onmouseover", ShapeHandler);
    //    //map.AttachEvent("onmouseout", ShapeHandler);
    
    var city = $get("city").value
    switch(city)
    {
        case "sthlm":            
          zoomCity(59.32793572139082, 18.063583374023444, 1, 'Senast i Stockholm');
          break;
        case "gbg":
          zoomCity(57.70011145457481, 11.96754455566406,2,'Senast i Göteborg')
          break;
        default:
            showLatestAdds(false); 
    }
//    //Detect if browser is Firefox 3.5
//    if (navigator.userAgent.indexOf("Firefox/3.5") != -1) {
//        $get("startMap").addEventListener('DOMMouseScroll', WindowMouseWheelHandler, false);
//    }
}
function WindowMouseWheelHandler(e) {
    e.stopPropagation();
    e.preventDefault();
    e.cancelBubble = false;
    return false;
}
//function ShapeHandler(e) {
//    if (e.elementID != null) {
//        var shape = map.GetShapeById(e.elementId);
//        map.ShowInfoBox(shape, new VEPixel(0, 0));
//        //document.getElementById('resultDiv').innerHTML = e.eventName + " event occurred on shape (id=" + e.elementID + ").";
//        }
//    else 
//        {
//            map.HideInfoBox();
//        }
//    }

function openwindow(target) 
{
    window.open(target, "_blank", "status=1,scrollbars=1,toolbar=1,resizable=1,menubar=0,location=0"); 
} 
 

function showLatestAdds(doCenterAndZoom) {    
    var time=new Date().getTime();
    var aid = $get("addId").value + "," + time;
    ZeroForUnauth = $get("addId").value;
    var link = "/RetrieveService.svc/GetPolygon/" + aid;   //+ $get("txtId").value;
//    $.ajax({
//        type: "GET",
//        url: link,
//        dataType: "xml",
//        success: function (xml) {
//            GetPolygon_Complete(xml);
//        },
//        error: function (xhr, ajaxOptions, thrownError) {
//            alert(thrownError.description);
//        }
//    });
    LoadGeoRSS(link, doCenterAndZoom );
   //$.get(request, GetPolygon_Complete);
    //VEDataType.ImportXML   VEDataType.GeoRSS,
//        var layer = new VEShapeLayer();
//        var layerSpec = new VEShapeSourceSpecification(VEDataType.GeoRSS, request, layer);
    //        map.ImportShapeLayerData(layerSpec, GetPolygon_Complete, true);  
   
        
}

function LoadGeoRSS(url, doCenterAndZoom) {
    map.entities.clear();

    //Define default shape options

    var polylineOptions = {
        fillColor: new Microsoft.Maps.Color(156, 0, 0, 255)
    };

    var polygonOptions = {
        fillColor: new Microsoft.Maps.Color(156, 0, 0, 255),
        strokeColor: new Microsoft.Maps.Color(156, 0, 255, 0)
    };

    var layer = new GeoRSSLayer(null, polylineOptions, polygonOptions);
    layer.LoadGeoRSS(url, function (items) {
        map.entities.push(items);
        if (doCenterAndZoom) {
            map.setView({ bounds: layer.GetBounds() });
        }
      
       
    });
}
function GetPolygon_Complete(xml) {
    
//    alert('RSS or Collection loaded. There are ' + result.GetShapeCount() +
    //               ' items in this list.');

    //var numShapes = result.GetShapeCount();
    
    var hitSpan=$get("spanHits");
    if(hitSpan!=null){
       hitSpan.innerHTML = numShapes.toString();  
    }
    var addUL = $get("addlistScroll");
    addUL.innerHTML = "";
    if (ZeroForUnauth != 0) {
        var liItem = document.createElement('li');
        liItem.innerHTML = "<a href='javascript:Refresh(0);'><img src='/img/Refresh16.png' /> Uppdatera karta och lista</a>"
        try {//For FIREFOX
            addUL.appendChild(liItem, null);
        }
        catch (e) {//For IE
            addUL.appendChild(liItem);
        }
    }
    var fake=false;
    //for (var i = 0; i < numShapes; ++i) {
    //Read RSS itms
    $(xml).find("item").each(function () {
        var s = parseGeoRSSItem($(this));
        //if (shape != null) {
          //  items.push(shape);
        //}
    //});
    //$.each(result.xml, function (i, value) {
        //var s = result.GetShapeByIndex(i);
        var listItem = document.createElement('li');

        if (s.Title == "Fake") {
            if (ZeroForUnauth != 0) {
                $get("spanHits").innerHTML = "0";
            }
            //map.Clear();
            map.DeleteShape(s);
            map.SetCenterAndZoom(startLocation, 5);

            listItem.innerHTML = "<a href='javascript:void(0);'>Saknas</a>"
            fake = true;
        }
        else {
            //var icon = "<div style='font-size:12px;font-weight:bold;border:solid 2px Black;background-color:Aqua;width:50px;'>Shape</div>";
            //var icon = "<div><img src='img/greendot.png' /></div>";
            //var icon = "<div>" + s.IconId + "</div>";
            //var icon=s.IconId;            
            s.SetCustomIcon(s.IconId);
            //listItem.innerHTML = "<a href='javascript:zooma(" + s.Latitude + "," + s.Longitude + ");'><img height='12px' src='" + s.IconId + "' />" + s.Title + "</a>";
            listItem.innerHTML = "<a href='javascript:zooma(" + s.Latitude + "," + s.Longitude + ",\"" + s.GetId() + "\");' title=\"Klicka för att zooma. En gång till för info. Blå prick för hela annonsen.\">" + "<div class=\"img12\">" + s.IconId + "</div>" + s.Title + "</a>";
        }
        try {//For FIREFOX
            addUL.appendChild(listItem, null);
        }
        catch (e) {//For IE
            addUL.appendChild(listItem);

        }
    });
   

}

var previousId = "";
function zooma(lat, lon, id) {
    //var Location = new VELatLong(lat, lon);
    //var mapCenterLocation = map.GetCenter();
    var location = new Microsoft.Maps.Location(lat, lon);
   
    if (id==previousId) {
//        var shape = map.GetShapeByID(id);
        //        map.ShowInfoBox(shape);      
    }
    else {
        //map.HideInfoBox();
        map.setView({ zoom: 10, center: location });
        //map.SetCenterAndZoom(Location, 13);
        previousId=id;
    }
}

function zoomCity(lat, lon, cityId, stad) {
    clearInfoBox();
    map.entities.clear();
    var time=new Date().getTime();
    var id = cityId + "," + time;
    ZeroForUnauth = $get("addId").value;
    var request = "/RetrieveService.svc/GetPolygon/" + id;   
//    var layer = new VEShapeLayer();
//    var layerSpec = new VEShapeSourceSpecification(VEDataType.GeoRSS, request, layer);
//    var layer = new Microsoft.Maps.TileSource();
//    var layerSpec =  new Microsoft.Maps.TileLayer({ mercator: tileSource}); 
//    map.ImportShapeLayerData(layerSpec, GetPolygon_Complete, true);
    $get("NavRubrik").innerHTML = stad;
    LoadGeoRSS(request, true);
    var location = new Microsoft.Maps.Location(lat, lon);
    map.setView({ zoom: 10, center: location });

}

function clearInfoBox() {
    //var infobox = document.getElementById('infoBox');
    var ibTitle = document.getElementById('ibTitle');
    ibTitle.innerHTML ="";
    var ibDescription = document.getElementById('ibDescription');
    ibDescription.innerHTML ="";
    //infoBox.style.visibility = "hidden";
}
