if (window['console'] === undefined) {
    window.console = { log: function(){} };
}

var map;
var markers = [];

var LiveMap = {
    config: {
        idIndex:    0,
        delayAppear:2,
        delayFade:  3,
        delayQuery: 240,
        loop:       0,
        points:     null,
        ptIndex:    0,
        timer:      null,
        service:    'http://ifelse.org/projects/nyt/timespeople/map/stream.js'
    },

    initialize: function() {
        if (GBrowserIsCompatible()) {
            map            = new GMap2(document.getElementById("earth"));
            var boundaries = new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 179.8));
            var earth      = new GGroundOverlay("images/dark_earth.jpg", boundaries);

            map.addOverlay(earth);
            map.disableDoubleClickZoom();
            map.disableDragging();
            map.setCenter(new GLatLng(40, -3), 2);

            this.request();

            var that = this;
            new PeriodicalExecuter(function(pe) {
                that.request();
            }, this.config.delayQuery);
        }
    },

    request: function() {
        var instance = this;
        new Ajax.Request(this.config.service + '?cache=' + (new Date()).getTime(), {
            method: 'get',
            onSuccess: function(response) {
                console.log('onSuccess: response', response);
                var json = response.responseText.evalJSON();
                instance.process(json);
            },
            onException: function(req,exception) {
                console.log('onException: request over',req,exception);
            }
        });
    },

    process: function(points) {
        $('points').innerHTML = '';

        markers.each(function(m){
            map.removeOverlay(m);
        });
        markers = [];

        var idPad      = this.uniqueID();
        var total      = points.result.length;
        var markerIcon = new GIcon(G_DEFAULT_ICON);

        markerIcon.iconSize   = new GSize(15, 15);
        markerIcon.iconAnchor = new GPoint(7, 15);
//      markerIcon.infoWindowAnchor = new GPoint(7, 2);

        for (i=0; i<total; i++) {

            var loc    = points.result[i];
            var pic    = (loc.pic=='' || loc.pic=='http://graphics8.nytimes.com/') ? 'http://ifelse.org/projects/nyt/timespeople/map/images/avatar_community.gif' : loc.pic;

            markerIcon.image = pic;
            markerOptions  = { icon: markerIcon };

            var point  = new GLatLng(loc.lat, loc.lng);
            var marker = new GMarker(point, markerOptions);

            markers.push(marker);

            map.addOverlay(markers[markers.length-1]);

			console.log('marker', marker);

		//	was Er, now xn
            marker.xn.hide();
            marker.xn.addClassName('activity');
            marker.xn.id = "m_" + idPad + i;
            marker.xn.title = loc.loc;
            marker.xn.writeAttribute('html', this.notification(loc));
        }

        setTimeout("LiveMap.plot();", 1000);
    },

    notification: function(l) {
        var profile = "http://timespeople.nytimes.com/view/user/"+l.userid+"/activities.html";
        var thumb   = (l.pic=='' || l.pic=='http://graphics8.nytimes.com/') ? 'http://ifelse.org/projects/nyt/timespeople/map/images/avatar_community.gif' : l.pic;
        var hdl     = (l.hdl.length>200) ? l.hdl.truncate(120) : l.hdl;

        return "<div><img style='float:left;' src='" + thumb + "'/><a href='"+profile+"'>" + l.name + "</a> " + l.verb + ": <a href='"+l.url+"' class='hdl'>" + hdl + "</a></div>"; 
    },

    plot: function() {
        $('block').hide();

        var allpoints = $$('img.activity');
        var total     = allpoints.length;

        LiveMap.config.delayAppear = parseInt(LiveMap.config.delayQuery/total/3);
        LiveMap.config.delayFade   = parseInt(LiveMap.config.delayQuery/total/3*2);

        LiveMap.config.points  = allpoints;
        LiveMap.config.ptIndex = 0;

        this.timedEffect();
    },

    timedEffect: function() {
        var points = LiveMap.config.points;
        var limit  = LiveMap.config.points.length;
        var index  = LiveMap.config.ptIndex;

        var delay  = parseInt(LiveMap.config.delayQuery/limit);
        var stream = $('stream');
        var list   = stream.select('li');

        stream.insert({top: '<li id="li_' + points[index].id + '" style="display:none;">' + points[index].readAttribute('html') + '</li>' });

        if (list.length>=7) {
            new Effect.Fade (list[list.length-5], { duration: 2, from: 1,   to: 0.8 });
            new Effect.Fade (list[list.length-4], { duration: 2, from: 0.8, to: 0.6 });
            new Effect.Fade (list[list.length-3], { duration: 2, from: 0.6, to: 0.4 });
            new Effect.Fade (list[list.length-2], { duration: 2, from: 0.4, to: 0.2 });
            new Effect.Fade (list[list.length-1], { duration: 2, from: 0.2, to: 0,
                afterFinish: function() {
                    list[list.length-1].remove();
                } 
            });
        }

        new Effect.Appear(points[index].id, { duration: 4, queue: { position: 'end', scope: 'appearGroup' } }); // Map
        new Effect.Appear('li_' + points[index].id, { duration: 4, queue: { position: 'end', scope: 'appearGroup' } }); // List
        setTimeout("new Effect.Fade('"+points[index].id+"', { duration: 8, queue: { position: 'end', scope: 'fadeGroup' } });", 20000); // Map 20s

        LiveMap.config.ptIndex++;

        if (LiveMap.config.ptIndex==limit) {
            clearTimeout(LiveMap.config.timer);
        } else {
            LiveMap.config.timer = setTimeout("LiveMap.timedEffect()", (delay*1000));
        }
    },

    uniqueID: function() {
        var range = 'abcdefghijklmnopqrstuvwxyz';
        var index = ++this.config.idIndex;

        if (index>range.length) {
            this.config.idIndex = 0;
            index = 0;
        }
        return range.charAt(index);
    }
};

Event.observe(document, 'load', LiveMap.initialize());