﻿var _items = null;
var _maps = null;
var _groups = null;
var _icon = '';
var _tweet = null;
var _gMap = null;
var _bounds = null;
var _protected = '0';
var _map = 'Autobiogeography';
var _group = '';

function startup() {
    resize();
    loadMap();           
    loadMaps();
    loadGroups();
    loadItems();
    loadTweet();
    setInterval(loadTweet, 60000);
};

function selectItems(map, group, icon, isprotected) {
    _gMap.clearOverlays();
    $('itemHover').hide();
    $('itemCentre').hide();
    _map = map;
    _group = group;
    _icon = icon;
    _protected = isprotected;
    loadItems();
};

function loadMap() {
    if (GBrowserIsCompatible()) {                                
        _gMap = new GMap2($("map"));
        _gMap.setCenter(new GLatLng(0, 0), parseInt(4));
        _gMap.setMapType(G_PHYSICAL_MAP);
        _gMap.addControl(new GLargeMapControl());

        GEvent.addListener(_gMap, "movestart", function() { $('itemCentre').hide(); $('itemHover').hide() });
        //GEvent.addListener(_gMap, "click", function() { $('itemCentre').hide(); $('itemHover').hide() });
    };
};

function loadGroups() {
    switch (_map) {
        case 'Articles':
            $('groupsContent').update('');
            $('stars').show();
            break;
        default:
            $('stars').hide();
            new Ajax.Request('feed.ashx?get=groups&map=' + _map , {
                method: 'get',
                onSuccess: function(transport) {
                    _groups = transport.responseText.evalJSON().groups;
                    displayGroups();
                },
                onFailure: handleError
            });        
            break;
    };
};

function loadMaps() {
    new Ajax.Request('feed.ashx?get=maps', {
        method: 'get',
        onSuccess: function(transport) {
            _maps = transport.responseText.evalJSON().maps;
            displayMaps();
        },
        onFailure: handleError
    });
};

function fill(data, elementid, template) {
    var t = new Template(template);
    $(elementid).innerHTML = t.evaluate(data);
    t = null;
};

function loadItems() {
    var password = '';
    
    if (_protected=='1') {
        password = prompt("Password Required");
    };
    
    _bounds = new GLatLngBounds();
    _gMap.clearOverlays();
    new Ajax.Request('feed.ashx?get=articles&map=' + _map + '&group=' + _group + '&icon=' + _icon + '&password=' + password, {
        method: 'get',
        onSuccess: function(transport) {
            _items = transport.responseText.evalJSON().articles;
            loadGroups();
            displayItems();
        },
        onFailure: handleError
    });
};

function displayGroups() {
    $('groupsContent').innerHTML = '';
    _groups.each(displayGroup);
};

function displayGroup(group) {
    $('groupsContent').innerHTML += '<a href="javascript:selectItems(\'' + _map + '\',\'' + group.label + '\',\'\', ' + _protected + ');"><img border="0" src="' +  group.icon.url + '"/>' + group.label + '</a>';
};

function displayItems() {
    _items.each(displayItem);

    _gMap.setZoom(_gMap.getBoundsZoomLevel(_bounds));

    if ($('itemCounter')) {
        $('itemCounter').innerHTML = 'Items Found: ' + _items.size();
    };

    if (_map == 'OnTour') {
        _touring = setInterval(tour, 1000);
    } else {
        clearInterval(_touring);
    };
};

var _l = 0;
var _index = 0;
var _lines = new Array(10);
var _touring;

function tour() {
    
    hover(_items[_index]);

    if (_index > 0) {
        if (_lines[_l]) {
            _gMap.removeOverlay(_lines[_l]);
        };

        _lines[_l] = new GPolyline([new GLatLng(_items[_index - 1].latitude, _items[_index - 1].longitude), new GLatLng(_items[_index].latitude, _items[_index].longitude)], "#000000", 2);

        _gMap.addOverlay(_lines[_l]);
        
        _l++;
        
        if (_l == 10) {
            _l = 0;
        };
    };

    _index++;    
    
    if (_index == _items.size()) {
        _index = 0;
    };
};

function displayItem(item) {          
    var gi = new GIcon();

    gi.image = item.icon.url;
    gi.iconSize = new GSize(item.icon.width, item.icon.height);
    gi.iconAnchor = new GPoint(item.icon.anchorx, item.icon.anchory);

    item.latitude = parseFloat(item.latitude) + random();
    item.longitude = parseFloat(item.longitude) + random();

    var gm = new GMarker(new GLatLng(parseFloat(item.latitude), parseFloat(item.longitude)), gi);

    if (_map != 'Reviews' && _map != 'Articles') GEvent.addListener(gm, "click", function() { click(item) });
    GEvent.addListener(gm, "mouseover", function() { hover(item) });
    GEvent.addListener(gm, "click", function() { click(item) });

    _gMap.addOverlay(gm);

    _bounds.extend(new GLatLng(parseFloat(item.latitude), parseFloat(item.longitude)));
};

function click(item) {
    _gMap.setCenter(new GLatLng(item.latitude, item.longitude))

    $('itemHover').hide();
    $('itemCentre').show();
    $('itemCentreContent').innerHTML = '';
                  
    switch (_map) {
        case 'Articles':
            fill(item, 'itemCentreContent', '<center><span class="b" style="font-size: 1.2em;">#{title}</span><br/><span style="font-size: 1.1em;">#{group}</span><br/><span style="font-size: 0.9em;">#{published}</span></center><hr/>#{description}<hr style="clear:both;"/><a href="javascript:void(0);" onclick="$(\'itemCentre\').hide();" style="position:absolute; top: 2px; left: 2px; border: 0;"><img src="graphics/close.png" border="0"/></a><a href="#{url}" target="_blank">Read</a>'); 
            break;
        case 'Autobiogeography':
            fill(item, 'itemCentreContent', '<center><span class="b" style="font-size: 1.2em;">#{title}</span><br/><span style="font-size: 1.1em;">#{group}</span><br/><span style="font-size: 0.9em;">#{published}</span></center><hr/>#{description}<hr style="clear:both;"/><a href="javascript:void(0);" onclick="$(\'itemCentre\').hide();" style="position:absolute; top: 2px; left: 2px; border: 0;"><img src="graphics/close.png" border="0"/></a><a href="#{url}" target="_blank">Visit Website</a>');
            break;
        case 'Address':
            fill(item, 'itemCentreContent', '<center><span class="b" style="font-size: 1.2em;">#{title}</span><br/><span style="font-size: 1em;">#{location}</span></center><hr/>#{description}<hr style="clear:both;"/><a href="javascript:void(0);" onclick="$(\'itemCentre\').hide();" style="position:absolute; top: 2px; left: 2px; border: 0;"><img src="graphics/close.png" border="0"/></a>');        
            break;
        case 'NotBeen':
            break;
        case 'OnTour':
            break;
        default:
            break;                                      
    };
};

function hover(item) {
    var p = new GLatLng(item.latitude, item.longitude);
    var x = _gMap.fromLatLngToContainerPixel(p).x + 20;
    var y = _gMap.fromLatLngToContainerPixel(p).y + 62;

    $('itemCentre').hide();
    $('itemHover').setStyle({height: '120px',width: '160px'});
    
    position('itemHover', x, y);

    switch (_map) {
        case 'Articles':
            fill(item, 'itemHoverContent', '<center><span class="b" style="font-size: 1.1em;">#{title}</span><br/><span style="font-size: 1em;">#{group}</span><br/><span style="font-size: 0.75em;">#{published}</span><br/><span style="font-size: 0.85em;">#{location}</span><br/><a href="#{url}" target="_blank" style="font-size: 0.85em; font-style: normal;">Read this article</a></center>'); 
            break;
        case 'Autobiogeography':            
            if (item.url == '') {
                fill(item, 'itemHoverContent', '<center><span class="b" style="font-size: 1.2em;">#{title}</span><br/><span style="font-size: 0.9em;">#{group}, #{year}<br/>#{location}</span></center></span>');
            } else {
                fill(item, 'itemHoverContent', '<center><span class="b" style="font-size: 1.2em;">#{title}</span><br/><span style="font-size: 0.9em;">#{group}, #{year}<br/>#{location}<br/><a href="#{url}" target="_blank">Website</a></span></center></span>');
            };
            break;
        case 'Address':
            fill(item, 'itemHoverContent', '<center><span class="b" style="font-size: 1.1em;">#{title}</span><br/><span style="font-size: 0.9em;">#{location}</span></center>'); 
            break;
        case 'OnTour':

            if (item.thumbnail == '') {
                $('itemHover').setStyle({ height: '50px', width: '160px' });
                fill(item, 'itemHoverContent', '<span style="display:block; text-align: right; font-size: 0.9em;">#{location}<br/>#{published}</span>');
            } else {
                fill(item, 'itemHoverContent', '<center><img src="#{thumbnail}" style="width: 140px;margin-bottom:2px;border: 1px solid #000;"/></center><span style="display:block; text-align: right; font-size: 0.9em;">#{location}<br/>#{published}</span>');
            };

            break;
        default:
            if (item.url == '') {
                fill(item, 'itemHoverContent', '<center><span class="b" style="font-size: 1.1em;">#{title}</span><br/><span style="font-size: 0.9em;">#{location}</span><br/><span style="font-size: 1em;">#{group}</span><br/><span style="font-size: 0.75em;">#{published}</span><br/></center>');
            } else {
                fill(item, 'itemHoverContent', '<center><span class="b" style="font-size: 1.1em;">#{title}</span><br/><span style="font-size: 0.9em;">#{location}</span><br/><span style="font-size: 1em;">#{group}</span><br/><span style="font-size: 0.75em;">#{published}</span><br/><a href="#{url}" target="_blank" style="font-size: 0.85em; font-style: normal;">Read this article</a></center>');
            };
            break;
    }; ;
};

function position(elementid,x,y) {
    var minX = 350;
    var minY = 240;
    var maxX = width() - 340;
    var maxY = height() - 100;

    var anchorWhere =  'bottomRight';

    if (x <= minX) {
        anchorWhere = 'bottomLeft';
        
        if (y <= minY) {
            anchorWhere = 'topLeft';
        };

        if (y >= maxY) {
            anchorWhere = 'bottomLeft';
        };
    };

    if (x >= maxX) {
        anchorWhere = 'bottomRight';
    
        if (y <= minY) {
            anchorWhere = 'topRight';
        };

        if (y >= maxY) {
            anchorWhere = 'bottomRight';
        };
    };

    if (y <= minY) {
        if (x > minX && x < maxX) {
            anchorWhere = 'topRight';
        };
    };

    if (y >= maxY) {
        if (x > minX && x < maxX) {
            anchorWhere = 'bottomRight';
        };
    };

    $(elementid).show();

    $(elementid + 'Content' ).innerHTML = 'where:' + anchorWhere + '<br/>maxX:' + maxX + '<br/>maxY:' + maxY + '<br/>x:' + x + '<br/>y:' + y;


    $(elementid).style.right = '';
    $(elementid).style.top = '';
    $(elementid).style.left = '';
    $(elementid).style.bottom = ''; 
    
    switch (anchorWhere) {
        case 'bottomLeft':                   
            $(elementid).style.left = x + 'px';
            $(elementid).style.bottom = (height() - y) + 'px';
            break;
        case 'bottomRight':
            $(elementid).style.right = (width() - x) + 'px';
            $(elementid).style.bottom = (height() - y) + 'px';
            break;
        case 'topLeft':
            $(elementid).style.left = x + 'px';
            $(elementid).style.top = y + 'px';
            break;
        case 'topRight':                    
            $(elementid).style.top = y + 'px';
            $(elementid).style.right = (width() - x) + 'px';
            break;
        default:
            $(elementid).style.left = x + 'px';
            $(elementid).style.bottom = (height() - y) + 'px';
            break;
    };
    
};

function showMapDescription(element) {
    $(element).select('div').invoke('show');
};

function hideMapDescription(element) {
    $(element).select('div').invoke('hide');        
};


function displayMaps() {
    var s = '';

    _maps.each(function(item) {
        s += '<a class="mapLink" onMouseOver="showMapDescription(this);" onMouseOut="hideMapDescription(this);" href="javascript:selectItems(\'';
        s += item.label;
        s += '\',\'\',\'\',\'';
        s += item.protected;
        s += '\');">';
        s += item.title;
        s += '<div class="mapDescription" style="display:none;">';
        s += item.description;
        s += '</div>';
        s += '</a> | ';
    });
    
    s+='<span id="itemCounter" class="mapLink" style="border:0;">Loading...</span>'
    $('mapListContent').innerHTML = s;
};

var tweet = '';
var tc = 0;

function loadTweet() {
    new Ajax.Request('feed.ashx?get=tweet', {
        method: 'get',
        onSuccess: function(transport) {
            tc = 0;
            tweet = transport.responseText.evalJSON().tweet;
            setTimeout(displayTweet, 50);
        },
        onFailure: handleError
    });
};

function displayTweet() {
    tc++;
    
    $('tweet').innerHTML = tweet.substr(0, tc);

    if (tc < tweet.length) {
        setTimeout(displayTweet, 50);
    };
};

function resize() {
    $('map').style.height = height() - 90 + 'px';
    $('map').style.width = width() - 48 + 'px';
};

function handleError() {
    alert('Error!');
};

function random() {
    return roundNumber(Math.random() / 10 - .05, 3);
};

function roundNumber(num, dec) {
    return Math.round(Math.round(num * Math.pow(10, dec + 1)) / Math.pow(10, 1)) / Math.pow(10, dec);
};

function width() {
    return document.viewport.getWidth();
};

function height() {
    return document.viewport.getHeight();
};

Event.observe(window, 'load', startup);
Event.observe(window, 'resize', resize);
    
