﻿
// disable buttons during partial page postbacks
var pbControlId = null;
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(
    function(sender, args) {
        var pbControl = args.get_postBackElement();  //the control causing the postback
        pbControlId = pbControl.id;
        pbControl.disabled = true;
    }
);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(
    function(sender, args) {
        if (pbControlId != null) {
            var pbControl = document.getElementById(pbControlId);
            if (pbControl != null)
                pbControl.disabled = false;
            pbControlId = null;
        }
    }
);


// resize the screen to fit the browser
function resizeMapToFit() {
    var mapDiv = document.getElementById("map_canvas");
    var mapMenuDiv = document.getElementById("map_menu");

    // first figure out the window dimensions
    var winW = 0, winH = 0;
    if (typeof (window.innerWidth) == 'number') {
        //Non-IE
        winW = window.innerWidth;
        winH = window.innerHeight;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode'
        winW = document.documentElement.clientWidth;
        winH = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        //IE 4 compatible
        winW = document.body.clientWidth;
        winH = document.body.clientHeight;
    }
    
    var w = winW * 1;
    var h = winH * 1;
    var X_OFFSET = 20; //(40 / 1440) * w;
    var Y_OFFSET = 75; //(75 / 1440) * w;
    var mapW = (w * 0.8) - X_OFFSET;
    var menuW = w - mapW - X_OFFSET;
    var mapH = h - Y_OFFSET;
    var menuH = h - Y_OFFSET;
    
    mapDiv.style.width = mapW + "px";
    mapDiv.style.height = mapH + "px";
    mapMenuDiv.style.width = menuW + "px";
    mapMenuDiv.style.height = menuH + "px";

    if (map) {
        setTimeout(function() {
            var customUI = map.getDefaultUI();
            customUI.maptypes.normal = false;
            customUI.maptypes.satellite = false;
            customUI.maptypes.hybrid = false;
            customUI.maptypes.physical = false;
            customUI.controls.scalecontrol = false;
            map.setUI(customUI);
        }, 1000);
    }
}
resizeMapToFit();


/////////////////////////////////////////////////////


var map = null;
var markers = new Array();
var currentTabName = null;
var xoffset = 0.5759239196777344;
var yoffset = 0.03914034216360973;
var ratio = 0.03515625;

var userMarker = null;

var userCat = null;
var userLocName = null;
var userLocDesc = null;

var locListSubCats = new Array();       // locListSubCats[rootBoxId][i] = id of another rootbox nested under rootBoxId
var locLists = new Array();             // locLists[rootBoxId][i] = a location checkbox id directly under the node
var locListBoxes = new Array();         // locListBoxes[locId][i] = all the checkboxes associated with locId
var categoryLocsCache = new Array();    // locListBoxes[catId][i] = all the checkboxes with category catId, including sub-categories
var categoryTree = new Array();         // categoryTree[parentCatId][i] = the locationcategoryid's of all direct child categories of parentCatId
var locsByStatus = new Array();         // locsByStatus[status] = all the checkboxes with PublicStatus of status

var showAcceptedBoxId = null;
var showSubmittedBoxId = null;
var showRejectedBoxId = null;

var mapIcons = new Array();

if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map_canvas"));
    map.setCenter(new GLatLng(0.0, 0.0), 13);
    map.setUIToDefault();

    var copyright = new GCopyright(1, new GLatLngBounds(new GLatLng(0, 0), new GLatLng(0, 0)), 7, "Darkfall (copyright Aventurine)");

    var copyrightCollection = new GCopyrightCollection('Map of');
    copyrightCollection.addCopyright(copyright);

    var tilelayers = [new GTileLayer(copyrightCollection, 9, 13)];
    tilelayers[0].getTileUrl = function(a, b) { return "/mapimages/" + b + "_" + a.x + "_" + a.y + ".jpg"; };

    var custommap = new GMapType(tilelayers, new GMercatorProjection(14), "Darkfall");

    map.addMapType(custommap);

    map.setCenter(new GLatLng(-0.69349, 0.528717), 10, custommap);

    var customUI = map.getDefaultUI();
    customUI.maptypes.normal = false;
    customUI.maptypes.satellite = false;
    customUI.maptypes.hybrid = false;
    customUI.maptypes.physical = false;
    customUI.controls.scalecontrol = false;
    map.setUI(customUI);

    userMarker_Create(new GLatLng(0, 0));
    userMarker.hide();

    // click event
    GEvent.addListener(map, "click", function(overlay, clickLatLng) {
        map.closeInfoWindow();
        if (clickLatLng) {
            if (userMarker.isHidden())
                userMarker.show();
            userMarker_MoveToReal(clickLatLng);
        }
    });

    // zoom event
    GEvent.addListener(map, "zoomend", function(oldLevel, newLevel) {
        //        for (var i in mapIcons) {
        //            mapIcons[i].iconSize = new GSize(25, 25);
        //        }

        //for (var i in markers) {
        //    markers[i].hide();
        //}
    });
}


function openMarkerInfo(marker, msg) {
    
    // i don't know why this works when it's inside a setTimeout and not when it's inline code, but whatever

    setTimeout(
        function() {
            var tabs = [
                new GInfoWindowTab("Info", "<iframe style='border:none;' src='LocInfo.aspx?LocationID=" + marker.ID + "' width=490 height=350>Your browser doesn't support HTML iframes.</iframe>")
                //, new GInfoWindowTab("Report Error", "<iframe src='LocError.aspx?LocationID=" + marker.ID + "' width=300 height=300>Your browser doesn't support HTML iframes.</iframe>")
            ];
            marker.openInfoWindowTabsHtml(tabs);
        },
        1
    );
}

function gameToReal(min, sec, d) {
    var x = (min * 1.0) + ((sec * 1.0) / 60.0);

    if (d == "W") {
        x = x * -1; // i.e treat 10W as -10E so the two coordinate systems are increasing in the same direction
        return (xoffset + (x * ratio));
    }
    else if (d == "E") {
        return (xoffset + (x * ratio));
    }
    else if (d == "S") {
        x = x * -1; // i.e. treat 10S as -10N so the two coordinate systems are increasing in the same direction
        return (yoffset + (x * ratio));
    }
    else if (d == "N") {
        return (yoffset + (x * ratio));
    }
    else {
        alert('unknown direction ' + d + ' in loc ' + min + '\'' + sec + d);
        return 0;
    }
}

function realToGame(lat, lng) {
   
    var x = (lng - xoffset) / ratio;
    var xDir = 'E';
    if (x < 0) {
        x = x * -1;
        xDir = 'W';
    }
    var xMin = Math.floor(x);
    var xSec = Math.round((x - xMin) * 60);

    var y = (lat - yoffset) / ratio;
    var yDir = 'N';
    if (y < 0) {
        y = y * -1;
        yDir = 'S';
    }
    var yMin = Math.floor(y);
    var ySec = Math.round((y - yMin) * 60);


    return xMin + '.' + xSec + '.' + xDir + '.' + yMin + '.' + ySec + '.' + yDir;
}


var currentTabId = null;
var currentTabTargetId = null;

function menuTab_Select(tabId, targetId, tabName) {
    if (currentTabId != null) {
        var prevTab = document.getElementById(currentTabId);
        var prevTarget = document.getElementById(currentTabTargetId);
        prevTab.className = "MapMenuTabUnselected";
        prevTarget.style.display = "none";
    }

    document.getElementById(tabId).className = "MapMenuTabSelected";
    document.getElementById(targetId).style.display = "block";

    currentTabId = tabId;
    currentTabTargetId = targetId;
    currentTabName = tabName;

}




//////////// WORK IN PROGRESS



function locList_Toggle(stateId, toggleId, locPanelId) {
    var toggle = document.getElementById(toggleId);
    var locPanel = document.getElementById(locPanelId);
    var state = document.getElementById(stateId);
    var imageText = "<img src='/images/toggleloading.gif' border=0>";

    // if already loading, do nothing
    if (toggle.loading) {
        return false;
    }
        
    if (state.value == "COL") {
        if (locPanel != null) {
            state.value = "EXP";
            toggle.innerHTML = "-";
            toggle.className = "LocListRootToggleCollapse";
            locPanel.style.display = "block";
            return false;
        }
        else {
            toggle.innerHTML = imageText;
            toggle.loading = true;
            return true;    // allow the postback to pull the panel from the server
        }
    }
    else {
        state.value = "COL";
        toggle.innerHTML = "+";
        toggle.className = "LocListRootToggleExpand";
        if (locPanel != null)
            locPanel.style.display = "none";
        return false;
    }
}


function locList_Click(cbId, parentVal) {

    var cb = document.getElementById(cbId);
    var catId = cb.getAttribute("LocationCategoryId");
    
    if (parentVal != undefined)
        cb.checked = parentVal;

    // for loclists that are bound to a location category
    if (catId != undefined && catId != null) {
    
        // recursively display all the locs and all the sub-categories
        locList_ToggleLocsByCatRecursive(catId, cb.checked);

        // check all sub-categories boxes (if they're rendered)
        if (locListSubCats[cbId] != undefined && locListSubCats[cbId] != null) {
            for (var i in locListSubCats[cbId]) {
                var subBox = document.getElementById(locListSubCats[cbId][i]);
                if (subBox)
                    subBox.checked = cb.checked;
            }
        }
    }
    
    // for loclists that are bound to a random collection of unrelated locs
    else {
        var locs = cb.getAttribute("LocationIds").split(',');

        for (var k = 0; k < locs.length; k++) {
            if (cb.checked) {
                locList_ShowMarker(locs[k], false);
            }
            else {
                locList_HideMarker(locs[k]);
            }
        }
    }
}

function locList_ToggleLocsByCatRecursive(catId, show) {

    if (show) {
        // see if we already have the markers
        if (categoryLocsCache[catId] != undefined && categoryLocsCache[catId] != null) {
            for (var i in categoryLocsCache[catId]) {
                locList_ShowMarker(categoryLocsCache[catId][i], false);
            }
        }
        // have to pull the markers from the server
        else {
            var showAccepted = document.getElementById(showAcceptedBoxId).checked;
            var showSubmitted = document.getElementById(showSubmittedBoxId).checked;
            var showRejected = document.getElementById(showRejectedBoxId).checked;

            PageMethods.GetLocationsByCategoryId(catId, showAccepted, showSubmitted, showRejected,
                function(locArray, context, name) {

                    // clear the cache and refresh it row-by-row
                    categoryLocsCache[catId] = new Array();

                    if (locArray != null) {
                        for (var i = 0; i < locArray.length; i++) {

                            categoryLocsCache[catId].push(locArray[i].LocationId);

                            if (markers[locArray[i].LocationId] == null)
                                locList_AddMarker(locArray[i], false);
                            else
                                locList_ShowMarker(locArray[i].LocationId, false);
                        }
                    }
                },

                function(error, context, methodName) {
                    alert('error getting locs by category ' + catId + ': ' + error.get_message());
                }
            );
        }
    }
    
    // hide the markers
    else {
        if (categoryLocsCache[catId] != undefined && categoryLocsCache[catId] != null) {
            for (var i in categoryLocsCache[catId]) {
                locList_HideMarker(categoryLocsCache[catId][i]);
            }
        }
    }
    
    // recurse to child categories
    if (categoryTree[catId] != undefined && categoryTree[catId] != null) {
        for (var i in categoryTree[catId]) {
            locList_ToggleLocsByCatRecursive(categoryTree[catId][i], show);
        }
    }
}




//////////// WORK IN PROGRESS







function locList_LocBoxClick(cbId, parentState) {

    
    var cb = document.getElementById(cbId);
    
    if (cb == null)
        return;

    var locId = cb.getAttribute("LocationId") * 1;

    // synch with parent box if necessary
    var userClick = true;
    if (parentState != undefined) {
        cb.checked = parentState;
        userClick = false;
    }

    if (cb.checked) {
        locList_ShowMarker(locId, userClick);
    }
    else {
        locList_HideMarker(locId);
    }
}

function locList_RegisterList(locListId, parentId) {
    if (locLists[locListId] == undefined || locLists[locListId] == null)
        locLists[locListId] = new Array();

    // link the box to its parent
    if (parentId) {
        if (locListSubCats[parentId] == null || locListSubCats[parentId] == undefined)
            locListSubCats[parentId] = new Array();

        var alreadyExists = false;
        for (var i in locListSubCats[parentId]) {
            if (locListSubCats[parentId][i] == locListId) {
                alreadyExists = true;
                break;
            }
        }
        if (!alreadyExists) {
            locListSubCats[parentId].push(locListId);
        }

        var locBox = document.getElementById(locListId);
        var parentBox = document.getElementById(parentId);
        if (locBox != null && parentBox != null)
            locBox.checked = parentBox.checked;
    }
}

function locList_RegisterLocBox(locListId, locBoxId, locId) {
   
     // register with locListBoxes (reference to loc boxes by location id)
    if (locListBoxes[locId] == null || locListBoxes[locId] == undefined)
        locListBoxes[locId] = new Array();
        
    var alreadyRegistered = false;
    for (var i in locListBoxes[locId]) {
        if (locListBoxes[locId][i] == locBoxId) {
            alreadyRegistered = true;
            break;
        }
    }
    if (!alreadyRegistered)
        locListBoxes[locId].push(locBoxId);

    // register with locLists (reference to loc boxes by parent id)
    alreadyRegistered = false;
    if (locLists[locListId] == undefined || locLists[locListId] == null)
        locLists[locListId] = new Array();
    for (var i in locLists[locListId]) {
        if (locLists[locListId][i] == locBoxId) {
            alreadyRegistered = true;
            break;
        }
    }
    if (!alreadyRegistered)
        locLists[locListId].push(locBoxId);

    // set the default state of the box correctly
    var locBox = document.getElementById(locBoxId);
    if (locBox) {
        if (markers[locId] != undefined && markers[locId] != null && !markers[locId].isHidden())
            locBox.checked = true;
        else
            locBox.checked = false;
    }
}

function locList_RootRowClick(rootBoxId) {
    var rootBox = document.getElementById(rootBoxId);
    rootBox.checked = !rootBox.checked;
    locList_Click(rootBoxId);
}

function locList_RowClick(locBoxId) {
    var cb = document.getElementById(locBoxId);
    cb.checked = !cb.checked;
    locList_LocBoxClick(locBoxId);
}

var gettingLocs = new Array();  // used to synchronize location requests from server
function locList_ShowMarker(locId, showInfo) {

    if (gettingLocs[locId])
        return;

    gettingLocs[locId] = true;
    
    if (markers[locId] == null) {
        PageMethods.GetLocationById(locId,
            function(loc, context, name) {
                locList_AddMarker(loc, showInfo);
                gettingLocs[locId] = false;

                // check all the boxes for this location
                if (locListBoxes[locId] != undefined && locListBoxes[locId] != null) {
                    for (var i in locListBoxes[locId]) {
                        var cb = document.getElementById(locListBoxes[locId][i]);
                        if (cb != null && cb.getAttribute("LocationId") == locId)
                            cb.checked = true;
                    }
                }
            },

            function(error, context, methodName) {
                alert('error getting LocList location ' + locId + ': ' + error);
                gettingLocs[locId] = false;
            }
        );
    }
    else {
        markers[locId].show();
        if (showInfo)
            openMarkerInfo(markers[locId]);

        // check all the boxes for this location
        if (locListBoxes[locId] != undefined && locListBoxes[locId] != null) {
            for (var i in locListBoxes[locId]) {
                var cb = document.getElementById(locListBoxes[locId][i]);
                if (cb != null && cb.getAttribute("LocationId") == locId)
                    cb.checked = true;
            }
        }
        
        gettingLocs[locId] = false;
    }
}


function locList_HideMarker(locId) {

    // hide the marker
    if (markers[locId] != null) {
        markers[locId].closeInfoWindow();
        markers[locId].hide();
    }

    // uncheck all the boxes for this location
    if (locListBoxes[locId] != undefined && locListBoxes[locId] != null) {
        for (var i in locListBoxes[locId]) {
            var cb = document.getElementById(locListBoxes[locId][i]);
            if (cb != null && cb.getAttribute("LocationId") == locId)
                cb.checked = false;
        }
    }
}

function locList_AddMarker(loc, openInfoWindow) {
    var locId = loc.LocationId;
    var locName = loc.LocationName;
    var xMin = loc.Xminutes;
    var xSec = loc.Xseconds;
    var xDir = loc.Xdirection;
    var yMin = loc.Yminutes;
    var ySec = loc.Yseconds;
    var yDir = loc.Ydirection;
    var cat = loc.LocationCategoryId;
    var publicStatus = loc.PublicStatus;

    // work with an existing marker
    if (markers[locId] != null) {
        locList_ShowMarker(locId, openInfoWindow);
        return;
    }

    // register this loc with indexes
    if (locsByStatus[publicStatus] == null || locsByStatus[publicStatus] == undefined)
        locsByStatus[publicStatus] = new Array();
    locsByStatus[publicStatus].push(locId);

    // adding a brand new marker

    var mapX = gameToReal(xMin, xSec, xDir);
    var mapY = gameToReal(yMin, ySec, yDir);
    var mapLoc = new GLatLng(mapY, mapX);

    var marker = new GMarker(mapLoc, { title: locName, icon: mapIcons[cat] });

    if (markers[locId] == null)
    {
        markers[locId] = marker;

        marker.x = mapX;
        marker.y = mapY;
        marker.name = locName;
        marker.icon = mapIcons[cat];
        marker.category = cat;
        marker.ID = locId;
        marker.PublicStatus = publicStatus;

        GEvent.addListener(marker, "click", function(point) {
            openMarkerInfo(marker);
        });

        map.addOverlay(marker);
        
        if (openInfoWindow)
            openMarkerInfo(marker);
    }
}

function userMarker_Create(latLng) {
    var mapIcon = new GIcon();
    mapIcon.iconSize = new GSize(30, 30);
    mapIcon.iconAnchor = new GPoint(15, 30);
    mapIcon.infoWindowAnchor = new GPoint(15, 0);
    //mapIcon.image = "/mapicons/" + cat + ".gif";

    userMarker = new GMarker(latLng, { draggable: true });

    GEvent.addListener(userMarker, "drag", function() { userMarker_OnMove(userMarker.getPoint()); });

    map.addOverlay(userMarker);
}

function userMarker_MoveToReal(toLatLng) {

    // validate before moving
    
    var coordString = realToGame(toLatLng.lat(), toLatLng.lng());
    var tmp = coordString.split('.');
    var xMin = tmp[0];
    var xSec = tmp[1];
    var xDir = tmp[2];
    var yMin = tmp[3];
    var ySec = tmp[4];
    var yDir = tmp[5];

    if (userMarker_IsLocValid(xMin, xSec, xDir, yMin, ySec, yDir)) {
        userMarker.setPoint(toLatLng);
        GEvent.trigger(userMarker, "move", xMin, xSec, xDir, yMin, ySec, yDir); 
    }
}

function userMarker_MoveToGame(xMin, xSec, xDir, yMin, ySec, yDir) {

    // validate before moving
    if (userMarker_IsLocValid(xMin, xSec, xDir, yMin, ySec, yDir)) {

        if (userMarker.isHidden())
            userMarker.show();
            
        var newLatLng = new GLatLng(gameToReal(yMin, ySec, yDir), gameToReal(xMin, xSec, xDir));
        userMarker.setPoint(newLatLng);
        GEvent.trigger(userMarker, "move", xMin, xSec, xDir, yMin, ySec, yDir);
    }
}

function userMarker_OnMove(latLng) {

    var coordString = realToGame(latLng.lat(), latLng.lng());
    var tmp = coordString.split('.');

    var xMin = tmp[0];
    var xSec = tmp[1];
    var xDir = tmp[2];
    var yMin = tmp[3];
    var ySec = tmp[4];
    var yDir = tmp[5];

    if (userMarker_IsLocValid(xMin, xSec, xDir, yMin, ySec, yDir))
        GEvent.trigger(userMarker, "move", xMin, xSec, xDir, yMin, ySec, yDir);
}


function userMarker_IsLocValid(xMin, xSec, xDir, yMin, ySec, yDir) {

    if (xDir == '')
        return false;
    if (isNaN(xMin) || xMin < 0 || xMin > 20)
        return false;
    if (isNaN(xSec) || xSec < 0 || xSec > 59)
        return false;

    if (yDir == '')
        return false;
    if (isNaN(yMin) || yMin < 0 || (yDir == 'S' && yMin > 40) || (yDir == 'N' && yMin > 1))
        return false;
    if (isNaN(ySec) || ySec < 0 || ySec > 59)
        return false;


    return true;
}

function userMarkerCoords_MarkerMove(xMin, xSec, xDir, yMin, ySec, yDir, _xMin, _xSec, _xDir, _yMin, _ySec, _yDir) {

    document.getElementById(_xMin).value = xMin;
    document.getElementById(_xSec).value = xSec;
    document.getElementById(_xDir).value = xDir;
    document.getElementById(_yMin).value = yMin;
    document.getElementById(_ySec).value = ySec;
    document.getElementById(_yDir).value = yDir;
}

function userMarkerCoords_Change(_xMin, _xSec, _xDir, _yMin, _ySec, _yDir) {

    var xMin = document.getElementById(_xMin).value;
    var xSec = document.getElementById(_xSec).value;
    var xDirDD = document.getElementById(_xDir);
    var xDir = xDirDD.options[xDirDD.selectedIndex].value;
    var yMin = document.getElementById(_yMin).value;
    var ySec = document.getElementById(_ySec).value;
    var yDirDD = document.getElementById(_yDir);
    var yDir = yDirDD.options[yDirDD.selectedIndex].value;

    userMarker_MoveToGame(xMin, xSec, xDir, yMin, ySec, yDir);
}

function categoryTree_Register(catId, parentId) {
    if (parentId != null) {
        if (categoryTree[parentId] == undefined || categoryTree[parentId] == null)
            categoryTree[parentId] = new Array();

        var alreadyExists = false;
        for (var i in categoryTree[parentId]) {
            if (categoryTree[parentId][i] == catId) {
                alreadyExists = true;
                break;
            }
        }
        if (!alreadyExists)
            categoryTree[parentId].push(catId);
    }

    if (categoryTree[catId] == undefined || categoryTree[catId] == null)
        categoryTree[catId] = new Array();
}


function locStatusFilter_Click(cbId, publicStatus) {
    var cb = document.getElementById(cbId);

    for (var i in locsByStatus[publicStatus]) {
        if (cb.checked)
            locList_ShowMarker(locsByStatus[publicStatus][i], false);
        else
            locList_HideMarker(locsByStatus[publicStatus][i]);
    }
}


function map_createIcon(catId) {
    var mapIcon = new GIcon();
    mapIcon.iconSize = new GSize(18, 18);
    mapIcon.iconAnchor = new GPoint(9, 9);
    mapIcon.infoWindowAnchor = new GPoint(9, 9);
    mapIcon.image = "/mapicons/" + catId + ".gif";

    mapIcons[catId] = mapIcon;
}