﻿var map = null;
var div = null;
var notOver = false;
var crunchedLayerManager = null;
var hittautMapVisible = true;
var hittautMapMaximal = false;

var hittautUnikVariabel = new Array();

var ve_checkpoints = new Array();
var ve_sponsors = new Array();
//alert(dump(ve_checkpoints));
//var cps = new Array();
var checkpointNumbers = new Array();
var checkpointNumbersUsed = new Array();
//var checkpointLevels = new Array();
//var checkpointSponsors = new Array();

jQuery(document).ready(function() {
    LoadTheMap();
});

function failedLoadCheckpoints(error) {
    alert(dump(error));
}

function loadCheckpoints(results) {
    eval('json = ' + results);
    cps = json['NewDataSet']['Projects'];

    for (var i = 0; i < cps.length; i++) {
        //alert(dump(cps));
        addCheckpointToMap(cps[i]);
    }
}

function loadLevels(results) {
    eval('json = ' + results);
    json = json['NewDataSet']['Projects'];
    //alert(dump(json));
    for (i=0, l = json.length; i<l; i++) {
        checkpointLevels[json[i]['LevelId']] = json[i];
    }
    //alert(dump(checkpointLevels));
}

function loadSponsors(results) {
    eval('json = ' + results);
    json = json['NewDataSet']['Projects'];
    //alert(dump(json));
    for (i = 0, l = json.length; i < l; i++) {
        //alert(dump(json[i]));
        checkpointSponsors[json[i]['SponsorId']] = json[i];
    }
}

/**
 * Returns the merest number not used as a checkpoint number
 * 
 * @returns the merest number not used as a checkpoint number (between 0 and infinity
 */
function getNextFreeCheckpointNumber() {
    for (var i = 1; checkpointNumbersUsed[i] != null; i++) {
        ;
    }
    return i;
}

/**
 * Adds a new checkpoint to the map
 *
 * @param array for checkpoint properties.
 *        cp = {'number': 1, 
 *              'name': 'Checkpoint Stadsparken', 
 *              'level': 1,                         //mandatory
 *              'lat': 57.783198,                   //mandatory
 *              'long': 14.139463 };                //mandatory
 * 
 * @returns the merest number not used as a checkpoint number (between 0 and infinity
 */
function addCheckpointToMap(cp, newCp) {

    //alert(dump(cp));
    if (!newCp) {
        cp['Lat'] = cp['Lat'].replace(',', '.');
        cp['Lon'] = cp['Lon'].replace(',', '.');
    }
    // Get pin style class name
    //alert(dump(checkpointLevels));
    //alert(cp['LevelId']);
    var pinStyle = checkpointLevels[cp['LevelId']]['PinStyle'];
    //alert(dump(cp));
    // If no number is assign, assign it the next free number
    if (!cp['Number']) {
        cp['Number'] = getNextFreeCheckpointNumber();

    }

    // If no name is defined, name the checkpoint "Checkpoint #nr"
    if (cp['NameSe'] == '') {
        var name = "Checkpoint " + cp['Number'];
    } else {
        var name = cp['NameSe'];
    }
    
    //cp['Lat'] = parseInt(cp['Lat']);
    //cp['Lon'] = parseInt(cp['Lon']);
    if (!newCp) {
        cp['state'] = 'unchanged';
    } else {
        cp['state'] = 'new';
    }
    // Creates the Checkpoint shape and add it to the map
    checkpoint = new VEShape(VEShapeType.Pushpin, new VELatLong(cp['Lat'], cp['Lon']));
    checkpoint.SetCustomIcon("<div class='" + pinStyle + "'><div class='text'>" + getCHeckpointNumberWithPrefix(cp['Number']) + "</div></div>");
    checkpoint.SetTitle("<div class='pinStyleHeader'>" + name + "</div>");
    checkpoint.SetDescription("<div class='pinStyleText'><b>Lat:</b> " + convertDDtoDMS(cp['Lat']) + " (DMS)<br/><b>Long:</b> " + convertDDtoDMS(cp['Lon']) + " (DMS)</div><div class='pinStyleText'><b>Lat:</b> " + cp['Lat'] + " (DD)<br/><b>Long:</b> " + cp['Lon'] + " (DD)</div>");
    map.AddShape(checkpoint);
    
    // Store current checkpoint data in tha checkpoints array with the internal VEShape ID as key
    ve_checkpoints[checkpoint.GetID()] = cp;
    //alert(dump(ve_checkpoints));
    
    //checkpointNumbers[cp['number']] = checkpoint.GetID();

    // Mark the current checkpoint's number as used by
    checkpointNumbersUsed[cp['Number']] = checkpoint.GetID();
    return checkpoint;
}

function getCHeckpointNumberWithPrefix(num)
{
    if (num > 1000) {
        number = num - 1000;
        number = "F" + number;
    }
    else {
        number = num;
    }
    return number;
}

/**
* Returns the pin style for the supplied level
*
* Currently the mapping betweenlevels and styles is hardcoded
* 1 = pinStyleGreen
* 2 = pinStyleBlue
* 3 = pinStyleRed
* 4 = pinStyleBlack
*
* @param int styleID the level
* 
* @returns the pin style for the supplied level
*/
/*function getPinStyle(styleID) {
    switch (styleID) {
        case 1:
            return 'pinStyleGreen';
            break;
        case 2:
            return 'pinStyleBlue';
            break;
        case 3:
            return 'pinStyleRed';
            break;
        case 4:
            return 'pinStyleBlack';
            break;

    }
}*/

function convertDDtoDMS(dd, accuracy) {
    if (typeof accuracy == "undefined") {
        accuracy = 4;
    }

    deg = parseInt(dd);
    dd = (dd - deg) * 60;
    min = parseInt(dd);
    sec = (dd - min) * 60

    return deg + '° ' + min + '\' ' + sec.toFixed(accuracy) + '"';
}

function MapModeChanged(e) {
    if (map.GetMapMode() == Msn.VE.MapActionMode.Mode3D && window.location.protocol == "file:") {
        alert("MapCruncher tiles will only display in 3D mode " +
    "if your map is hosted on a web server (using http://).\n" +
    "Currently, your tiles are coming from a local machine (file://) " +
    "so only 2D mode is available.");
    }
}

function GetSize() {
    var myWidth = 0, myHeight = 0;

    if (typeof (window.innerWidth) == 'number') {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }

    if (myWidth > 0) {
        var result = new Array();
        result[0] = myWidth;
        result[1] = myHeight;
        return result;
    }
    else {
        return null;
    }
}

function toggleSize() {
    var MaxMinButton = document.getElementById("MaxMinButton");
    var HittautLogo = document.getElementById("HittautLogo");

    if (hittautMapMaximal == false) {
        maxSize();
        MaxMinButton.innerText = "Visa mindre karta";
        hittautMapMaximal = true;
        HittautLogo.style.left = "609px";
        HittautLogo.style.top = "1px";
        map.AddControl(HittautLogo);
    }
    else {
        normalSize();
        MaxMinButton.innerText = "Visa större karta";
        hittautMapMaximal = false;
        HittautLogo.style.left = "382px";
        HittautLogo.style.top = "1px";
        map.AddControl(HittautLogo);
    }
}

function maxSize() {
    var div = document.getElementById("Map");
    var browserSize = GetSize();
    if (browserSize != null) {
        //div.style.width = (browserSize[0]) + "px";
        //div.style.height = (browserSize[1]) + "px";
        //div.style.width = "720px";
        div.style.height = (browserSize[1]-175) + "px";
        //div.style.top = "138px";
        //div.style.left = ((browserSize[0]/2)-462) + "px";
        //div.style.position = "absolute";
    }
    map.Resize((683), (browserSize[1]-175));

    var MapLinks = document.getElementById('MapLinks');
    MapLinks.style.position = "absolute";
    MapLinks.style.top = (browserSize[1] - 135) + "px";
    MapLinks.style.left = ((browserSize[0] / 2) - 462) + "px";
    MapLinks.style.width = "710px";

    map.ShowMiniMap(568, 50);
}

function normalSize() {
    var div = document.getElementById("Map");
    div.style.width = "493px";
    div.style.height = "160px";
    div.style.top = "";
    div.style.left = "";
    div.style.position = "relative";
    map.Resize((493), (160));

    var MapLinks = document.getElementById('MapLinks');
    MapLinks.style.position = "relative";
    MapLinks.style.top = "";
    MapLinks.style.left = "";
    MapLinks.style.width = "483px";

    map.HideMiniMap();
}

function SetMapSize(){
    var div = document.getElementById("Map");
    var browserSize = GetSize();
    if (browserSize != null) {
        div.style.height = (browserSize[1] - 60) + "px";
    }
    map.Resize((683), (browserSize[1] - 60));

//    var MapLinks = document.getElementById('MapLinks');
//    MapLinks.style.position = "absolute";
//    var browser=navigator.appName;
//    if (browser.indexOf("Microsoft") != -1) {
//        MapLinks.style.left = ((browserSize[0] / 2) - 630) + "px";
//        MapLinks.style.top = (browserSize[1] - 54) + "px";
//    }
//    else {
//        MapLinks.style.left = ((browserSize[0] / 2) - 640) + "px";
//        MapLinks.style.top = (browserSize[1] - 58) + "px";
//    }
//    MapLinks.style.display = "inline";
//    MapLinks.style.width = "675px";
}

function ToggleLayer() {
    var ToggleButton = document.getElementById("ToggleButton");

    if (hittautMapVisible == false) {
        crunchedLayerManager.layerList.find("SverigeKarta").Activate(map);
        hittautMapVisible = true;
        ToggleButton.innerText = "Dölj hittaut.nu-kartan";
    }
    else {
        crunchedLayerManager.layerList.find("SverigeKarta").Deactivate(map);
        hittautMapVisible = false;
        ToggleButton.innerText = "Visa hittaut.nu-kartan";
    }
}


function mouseOverSidebarItem(markerId) {
    //Update pushpin
    currentShape = map.GetShapeByID(markerId);
    //currentIcon = currentShape.GetCustomIcon();
    //currentShape.SetCustomIcon(currentIcon.replace('pinStyleBlue', 'pinStyleHover'));
    map.ShowInfoBox(currentShape);

    //Update side bar icon
    //var sideBarIconId = 'sideBarMarker_' + currentShape.GetID();
    //document.getElementById(sideBarIconId).className = 'pinHoverStyle';
}

function mouseOutSidebarItem(markerId) {
    //Update pushpin
    currentShape = map.GetShapeByID(markerId);
    //currentIcon = currentShape.GetCustomIcon();
    //currentShape.SetCustomIcon(currentIcon.replace('pinStyleHover', 'pinStyleBlue'));
    map.HideInfoBox(currentShape);

    //Update side bar icon
    //var sideBarIconId = 'sideBarMarker_' + currentShape.GetID();
    //document.getElementById(sideBarIconId).className = 'pinStyle';
}

function mouseOverHandler(e) {
    if (e.elementID && notOver) {
        mouseOverSidebarItem(e.elementID)
        notOver = false;
    }
}

function mouseOutHandler(e) {
    if (e.elementID && !notOver) {
        mouseOutSidebarItem(e.elementID)
        notOver = true;
    }
}



function LoadTheMap() {
    var div = document.getElementById("Map");
    div.style.width = "683px";
    div.style.overflow = "hidden";
    div.style.position = "relative";
    div.style.border = "1px solid black";
    //div.style.left = "-171px";
    //div.style.margin = "150px 0 0 0";
    //if (crunchedLayerManager != null) {
    //    crunchedLayerManager.controlManager.UpdateControlLayout();
    //}
    map = new VEMap("Map");
    map.LoadMap();
    map.AttachEvent("oninitmode", MapModeChanged);
    map.SetMapStyle(VEMapStyle.Aerial);
    map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);
    crunchedLayerManager = new VE.MapCruncher.CrunchedLayerManager(map);
    crunchedLayerManager.ImportLayersFromAnchorHRef("CrunchedLayers");

    SetMapSize();
    window.onresize = SetMapSize;
    map.ShowMiniMap(532, 50);

    var HittautLogo = document.getElementById('HittautLogo');
    HittautLogo.style.left = "574px";
    HittautLogo.style.top = "3px";
    HittautLogo.style.display = "inline";
    map.AddControl(HittautLogo);

    var MapLinks = document.getElementById('MapLinks');
    MapLinks.style.left = "424px";
    MapLinks.style.top = "3px";
    MapLinks.style.display = "inline";
    map.AddControl(MapLinks);

    // Attach the event handlers to the mouse 
    map.AttachEvent("onmouseover", mouseOverHandler);
    map.AttachEvent("onmouseout", mouseOutHandler);


    var layer = crunchedLayerManager.layerList.find("SverigeKarta");
    layer.Activate(map);
    layer.SetDefaultView(map);
    document.getElementById("VE_MapCruncher_legend_box").style.display = "none";

    
    //Adds checkpoint to the map
    //Checkpoints.getLevels(loadLevels, failedLoadCheckpoints);
    //Checkpoints.getSponsors(loadSponsors, failedLoadCheckpoints);
    //Checkpoints.getCheckpoints(loadCheckpoints, failedLoadCheckpoints);

    for (var i = 0; i < cps.length; i++) {
        addCheckpointToMap(cps[i]);
    }
    SponsorWidth = 0.0013;
    SponsorHeight = 0.00015;
    for (s in checkpointSponsors) {
        if (checkpointSponsors[s]['Lat'] != "" && checkpointSponsors[s]['Lon'] != "" && typeof(checkpointSponsors[s]['Lat']) != "undefined" && typeof(checkpointSponsors[s]['Lon']) != "undefined") {
            //alert(checkpointSponsors[s]['Lat']);
            var c1Lat = parseFloat(checkpointSponsors[s]['Lat'].replace(",", ".")) + SponsorHeight;
            var c1Lon = parseFloat(checkpointSponsors[s]['Lon'].replace(",", ".")) - SponsorWidth;

            var c2Lat = parseFloat(checkpointSponsors[s]['Lat'].replace(",", ".")) + SponsorHeight;
            var c2Lon = parseFloat(checkpointSponsors[s]['Lon'].replace(",", ".")) + SponsorWidth;

            var c3Lat = parseFloat(checkpointSponsors[s]['Lat'].replace(",", ".")) - SponsorHeight;
            var c3Lon = parseFloat(checkpointSponsors[s]['Lon'].replace(",", ".")) + SponsorWidth;

            var c4Lat = parseFloat(checkpointSponsors[s]['Lat'].replace(",", ".")) - SponsorHeight;
            var c4Lon = parseFloat(checkpointSponsors[s]['Lon'].replace(",", ".")) - SponsorWidth;

            var c5Lat = parseFloat(checkpointSponsors[s]['Lat'].replace(",", ".")) + SponsorHeight;
            var c5Lon = parseFloat(checkpointSponsors[s]['Lon'].replace(",", ".")) - SponsorWidth;
           
            var points = [new VELatLong(c1Lat, c1Lon), new VELatLong(c2Lat, c2Lon), new VELatLong(c3Lat, c3Lon), new VELatLong(c4Lat, c4Lon), new VELatLong(c5Lat, c5Lon)];

            var poly = new VEPolygon(checkpointSponsors[s]['SponsorId'], points, new VEColor(0, 150, 100, 0.0), new VEColor(0, 150, 100, 0.0), 1)
            ve_sponsors[checkpointSponsors[s]['SponsorId']] = poly;
            map.AddPolygon(poly);

            

            /*shape = new VEShape(VEShapeType.Polygon, points);
            shape.SetLineWidth(1);
            shape.SetLineColor(new VEColor(0, 150, 100, 0.0));
            shape.SetFillColor(new VEColor(0, 150, 100, 0.0));
            map.AddShape(shape);*/


        }
    }
    if (typeof(disableClickableSponsors) == "undefined" || !disableClickableSponsors) {
        map.AttachEvent("onclick", onClickHandlerSponsors);
    }
    var ProgressBar = document.getElementById("ProgressBar");
    ProgressBar.style.display = "none";
}

function onClickHandlerSponsors(e) 
{
    if (e.leftMouseButton && map.GetZoomLevel() > 13) {
        var pt = map.PixelToLatLong(new VEPixel(e.mapX, e.mapY));
        for (poly in ve_sponsors) {
            s = ve_sponsors[poly];
            /*var isInZone = 0;
            var j = ve_sponsors[poly].LatLongs.length - 1;
            for (var k = 0; k < ve_sponsors[poly].LatLongs.length; j = k++) {
                if ((((ve_sponsors[poly].LatLongs[k].Latitude <= pt.Latitude) && (pt.Latitude < ve_sponsors[poly].LatLongs[j].Latitude)) || ((ve_sponsors[poly].LatLongs[j].Latitude <= pt.Latitude) && (pt.Latitude < ve_sponsors[poly].LatLongs[k].Latitude))) && (pt.Longitude < (ve_sponsors[poly].LatLongs[j].Longitude - ve_sponsors[poly].LatLongs[k].Longitude) * (pt.Latitude - ve_sponsors[poly].LatLongs[k].Latitude) / (ve_sponsors[poly].LatLongs[j].Latitude - ve_sponsors[poly].LatLongs[k].Latitude) + ve_sponsors[poly].LatLongs[k].Longitude)) {
                    isInZone++;
                }
            }
            if ((isInZone % 2) == 0)
                alert('You clicked INSIDE the polygon');
            else
                alert('You clicked OUTSIDE the polygon');
            */
            if (typeof (s.LatLongs) != "undefined") {
                /*alert("Click: " + "Lat: " + pt.Latitude + "Lon: " + pt.Longitude + "\n" +
                "0: " + "Lat: " + new String(s.LatLongs[0].Latitude).substring(0, 15) + "Lon: " + new String(s.LatLongs[0].Longitude).substring(0, 15) + "\n" +
                "2: " + "Lat: " + new String(s.LatLongs[2].Latitude).substring(0, 15) + "Lon: " + new String(s.LatLongs[2].Longitude).substring(0, 15) + "\n"
                
                );*/

                if (pt.Latitude < new String(s.LatLongs[0].Latitude).substring(0, 15) && pt.Latitude > new String(s.LatLongs[2].Latitude).substring(0, 15) &&
                    pt.Longitude > new String(s.LatLongs[0].Longitude).substring(0, 15) && pt.Longitude  < new String(s.LatLongs[2].Longitude).substring(0, 15)) {
                    //alert('You clicked INSIDE the polygon');
                    window.open(checkpointSponsors[poly]['SponsorLink']);
                    return;
                }
            }
        }
        
        
    }
}

// Determines if a point is inside a polygon
