
jQuery.fn.setOuterWidth = function( newWidth ) {
    var difference = this.outerWidth(true) - this.width();
    return this.width( newWidth - difference );
};

jQuery.fn.setOuterHeight = function( newHeight ) {
    var difference = this.outerHeight(true) - this.height();
    return this.height( newHeight - difference );
};

function TRI2007TipControl () { }
function SchoolsTipControl () { }

$(document).ready(function () {
    if (GBrowserIsCompatible()) {
        $('#hide_page').show();
        var bookmark = window.location.href;
        var matches = bookmark.match(/#(.+)$/);

        if (matches && matches[1]) {
            var parts = matches[1].split(',');
            map_lat   = parseFloat( parts[0] );
            map_lon   = parseFloat( parts[1] );
            map_zoom  = parseInt( parts[2] );
        }

        var header_div = $('#header');
        var footer_div = $('#footer');
        var map_div = $('#map');
        var search_div = $('#search');
        var welcome_div = $('#welcome');
        var win = $(window);
        var body = $('body');
        var search_text = search_div.find(':text');
        var search_submit = search_div.find(':submit');
        win.resize(function(){
            var width = win.width();
            var height = win.height();
            if (width < 700) { width = 700; }
            if (height < 500) { height = 500; }

            header_div.setOuterWidth( width );
            footer_div.setOuterWidth( width );

            var bottom_height = height - header_div.outerHeight(true) - footer_div.outerHeight(true);
            map_div.setOuterHeight( bottom_height - search_div.outerHeight(true) );
            welcome_div.setOuterHeight( bottom_height );

            map_width = Math.round( width * .65 );
            map_div.setOuterWidth( map_width );
            search_div.setOuterWidth( map_width );

            welcome_div.css('left', map_width);
            welcome_div.setOuterWidth( width - map_width );

            footer_div.css('top', height - footer_div.outerHeight(true));
            search_div.css('top', height - footer_div.outerHeight(true) - search_div.outerHeight(true));
        });
        win.resize();

        var map = new GMap2( $('#map')[0] );
        map.setCenter(new GLatLng(map_lat, map_lon), map_zoom);
        map.enableScrollWheelZoom();
        map.setUIToDefault();

        setup_tile_overlay( map );
        setup_tri2007_tip( map );
        setup_school_tip( map );

        var type_icons = {};

        var school_icon = new GIcon();
        type_icons.school = school_icon;
        school_icon.image = "/images/icons/school_marker.png";
        school_icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
        school_icon.iconSize = new GSize(12, 20);
        school_icon.shadowSize = new GSize(22, 20);
        school_icon.iconAnchor = new GPoint(6, 20);
        school_icon.infoWindowAnchor = new GPoint(5, 1);

        type_icons.tri2007_facility = G_DEFAULT_ICON;

        var small_tri2007_icon = new GIcon();
        small_tri2007_icon.image = "/images/icons/tri2007_facility_marker.png";
        small_tri2007_icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
        small_tri2007_icon.iconSize = new GSize(12, 20);
        small_tri2007_icon.shadowSize = new GSize(22, 20);
        small_tri2007_icon.iconAnchor = new GPoint(6, 20);
        small_tri2007_icon.infoWindowAnchor = new GPoint(5, 1);

        var markers = [];
        var loading_markers = 0;
        var loading_marker_info = 0;
        var load_markers = function () {
            if (!map.getInfoWindow().isHidden()) { return; }
            if (loading_markers) { return; }
            loading_markers = 1;

            var map_center = map.getCenter();
            var map_zoom = map.getZoom();

            $.getJSON(
                '/api/markers',
                { lat:map_center.lat(), lon:map_center.lng(), z:map_zoom },
                function (data) {
                    $.each( markers, function (i, marker) {
                        map.removeOverlay( marker );
                    });
                    markers = [];

                    $.each(data, function(i,item){
                        var icon = type_icons[item[3]];
                        if (map_zoom <= 10 && item[3] == 'tri2007_facility') {
                            icon = small_tri2007_icon;
                        }
                        var marker = new GMarker( new GLatLng( item[1], item[2] ), { icon:icon } );
                        GEvent.addListener(
                            marker,
                            'click',
                            function () {
                                if (!loading_marker_info) {
                                    loading_marker_info = 1;
                                    $.get(
                                        '/api/marker_info',
                                        { id:item[0], type:item[3] },
                                        function (html) {
                                            marker.openInfoWindowHtml( html );
                                            loading_marker_info = 0;
                                        }
                                    );
                                }
                            }
                        );
                        markers.push( marker );
                        map.addOverlay( marker );
                    });

                    loading_markers = 0;
                }
            );
        }
        load_markers();

        GEvent.addListener(map, 'moveend', function () {
            var map_center = map.getCenter();
            var map_zoom = map.getZoom();
            var lat = Math.round( map_center.lat() * 1000000 ) * 0.000001;
            var lon = Math.round( map_center.lng() * 1000000 ) * 0.000001;
            window.location.href = 'http://toxicrisk.com/#' + lat + ',' + lon + ',' + map_zoom;

            load_markers();
        });

        win.unload(function () {
            GUnload();
        });
    }
});

function setup_tile_overlay (map) {
    var myCopyright = new GCopyrightCollection('Data');
    myCopyright.addCopyright(new GCopyright(1, new GLatLngBounds(new GLatLng(-90,-180), new GLatLng(90,180)), 0, '©20010 ToxicRisk.com'));

    var tilelayer = new GTileLayer(myCopyright, 0, 9);
    tilelayer.getTileUrl = function(tile, zoom) { return '/api/tile?z=' + zoom + '&x=' + tile.x + '&y=' + tile.y; };
    tilelayer.isPng = function() { return true;};
    tilelayer.getOpacity = function() { return 1.0; }

    var myTileLayer = new GTileLayerOverlay(tilelayer);
    map.addOverlay(myTileLayer);
}

function setup_tri2007_tip (map) {
    var seen_tri2007_tip = false;
    var tri2007_tip_div = $('#tri2007_tip');
    TRI2007TipControl.prototype = new GControl();
    TRI2007TipControl.prototype.initialize = function(map) {
        var div = tri2007_tip_div.get(0);
        map.getContainer().appendChild(div);
        return div;
    };
    TRI2007TipControl.prototype.getDefaultPosition = function() {
        return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(75, 10));
    }
    map.addControl(new TRI2007TipControl());
    GEvent.addListener(map, 'zoomend', function (oldZoom, newZoom) {
        if (newZoom < 9) { if (!seen_tri2007_tip) { tri2007_tip_div.show(); seen_tri2007_tip=true; } }
        else { tri2007_tip_div.hide(); }
    });
    if (map_zoom < 9) { tri2007_tip_div.show(); seen_tri2007_tip=true; }
    tri2007_tip_div.click(function(){ tri2007_tip_div.fadeOut('normal') });
}

function setup_school_tip (map) {
    var seen_schools_tip = false;
    var schools_tip_div = $('#schools_tip');
    SchoolsTipControl.prototype = new GControl();
    SchoolsTipControl.prototype.initialize = function(map) {
        var div = schools_tip_div.get(0);
        map.getContainer().appendChild(div);
        return div;
    };
    SchoolsTipControl.prototype.getDefaultPosition = function() {
        return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(75, 10));
    }
    map.addControl(new SchoolsTipControl());
    GEvent.addListener(map, 'zoomend', function (oldZoom, newZoom) {
        if (newZoom >= 11 && newZoom <= 13) { if (!seen_schools_tip) { schools_tip_div.show(); seen_schools_tip=true; } }
        else { schools_tip_div.hide(); }
    });
    if (map_zoom >= 11 && map_zoom <= 13) { schools_tip_div.show(); seen_schools_tip=true; }
    schools_tip_div.click(function(){ schools_tip_div.fadeOut('normal') });
}

