$(document).ready( function() {
    var mapCopy, mapRev;
    var mapRand = Math.round(Math.random() * 10000000000);

    var months = new Array();
    months[1]  = 'Tammikuu';
    months[2]  = 'Helmikuu';
    months[3]  = 'Maaliskuu';
    months[4]  = 'Huhtikuu';
    months[5]  = 'Toukokuu';
    months[6]  = 'Kesäkuu';
    months[7]  = 'Heinäkuu';
    months[8]  = 'Elokuu';
    months[9]  = 'Syyskuu';
    months[10] = 'Lokakuu';
    months[11] = 'Marraskuu';
    months[12] = 'Joulukuu';

    if (window.location.search) {
        var matches = window.location.search.match('(\\?|;|&|^)rev=([^;&]*)(;|&|$)');

        if (matches) {
            mapRev  = matches[2];
            mapCopy = mapRev.match(/(\d{2})M(\d{4})/);
        } else {
            $.getJSON('revision.txt?rand='+ mapRand, function(data) {
                mapRev  = data.revision;
                mapCopy = mapRev.match(/(\d{2})M(\d{4})/);
            });
        }
    } else {
        $.getJSON('revision.txt?rand='+ mapRand, function(data) {
            mapRev  = data.revision;
            mapCopy = mapRev.match(/(\d{2})M(\d{4})/);
        });
    }

    if (GBrowserIsCompatible()) {
        fixElements();

        var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
        var ie6  = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);
        if ($.browser.msie && (ie55 || ie6)) {
            DD_belatedPNG.fix('#map-header, #map-search, #map-search-help, #map-search-box, #map-footer');
        }

        var mapBounds  = new GLatLngBounds(new GLatLng(59.4090976325, 15.8112303566), new GLatLng(70.632299363, 33.6230671199));
        var mapMinZoom = 4;
        var mapMaxZoom = 12;

        var gcr  = GMapType.prototype.getCopyrights;
        GMapType.prototype.getCopyrights = function(bounds,zoom) {
            return [months[parseInt(mapCopy[1])] +" "+mapCopy[2]+" &copy; Elisa"].concat(gcr.call(this,bounds,zoom));
        }
        var map = new GMap2( document.getElementById("map"), { backgroundColor: '#fff', mapTypes:[G_NORMAL_MAP] } );
        map.setCenter(new GLatLng(60.7,25.5), 8);

        var mt = map.getMapTypes();
        for (var i=0; i<mt.length; i++) {
            mt[i].getMinimumResolution = function() {return 4;}
            mt[i].getMaximumResolution = function() {return 12;}
        }

        var hybridOverlay = new GTileLayerOverlay( G_NORMAL_MAP.getTileLayers()[1] );

        var tilelayer = new GTileLayer(GCopyrightCollection(''), mapMinZoom, mapMaxZoom);
        var mercator = new GMercatorProjection(mapMaxZoom+1);
        tilelayer.getTileUrl = function(tile, zoom) {
            if ((zoom < mapMinZoom) || (zoom > mapMaxZoom)) {
                return 'http://fs-www.elisa.fi/kuuluvuus/none.png';
            } 
            var ymax = 1 << zoom;
            var y = ymax - tile.y -1;
            var tileBounds = new GLatLngBounds(
                mercator.fromPixelToLatLng( new GPoint( (tile.x)*256, (tile.y+1)*256 ) , zoom ),
                mercator.fromPixelToLatLng( new GPoint( (tile.x+1)*256, (tile.y)*256 ) , zoom )
            );
	        if (mapBounds.intersects(tileBounds)) {
                return 'http://t'+rand(4)+'.fs-www.elisa.fi/kuuluvuus/'+ mapRev +'/'+ zoom +'/'+ tile.x +'/'+ y +'.png';
            } else {
                return 'http://fs-www.elisa.fi/kuuluvuus/none.png';
            }
        }
        tilelayer.isPng = function() { return true; };

        var overlay = new GTileLayerOverlay( tilelayer );
        map.addOverlay(overlay);

        var topLeft = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(25,90));
        map.addControl(new GLargeMapControl3D(), topLeft);
        map.addControl(new GOverviewMapControl()); 

        map.disableInfoWindow();
        map.enableContinuousZoom();
        map.enableScrollWheelZoom();

        map.setMapType(G_NORMAL_MAP);

        $('#map-address').mouseover( function() {
            if ($('#map-search-box').css('display') == 'none') $('#map-search-help').slideToggle('fast');
        }).mouseout(function(){
            if ($('#map-search-box').css('display') == 'none') $('#map-search-help').slideToggle('fast');
        });

        var footer  = 'open';
        var footerh = '25px';
        $('#map-footer .openclose').click( function() {
            $('#map-footer').animate({height: 0}, {duration: 500, complete: function() {
                if (footer == 'open') {
                    $('#map-footer').css({'background': 'url(/kuuluvuus/assets/img/map-footer-closed.png) no-repeat', 'height': '35px'});
                    footer  = 'closed';
                    footerh = '132px';
                } else {
                    $('#map-footer').css({'background': 'url(/kuuluvuus/assets/img/map-footer-open.png) no-repeat', 'height': '132px'});
                    footer  = 'open';
                    footerh = '35px';
                }
            }
            });
            $('#map-footer').animate({height: footerh}, {duration: 500});
        });

        $('#map-footer .reset').click( function(e) {
            e.preventDefault();

            map.clearOverlays();
            map.addOverlay(overlay);
            map.setCenter(new GLatLng(60.7,25.5), 8);
        })


        $('#map-search').submit( function(e) {
            e.preventDefault();

            var address = $('#map-address').val();

            if (address != '') {
                var geocoder  = new GClientGeocoder();
                // geocoder.getLocations(address, addAddressToMap);
                geocoder.getLatLng(address, function(point) {
                    if (point) {
                        if (mapBounds.contains(point)) {
                            var icon = new GIcon();
                            icon.image = "/kuuluvuus/assets/img/ico_marker.png";
                            icon.shadow = "/kuuluvuus/assets/img/ico_marker_shadow.png";
                            icon.iconSize = new GSize(26.0, 41.0);
                            icon.shadowSize = new GSize(47.0, 41.0);
                            icon.iconAnchor = new GPoint(13.0, 20.0);
                            icon.infoWindowAnchor = new GPoint(13.0, 20.0);
        
                            map.setCenter(point, 11);
                            map.addOverlay(new GMarker(point, icon));
                        }
                    } else {
                        if ($('#map-search-help').css('display') == 'block') $('#map-search-help').hide();
                        $('#map-search-box').html('<p>Osoitetta ei löytynyt</p><p><a href="#" class="close">Sulje</a></p>');
                        $('#map-search-box').show();
                    }
                });
            }
        });

        $('.close').live('click', function(e) {
            e.preventDefault();
            $(this).parent().parent().hide();
            $(this).parent().parent().html('');
        });
    }
});

$(document).unload( function() {
    GUnload();
});

$(window).resize( function() {
    fixElements();
});

function addAddressToMap(result) {
    if (result.Status.code == 200) {
        if (result.Placemark.length > 1) { 
            for (var i=0; i < result.Placemark.length; i++) {

            }
        } else {
            var coords = result.Placemark[0].Point.coordinates;
            var point  = new GPoint(coords[0], coords[1]);
        }
    } else {
        // Adress not found
    }
}

function rand(n) {
  return (Math.floor(Math.random()*n+1));
}

function fixElements() {
    $('#map').css({'height': $(window).height()-78 +'px'});

    return true;
}