/*
 * Copyright (c) 2010, Inmite s.r.o. (www.inmite.eu). All rights reserved.
 *
 * This source code can be used only for purposes specified by the given license contract
 * signed by the rightful deputy of Inmite s.r.o. This source code can be used only
 * by the owner of the license.
 *
 * Any disputes arising in respect of this agreement (license) shall be brought
 * before the Municipal Court of Prague.
 */

var APIroot = 'http://ida.inmite.eu/tmo-latitude/';
var user1 = 'Pinkie';
var user2 = 'Rosie';
//http://localhost:8080/tmo-latitude/event/listData?author=Ondra
var maxEvents = 10;

/**
 * ToursOverlay based on our superfast IMapMarkerOverlay.
 *
 * This singleton is used in IMap configuration in main.js.
 */
var poslitoOverlay = new IMapMarkerOverlay('poslito', '', {
    showDescr: false
});



///////////////////////////
//
// IMap API implementation
//
///////////////////////////



/**
 * IMap API
 *
 * Implementation of callback called by IMap during initialization of overlays.
 *
 * @param _initDoneCallback  function to be called after initialization is finished
 */
poslitoOverlay.initOverlay = function(mapBounds, _initDoneCallback) {
    poslitoOverlay._initDoneCallback = _initDoneCallback;

    $('BODY').append('<script type="text/javascript" src="'+APIroot+'event/listData?author='+user1+'&max='+maxEvents+'"></script>');
    $('BODY').append('<script type="text/javascript" src="'+APIroot+'event/listData?author='+user2+'&max='+maxEvents+'"></script>');
};

// demo data (content of JSON in JS):
//  dataLoaded({'author':{'id':6,'login':'eva'},
//  'count': 1,
//  'events': [{'id':6,'typeName': '', 'typeIcon': 'http://ida.inmite.eu/tmo-latitude/photos/02/2.png', 'typeIconUn': 'http://ida.inmite.eu/tmo-latitude/photos/03/3.png', 'time': '25.02.2010 15:51', 'place': '', 'lat': '50.1038321', 'lon': '14.49766644', 'descr': 'Tak tohle jsem tady viděla', 'celebrities': [], 'photos': [{p: 'http://ida.inmite.eu/tmo-latitude/photos/08/8.jpg', d: ' '}], 'thumbs': ['http://ida.inmite.eu/tmo-latitude/thumbs/08/8.jpg']}]
//  });
// --- end of demo data ---

// this is called when JS wrapped JSON is loaded
function dataLoaded(data) {
    if (data.author.login == user1) {
        _getDataLoaded('left', data);
    } else if (data.author.login == user2) {
        _getDataLoaded('right', data);
    }
}

/**
 * Called when more is clicked...
 */
function loadMore(suff, author) {
    if (loadedMarkersCnt[suff]) {
        $('BODY').append('<script type="text/javascript" src="'+APIroot+'event/listData?author='+author+'&max='+maxEvents+'&offset='+loadedMarkersCnt[suff]+'"></script>');
    }
}

    var loadedMarkersCnt = [];
    var lastLinePoint = [];
    /**
     * Generates callback called after Ajax call that loads data.
     *
     * @param suff  suffix of the side (left/right)
     */
    _getDataLoaded = function(suff, data) {
        var color = suff == 'left' ? 'red' : 'blue';

        if (!loadedMarkersCnt[suff]) {
            loadedMarkersCnt[suff] = 0;
        }

        if (data.events) {
            var lls = [];
            for (k = 0; k < data.count; k++) {
                loadedMarkersCnt[suff] ++;

                data.events[k].lat = data.events[k].lat.substring(0, 10);
                data.events[k].lon = data.events[k].lon.substring(0, 10);

                if (parseFloat(data.events[k].lat) && parseFloat(data.events[k].lon)) {
                    var pm = new PMarker('m_'+color, suff, k == 0, data.events[k]);

                    poslitoOverlay.markers.push(pm);
                    addListItem('list-'+suff, data.events[k], k == 0 && !initialized);

                    if (k == 0 && !initialized) {
                        updateTop(suff, data.events[k]);
                        lastActiveMarker[suff] = data.events[k].id;
                    }

                    lls.push(poslitoOverlay.getLatLng(pm));
                }
            }
            if (lls.length > 0) {
                //GPolyline(latlngs:GLatLng[], color?:String, weight?:Number, opacity?:Number, opts?:GPolylineOptions)
                for (l = 0; l < lls.length; l ++) {
                    if (lastLinePoint[color]) {
                        IMap.m.addOverlay(new GPolyline([lastLinePoint[color], lls[l]], color, 3, 0.2));
                    }
                    lastLinePoint[color] = lls[l];
                }
//                IMap.m.addOverlay(new GPolyline(lls, color, 3, 0.2));
            }

            // remove old more and add new one
            $('#more-'+suff).remove();
            if (data.count >= maxEvents) {
                addMore(suff, data.author.login);
            }

            poslitoOverlay.checkDone();
        } else {
            msgErr("Došlo k nečekané chybě. Zkuste prosím stránku načíst znova.");
        }
    };

    var done = 0;
    var initialized = false;
    /**
     * Cheks wether everything is loaded or not. If it is and it's a first load (left & right side) => calls _initDoneCallback().
     */
    poslitoOverlay.checkDone = function() {
        done ++;
        if (done >= 2) {
            if (!initialized) {
                poslitoOverlay._initDoneCallback(poslitoOverlay);
                initialized = true;

                // Zoom so that we can se both markers well
                var bounds = new GLatLngBounds();
                var points = 0;
                var ll1 = null;
                var ll2 = null;
                if (lastActiveMarker['left']) { points ++; ll1 = poslitoOverlay.getLatLngById(lastActiveMarker['left']); bounds.extend(ll1);}
                if (lastActiveMarker['right']) { points ++; ll2 = poslitoOverlay.getLatLngById(lastActiveMarker['right']); bounds.extend(ll2);}
                if (points == 1) {
                    poslitoOverlay.map.setCenter(ll1 ? ll1 : ll2, 7);
                } else if (points == 2) {
                    poslitoOverlay.map.setZoom(poslitoOverlay.map.getBoundsZoomLevel(bounds) - 1);
                    poslitoOverlay.map.setCenter(bounds.getCenter());
                }
            } else {
                poslitoOverlay.redraw(true);
            }
        }
    };

poslitoOverlay.markerOver = function(markerId, fromList) {
    _markerSwitch(markerId, false, fromList);
};

poslitoOverlay.markerClicked = function(markerId, fromList) {
    _markerSwitch(markerId, true, fromList);
};

    var clickSpeed = 100;
    var lastActiveMarker = [];
    function _markerSwitch(markerId, store, fromList) {

        var m = poslitoOverlay.getMarkerById(markerId);

        if (!m) {
            return false;
        }

        // Analytics tracker
        track('Side', ''+m.suff);
        track('ItemView', ''+markerId);

        if (store) {
            // mark previously active marker as unactive
            if (lastActiveMarker[m.suff]) {
                var om = poslitoOverlay.getMarkerById(lastActiveMarker[m.suff]);
                if (om) {
                    om.isActive = false;
                }
            }

            // currently clicked marker is active
            m.isActive = true;
            lastActiveMarker[m.suff] = markerId;
        }

        var oldM = $('.imap_marker.active.'+m.suff);
        oldM.removeClass('active');
        oldM.css('background-position', '0 -20px');
        oldM.css('z-index', '500');

        var newM = $('#im_poslito'+markerId);
        newM.addClass('active');
        newM.css('background-position', '0 0');
        newM.css('z-index', '1001');
//        alert(newM.css('z-index'));

        updateTop(m.suff, m);

        $('#list-'+m.suff+' .item.active').removeClass('active');
        $('#i-'+m.id).addClass('active');

        if (!fromList) {
            // switch didn't came from list => scroll to given item in the list
            // it should work like this: $('#list-'+m.suff).scrollTo('#i-'+m.id, 50); ...but it doesn't
            var c = $('#list-'+m.suff).children();
            for (var k = 0; k < c.length; k ++) {
                if (c[k].id == 'i-'+m.id) {
                    $('#list-'+m.suff).scrollTo((25*k)+'px', 250);
                }
            }
//            alert($('#i-'+m.id).attr('id'));
        } else {
            // switch came from the list => scroll marker on the map
//            poslitoOverlay.scrollToMarker(m);
        }

        // blink clicked marker and list item, scroll to it
        if (store) {
            poslitoOverlay.scrollToMarker(m, true);

            newM.fadeTo(clickSpeed, 0.5, function() {
                newM.fadeTo(clickSpeed, 1);
            });
            $('#i-'+m.id).fadeTo(clickSpeed, 0.5, function() {
                $('#i-'+m.id).fadeTo(clickSpeed, 1);
            });
        }
    }

        poslitoOverlay.scrollToMarker = function(m, force) {
            var ll = poslitoOverlay.getLatLng(m);
            if (!poslitoOverlay.map.getBounds().containsLatLng(ll) || force) {
                if (poslitoOverlay.map.getZoom() < 11) {
                    poslitoOverlay.map.setCenter(ll, 11);
                } else {
                    poslitoOverlay.map.panTo(ll);
                }
            }
        };

poslitoOverlay.markerOut = function(markerId, fromList) {
    var m = poslitoOverlay.getMarkerById(markerId);

    if (!lastActiveMarker[m.suff]) {
        return false;
    }

    _markerSwitch(lastActiveMarker[m.suff], false, fromList);
};

/////////////////////////
//
// Helper methods
//
/////////////////////////

function PMarker(icon, suff, active, itemData) {
//    alert(''+lat+lng+id+icon);
    this.lat = itemData.lat;
    this.lng = itemData.lon;
    this.id = itemData.id;
    this.markerIcon = icon;

    this.suff = suff;
    this.isActive = active;

    this.descr = itemData.descr;
    this.time = itemData.time;
    this.thumbs = itemData.thumbs;
    this.photos = itemData.photos;
}

var maxDescLength = 21;
function addListItem(listId, itemData, active) {
    //<div class="item"><div class="ititle">24.22.2010, 20:52</div><div class="itxt">Tak tohle je on vyfot...</div></div>
    var l = $('#'+listId);

    var descr = itemData.descr;
    descr = descr.replace(/<[^>]*>/,' ');
    if (descr && descr.length > maxDescLength) {
        descr = descr.substring(0, maxDescLength - 1) + '...';
    }

    l.append('<div class="item '+(active ? 'active' : '')+'" id="i-'+itemData.id+'" ' +
                 'onmouseover="im_ds(\'poslito\',\''+itemData.id+'\', true);" ' +
                 'onmouseout="im_dh(\'poslito\',\''+itemData.id+'\', true);" ' +
                 'onclick="im_cl(\'poslito\',\''+itemData.id+'\', true);" ' +
             '>' +
             '<div class="ititle">'+itemData.time+'</div>' +
             '<div class="itxt">'+descr+'</div>' +
             '</div>');
}

function addMore(suff, author) {
    $('#list-'+suff).append('<div id="more-'+suff+'" class="more">' +
             '<a href="#load-'+suff+'" onclick="loadMore(\''+suff+'\',\''+author+'\'); return false;">Načíst starší...</a>' +
             '</div>');
}

function updateTop(idSide, itemData) {
    $('#'+idSide+' .title').html(itemData.time);
    $('#'+idSide+' .txt').html(itemData.descr);

    if (itemData.thumbs && itemData.thumbs[0]) {
        $('#'+idSide+' .thumb').attr('src', itemData.thumbs[0]);

        if (itemData.photos && itemData.photos[0] && itemData.photos[0].p) {
            $('#'+idSide+' .img A').attr('href', itemData.photos[0].p);
        } else {
            $('#'+idSide+' .img A').attr('href', './img/dummy_big.png');
        }
    } else {
        $('#'+idSide+' .thumb').attr('src', './img/dummy_big.png');
    }
}

function overlayInited() {
    var p = getUrlParams();
    if (p.i) {
        poslitoOverlay.markerClicked(p.i, true);

        var m = poslitoOverlay.getMarkerById(p.i);
        if (m) {
            track('ImgShow', p.i);
            $('#'+m.suff+' .img A').trigger('click');
        } else {
            alert('Vypadá to, že se Vám podařilo "rozkliknout" obrázek z dávné minulosti...\n\nPokud si jej opravdu chcete prohlédnout, budete muset zalovit v hloubi některého ze seznamů ve spodní části stránky.');
        }
    }
}

function gotoNext(suff) {
    var nextId = $('#list-'+suff+' .item.active').next().attr('id');
    if (nextId == 'more-'+suff) {
        loadMore(suff, suff == 'left' ? user1 : user2);
    } else {
        poslitoOverlay.markerClicked(nextId.replace('i-', ''), false);
    }
}

function gotoPrev(suff) {
    var prevId = $('#list-'+suff+' .item.active').prev().attr('id');
    if (prevId) {
        poslitoOverlay.markerClicked(prevId.replace('i-', ''), false);
    }
}