var viewportWidth = 430;
var viewportHeight = 430;
var tileSize = 100;
var zoom = 0;
var zoomSizes = [["2300","1600", 0.5, -4.0], ["4600","3200", 2.0, 2.0]];

var dragging = false;
var top;
var left;
var dragStartTop;
var dragStartLeft;

function init_map() 
{
    $('#toggleZoomDiv').click(toggleZoom);
    //$('#togglePushPinDiv').click(togglePushPin);
    // make inner div big enough to display the map
    $("#innerDiv").css(
        {"width": zoomSizes[zoom][0], "height":zoomSizes[zoom][1]});

    // wire up the mouse listeners to do dragging
    $("#outerDiv").mousedown(startMove);
    $("#outerDiv").mousemove(processMove);
    $("#outerDiv").mouseup(stopMove);

    // necessary to enable dragging on IE
    $("#outerDiv").ondragstart = function() { return false; }

    // fix the toggle divs to be transparent in IE
    new OpacityObject('toggleZoomDiv','/static/map/images/zoom').setBackground();
    //new OpacityObject(
     //   'togglePushPinDiv','resources/images/pushpin').setBackground();

    checkTiles();
}

function startMove(event) 
{
    dragStartLeft = event.pageX;
    dragStartTop = event.pageY;
    $("#innerDiv").css("cursor", "-moz-grab");

    top = stripPx($("#innerDiv").css("top"));
    left = stripPx($("#innerDiv").css("left"));
                
    dragging = true;
    return false;
}

function processMove(event) 
{
    if (dragging) 
    {
        $("#innerDiv").css(
            {"top":calculate_top(event),
             "left":calculate_left(event)}
        );
    }
    checkTiles();
}

function calculate_top(event)
{
    t = parseFloat(top) + (event.pageY - dragStartTop);
    t = Math.min(0, t);
    t = Math.max(t, -zoomSizes[zoom][1] + viewportHeight);
    return t;
}

function calculate_left(event)
{
    l = parseFloat(left) + (event.clientX - dragStartLeft);
    l = Math.min(0, l);
    l = Math.max(l, -zoomSizes[zoom][0] + viewportWidth);
    return l;
}

function checkTiles() 
{
    var visibleTiles = getVisibleTiles();

    var innerDiv = document.getElementById("innerDiv");
    var visibleTilesMap = {};      
    $(visibleTiles).each(
        function(index, tile)
        {
            // START:imgZoomLevel
            var tile_name = "x" + tile[0] + "y" + tile[1] + "z" + zoom;
            // END:imgZoomLevel
            visibleTilesMap[tile_name] = true;
            if (!$("#" + tile_name).length > 0) 
            {
                img = $(document.createElement('img'));
                img.attr("src","/static/map/images/tiles/" + tile_name + ".png");
                img.css({"position":"absolute", "zIndex":0,
                            "left":(tile[0]),
                            "top":(tile[1])});
                img.attr("id", tile_name);
                img.appendTo($("#innerDiv"));     
             }
        }
    );
    
    $("#innerDiv img").each(
        function(index, tile)
        {
            if(!visibleTilesMap[$(tile).attr("id")])
            {
                $(tile).remove();
            }
        }
    );
 
}

function getVisibleTiles() 
{
    var mapX = stripPx($("#innerDiv").css("left"));
    var mapY = stripPx($("#innerDiv").css("top"));
    var startX = Math.abs(Math.floor(mapX / tileSize)) - 1;
    var startY = Math.abs(Math.floor(mapY / tileSize)) - 1;
    
    var tilesX = Math.ceil(viewportWidth / tileSize) + 1;
    var tilesY = Math.ceil(viewportHeight / tileSize) + 1;
    var visibleTileArray = [];
    var counter = 0;
    for (x = startX; x < (tilesX + startX); x++) 
    {
        for (y = startY; y < (tilesY + startY); y++) 
        {
          //  if (checkTileOnMap(x, y))
          // {
                visibleTileArray[counter++] = [x * 100, y * 100];
          //  }
        }
    }
    return visibleTileArray;
}

function checkTileOnMap(x, y)
{
    return (((x * 100) < zoomSizes[zoom][0]) && x>=0) && (((y * 100) < zoomSizes[zoom][1]) && y>=0)
}

function stopMove() 
{
    $("#innerDiv").css("cursor","");
    dragging = false;
}

function stripPx(value) 
{
    if (value == "")
    {
        return 0;
    }
    return parseFloat(value.substring(0, value.length - 2));
}

function toggleZoom() 
{
    zoom = (zoom == 0) ? 1 : 0;
    $("#innerDiv img").remove();
    $("#innerDiv").css(
        {"width": zoomSizes[zoom][0], "height":zoomSizes[zoom][1]});
    $("#innerDiv").css(
            {"top":stripPx($("#innerDiv").css("top")) * zoomSizes[zoom][2],
             "left":stripPx($("#innerDiv").css("left")) * zoomSizes[zoom][2]}
        );

    //adjust zoom position to compensate for the changing relative size of the viewport

    $("#innerDiv").css(
            {"top":stripPx($("#innerDiv").css("top")) - viewportHeight / zoomSizes[zoom][3],
             "left":stripPx($("#innerDiv").css("left")) - viewportWidth / zoomSizes[zoom][3]});

    /*if ($("#pushPin").length > 0) 
    {
        togglePushPin();
    }*/

    checkTiles();
}
                     

function togglePushPin() 
{
    if($("#pushPin").length > 0)
    {
        $("#pushPin").remove();
        $("#pinDialog").remove();
        return
    }

    pinImage = $(document.createElement("div"));
    pinImage.css({"position":"absolute","left":(zoom == 0) ? "850px" : "630px",
                    "top":(zoom == 0) ? "570px" : "420px","width":"37px",
                    "height":"34px", "zIndex":1}); 
    pinImage.attr("id", "pushPin");
    $("#innerDiv").append(pinImage);
    new OpacityObject('pushPin','/static/map/images/pin').setBackground();

    var dialog = $(document.createElement("div"));
    dialog.css({"position":"absolute", 
            "left": (stripPx($(pinImage).css("left")) - 90),
            "top": (stripPx($(pinImage).css("top")) - 210),
            "width":"309px", "height":"229px", "zIndex":2});
    dialog.attr("id", "pinDialog");
    dialog.html("<table height='80%' width='100%'><tr>" +
        "<td align='center'>The capital of Spain</td></tr></table>");
    $("#innerDiv").append(dialog);
    new OpacityObject('pinDialog','/static/map/images/dialog').setBackground();
}

$(document).ready(init_map);

