var shopitMapCallback; 
var shopitMarkers;

(function() {
    var markerClustererSrc = "http://gmaps-utility-library-dev.googlecode.com/svn/tags/markerclusterer/1.0/src/markerclusterer_packed.js";
    
    
    var city      = '';
    var map       = '';
    var mc        = '';
    var mcmarkers = [];
    var markers   = [];
    var type      = 'shopit';
    
    var mapListNext;
    var mapListPrev;
    
    function getMapsScriptSrc() {
        return "http://maps.google.com/maps?hl=fi&file=api&v=2&sensor=false&key=" + shopitGmapsApiKey + "&async=2&callback=shopitMapCallback";
    }
    
    function storeSearchFocus(e) {
        var target = e.target || e.srcElement;
        
        target.value = '';
    }
    
    function storeSearchUnfocus(e) {
        var target = e.target || e.srcElement;
        
        if (target.value == '') {
            target.value = target.defaultValue;
        }
    }
    
    function storeSearch(e) {
        if (typeof e.preventDefault != 'undefined'){
            e.preventDefault();
        } else {
            e.returnValue = false;
        }
        
        $('#map-list, #map-loading-error').hide();
        $('#map-loading').show();
        
        loadJSON(document.getElementById('shopitsearch').value);
    }
    
    function nextShopitInfo(e) {
        var currentItem = $('#map-list li').filter(':visible');
        
        if (typeof e.preventDefault != 'undefined'){
            e.preventDefault();
        } else {
            e.returnValue = false;
        }
        
        showShopitInfo(currentItem.next().attr('id').split('-')[1], true);
    }
    
    function prevShopitInfo(e) {
        var currentItem = $('#map-list li').filter(':visible');
        
        if (typeof e.preventDefault != 'undefined'){
            e.preventDefault();
        } else {
            e.returnValue = false;
        }
        
        showShopitInfo(currentItem.prev().attr('id').split('-')[1], true);
    }
    
    function showFirstShopitInfo() {
        showShopitInfo($('#map-list li').filter(':first').attr('id').split('-')[1]);
    }
    
    function showShopitInfo(id, center) {
        var infoItem = document.getElementById('shopitmapitemid-' + id);
        
        hideShopitInfo();
        $('#map-list, #map-list-content li#shopitmapitemid-' + id).show();
        
        mapListNext.style.display = infoItem.nextSibling == null ? 'none' : 'block';
        mapListPrev.style.display = infoItem.previousSibling == null ? 'none' : 'block';
        
        if (center != null && markers[id]) {            
            map.setCenter(markers[id].getLatLng(), 16);
        } 
    }
    
    function hideShopitInfo() {
        $('#map-list-content li').hide();
    }
    
    function loadJSON(city) {
        if (typeof jQuery == 'undefined') {
            return;
        }

        var bounds = '';
        markers    = [];
        mcmarkers  = [];

        map.clearOverlays();
        map.closeInfoWindow();

        if (typeof mc == 'object') {
            mc.clearMarkers();
        }
        
        markers = [];
        mcmarkers = [];
        $('#map-list').hide();
        $('#map-list-content').html('');

        if (city == '' || city == undefined || typeof city != 'string') {
            var city = '';
            var mgr  = true;
        } else {
            var city = '&city='+ city;
            var mgr  = false;
        }
        
        $.getJSON('shopit-json.php?type='+ type +'&stamp='+ new Date().getTime() + city, function(data) {
            if (data.status != 'error' && data.status != 'nocity') {
                var current = 0;

                if (!mgr) {
                    var sw = new GLatLng(data.minlat, data.minlon);
                    var ne = new GLatLng(data.maxlat, data.maxlon);
                    bounds = new GLatLngBounds(sw, ne);

                    delete data.minlat;
                    delete data.minlon;
                    delete data.maxlat;
                    delete data.maxlon;
                }

                $.each(data, function(i, item) {
                    if (data.length == i + 1) {
                        var cls = 'class="last"';
                    } else {
                        var cls = '';
                    }

                    var id       = item.id;
                    var name     = item.name;
                    var desc     = item.desc;
                    var edustaja = item.edustaja;
                    var status   = item.status;
                    var lon      = item.lon;
                    var lat      = item.lat;

                    if (edustaja == 0) {
                        var iconname = 'shopit';
                    } else {
                        var iconname = 'edustaja';
                    }
                    
                    $('ul#map-list-content').append(
                        '<li id="shopitmapitemid-'+ item.id +'" '+ cls +'>'+ item.desc +'</li>'
                    );

                    var icon = new GIcon();
                    icon.image = "http://www.elisa.fi/shopit/assets/img/icon_"+ iconname +"_"+ status +".png";
                    icon.shadow = "http://www.elisa.fi/shopit/assets/img/icon_shadow.png";
                    icon.iconSize = new GSize(119, 59);
                    icon.shadowSize = new GSize(119, 59);
                    icon.iconAnchor = new GPoint(60, 59);
                    icon.infoWindowAnchor = new GPoint(50, 10);
                    
                    var point  = new GLatLng(lat, lon);
                    var marker = new GMarker(point, {icon:icon, title:item.name, clickable:true, id:item.id});

                    GEvent.addListener(marker, 'click', function() {
                        map.panTo(marker.getLatLng());
                        showShopitInfo(marker.id);
                    });
                    
                    mcmarkers.push(marker);
                    markers[item.id] = marker;
                    
                    if (!mgr) {
                        map.addOverlay(marker);
                    }
                });

                hideShopitInfo();

                if (mgr) {
                    var opts = { gridSize: 70, maxZoom: 12};
                    mc       = new MarkerClusterer(map, mcmarkers, opts);
                } else {
                    $('ul#map-list-content li').hover(
                        function() {
                            $(this).css('cursor', 'pointer');
                        },
                        function() {
                            $(this).css('cursor', 'auto');
                        }
                    );
                    $('ul#map-list-content li').live('click', function(e) {
                        e.preventDefault();

                        var itemid = $(this).attr('id').split('-');
                        itemid = parseInt(itemid[1]);

                        if (!isNaN(itemid)) {
                            map.setCenter(markers[itemid].getLatLng(), 16);
                        }
                    });

                    showFirstShopitInfo();
                    map.setCenter(bounds.getCenter(), 11);
                }

                $('#map-loading').hide();
            } else if (data.status == 'nocity') {
                $('#map-loading').hide();
                if (type == 'shopit') {
                    $('#map-loading-error').html('Paikkakunnalta ei löytynyt Elisa Shopitia.');
                } else if (type == 'edustajat') {
                    $('#map-loading-error').html('Paikkakunnalta ei löytynyt Elisan edustajaa.');
                } else {
                    $('#map-loading-error').html('Paikkakunnalta ei löytynyt Elisa Shopitia tai edustajaa.');
                }
                $('#map-loading-error').show();
            } else {
                $('#map-loading').hide();
                $('#map-loading-error').html('Latausvirhe. Yritä myöhemmin uudestaan.');
                $('#map-loading-error').show();
            }
        });
    }
    
    function initShopitMap() {
        if (typeof GBrowserIsCompatible == 'undefined' || typeof GMap2 == 'undefined') {
            setTimeout(initShopitMap, 1000);
        } else if (GBrowserIsCompatible()) {
            bindEvent(window, 'unload', function(e) {unloadMap();})
            map = new GMap2(document.getElementById('shopitmap'), { backgroundColor: '#fff', mapTypes:[G_NORMAL_MAP] } );
            map.enableContinuousZoom();
            map.enableScrollWheelZoom();            
            map.setCenter(new GLatLng(62.5,27.4), 6);
            map.setMapType(G_NORMAL_MAP);
            map.addControl(new GSmallZoomControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(5, 15)));
            
            appendMarkerClustererScript();
        }
        
        // Bind result navigation events
        mapListNext = document.getElementById('map-list-next');
        mapListPrev = document.getElementById('map-list-prev');
        
        bindEvent(mapListPrev, 'click', prevShopitInfo);
        bindEvent(mapListNext, 'click', nextShopitInfo);
        
        // Bind search events
        bindEvent(document.getElementById('shopitsearchbtn'), 'click', storeSearch);
        bindEvent(document.getElementById('shopitsearchform'), 'submit', storeSearch);
        bindEvent(document.getElementById('shopitsearch'), 'focus', storeSearchFocus);
        bindEvent(document.getElementById('shopitsearch'), 'blur', storeSearchUnfocus);
    }
    
    function unloadMap(e) {
        GUnload();
    }
    
    // Load markerclusterer script
    function appendMarkerClustererScript() {
        var mcScriptNode = document.createElement('script');
        
        mcScriptNode.src = markerClustererSrc;
        mcScriptNode.type = 'text/javascript';        
        bindEvent(mcScriptNode, 'load', loadJSON);
        
        // Thank you IE!
        mcScriptNode.onreadystatechange= function () {
            if (this.readyState == 'complete' || this.readyState == 'loaded') {                
                loadJSON();
                delete this.onreadystatechange;
            }
        }
        
        document.body.appendChild(mcScriptNode);
    }
    
    // Load google maps script
    function appendMapScript() {
        var mapScriptNode = document.createElement('script');
        mapScriptNode.src = getMapsScriptSrc();
        mapScriptNode.type = 'text/javascript';
        
        document.body.appendChild(mapScriptNode);        
    }
    
    function bindEvent(target, event, handler) {
        if (target.addEventListener) {      
            target.addEventListener(event, handler, false);} 
        else if (target.attachEvent) {
            target.attachEvent('on' + event, handler); 
        } 
    }
    
    DD_roundies.addRule('#shopitsearch, #map-list, #map-loading, #map-loading-error', '10px', true);
    bindEvent(window, 'load', appendMapScript);
    shopitMapCallback = initShopitMap;
}());
