function setup_fancybox() {
    $('a.fancybox, a.fancybox_big').unbind('click');
    $('a.fancybox, a.fancybox_big').unbind('click.fb');
    $('a.fancybox').fancybox({
        hideOnContentClick: false,
        callbackOnClose: function() {
            top.location.hash = '';
        }
    });
    $('a.fancybox_big').fancybox({
        hideOnContentClick: false,
        frameHeight: 600,
        frameWidth: 800,
        callbackOnClose: function() {
            top.location.hash = '';
        }
    });
    $('a.fancybox, a.fancybox_big').bind('click.fb', function() {
        top.location.hash = this.href.replace(/http:\/\/[\w\.:]*/g, '').replace('?iframe', '');
    });
}
window.setup_fancybox = setup_fancybox

function addOpenLayer(map, name, url_callback) {
    var copyright = new GCopyright(1, new GLatLngBounds(new GLatLng(53.8136257,-3.0981445), new GLatLng(53.8654855,-2.9663944)), 17, "");
    var copyrightCollection = new GCopyrightCollection('');
    copyrightCollection.addCopyright(copyright);

    var tilelayers = [new GTileLayer(copyrightCollection, 1, 17)];
    tilelayers[0].getTileUrl = url_callback;
    var ocmmap = new GMapType(tilelayers, G_SATELLITE_MAP.getProjection(), name);
    map.addMapType(ocmmap);
}

function initialize() {
    if (GBrowserIsCompatible() && document.getElementById("map_canvas")) {
        // Initialize
        if(document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#SVG","1.1")){
            _mSvgEnabled = true;
            _mSvgForced  = true;
        }

        map = new GMap2(document.getElementById("map_canvas"));
        if (window.city) {
            map.setCenter(new GLatLng(window.city[0], window.city[1]), 13);
        } else {
            map.setCenter(new GLatLng(59.939039, 30.315785), 13);
        }
        var opts = {
          zoomInBtnTitle : "Ближе",
          zoomOutBtnTitle : "Дальше",
          moveNorthBtnTitle : "Север",
          moveSouthBtnTitle : "Юг",
          moveEastBtnTitle : "Восток",
          moveWestBtnTitle : "Запад",
          homeBtnTitle : "В начало"
        };
        var extLargeMapControl = new ExtLargeMapControl(opts);
        map.addControl(extLargeMapControl);

        var typeControl = new GMapTypeControl();
        map.addControl(typeControl);

        map.clearOverlays();

        addOpenLayer(map, "Open", function(a,b){return 'http://a.tile.openstreetmap.org/'+b+'/'+a.x+'/'+a.y+'.png';});
        addOpenLayer(map, "Cycle", function(a,b){return 'http://a.andy.sandbox.cloudmade.com/tiles/cycle/'+b+'/'+a.x+'/'+a.y+'.png';});

        if ($.cookie('map_type')) {
            map.setMapType(map.getMapTypes()[$.cookie('map_type')]);
        };

        GEvent.addListener(map, "maptypechanged", function() {
            var types = map.getMapTypes();
            for (var i in types) {
                if (types[i] == map.getCurrentMapType()) {
                    $.cookie('map_type', i, { expires: 31, path: '/'});
                }
            }
        });

        map.enableContinuousZoom();
        map.enableScrollWheelZoom();
    }
    setup_fancybox();

/*
    if ($.cookie('waiter_seen') != '1') {
        var el = $('<a href="#wait"></a>');
        el.fancybox({
            showCloseButton: false,
            hideOnOverlayClick: false,
            hideOnContentClick: false,
            callbackOnShow: function() {
                $('#fancy_div a').click(function() {
                    $.cookie('waiter_seen', '1', {expires: 365});
                    $.fn.fancybox.close();
                });
            }
        })
        el.trigger('click.fb');
    }
*/

    if (top.location.hash) {
         var a = top.location.hash.substring(1) + '?iframe';
         $('a[href$='+a+']').trigger('click.fb');
    }

    if (window.routes) {
        if (window.authenticated) {
            // heatmap
            var bounds = new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 180));
            var copyright = new GCopyright('ilvar', bounds, 0, "(c) 2008 BkMe " +"<http://www.bkme.ru/>");
            var copyrights = new GCopyrightCollection();
            copyrights.addCopyright(copyright);
            heatmap = new GTileLayer(copyrights, 10, 0);
            heatmap.getTileUrl = function (tile, zoom) {
                if (zoom > 13) {
                    return null;
                };
                base = 'http://bkme.ru/heat/';
                color_scheme = 'bkme';
                url = base + color_scheme +'/'+ zoom +'/'
                url += tile.x +','+ tile.y +'.png';
                return url;
            }
            heatmap.opacity = 0.2;
            heatmap.isPng = function () {return true;}
            heatmap.getOpacity = function () {return this.opacity;}

            window.heatmap_overlay = new GTileLayerOverlay(heatmap);
            if ($.cookie('show_heatmap')) { map.addOverlay(window.heatmap_overlay); }
            map.addControl(new OpacityControl( window.heatmap_overlay ));
        };

        var over_bounds = null;

        for (idx in window.routes) {
            var route = window.routes[idx];
            var line = new GPolyline.fromEncoded({
                color: "#009900",
                weight: 4,
                opacity: 0.5,
                points: route.points,
                levels: route.levels,
                zoomFactor: route.zoomFactor,
                numLevels: route.numLevels
            });

            window.routes[idx].line = line;

            if ($.cookie('show_routes')) { map.addOverlay(line); }

            if (line.getBounds()) {
                line.info_url = route.info_url;
                GEvent.addListener(line, "click", function() {
                    $('<a href="'+this.info_url+'?iframe"></a>').fancybox().trigger('click.fb');
                });

                if (!over_bounds) {
                    over_bounds = line.getBounds();
                } else {
                    var line_bounds = line.getBounds();
                    if (line_bounds) {
                        over_bounds.extend(line_bounds.getSouthWest());
                        over_bounds.extend(line_bounds.getNorthEast());
                    }
                }
            };

        };

        if (over_bounds) {
            map.setCenter(over_bounds.getCenter(), Math.min(map.getZoom(), map.getBoundsZoomLevel(over_bounds), 10))
        };

    };

    if (window.points && $.cookie('show_points')) {
        var markers = getMarkersList(window.points)
        window.markerClusterer = new MarkerClusterer(map, markers);
    }

    if (window.route_url) {
        var geoXml = new GGeoXml(window.route_url);

        map.addOverlay(geoXml);
    }

    if (window.locations) {
        for (idx in window.locations) {
            var l = window.locations[idx];
            var marker = new GMarker(l.latlng);
            marker.l = l;
            l.marker = marker;
            GEvent.addListener(marker, "click", function() {
                this.openInfoWindowHtml(this.l.owner.avatar+" <b><a href='"+this.l.owner.url+"'>"+this.l.owner.name+"</b></a> <br/> "+this.l.title+" <br/> "+this.l.updated);
            });
            if ($.cookie('show_users')) { map.addOverlay(marker); }
        }
    }


    function GroupsControl() {}
    GroupsControl.prototype = new GControl();

    function add_checkbox_to_group(container, name, checked, callback) {
        var cbDiv = document.createElement("div");
        var cbLabel = document.createElement("label");
        var cbInput = document.createElement("input");
        cbInput.type = 'checkbox';
        cbInput.checked = checked,
        container.appendChild(cbDiv);
        cbDiv.appendChild(cbLabel);
        cbLabel.appendChild(cbInput);
        cbLabel.appendChild(document.createTextNode(name));
        GEvent.addDomListener(cbInput, "change", callback);
    }

    GroupsControl.prototype.initialize = function(map) {
        var container = document.createElement("div");
        container.style.background = "white";
        container.style.border = "1px gray solid";
        container.style.padding = "0.5em";

        add_checkbox_to_group(container, 'Показывать маршруты', $.cookie('show_routes') || false, function() {
            $.cookie('show_routes', this.checked && -1 || null, {expires: 365});
            for (idx in window.routes) {
                if (this.checked) {
                    map.addOverlay(window.routes[idx].line);
                } else {
                    map.removeOverlay(window.routes[idx].line);
                }
            }
        });

        add_checkbox_to_group(container, 'Показывать точки', $.cookie('show_points') || false, function() {
            $.cookie('show_points', this.checked && -1 || null, {expires: 365});
            if (this.checked) {
                var markers = getMarkersList(window.points)
                window.markerClusterer = new MarkerClusterer(map, markers, {gridSize: 200, maxZoom: 11});
            } else {
                window.markerClusterer.clearMarkers()
                window.markerClusterer = null;
            }
        });

        add_checkbox_to_group(container, 'Показывать пользователей', $.cookie('show_users') || false, function() {
            $.cookie('show_users', this.checked && -1 || null, {expires: 365});
            for (idx in window.locations) {
                if (this.checked) {
                    map.addOverlay(window.locations[idx].marker);
                } else {
                    map.removeOverlay(window.locations[idx].marker);
                }
            }
        });

        if (window.authenticated) {
            add_checkbox_to_group(container, 'Показывать heatmap', $.cookie('show_heatmap') || false, function() {
                $.cookie('show_heatmap', this.checked && -1 || null, {expires: 365});
                if (this.checked) {
                    map.addOverlay(window.heatmap_overlay);
                } else {
                    map.removeOverlay(window.heatmap_overlay);
                }
            });
        }

        map.getContainer().appendChild(container);
        return container;
    }

    GroupsControl.prototype.getDefaultPosition = function() {
      return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(7, 21));
    }

    map.addControl(new GroupsControl());

    $('#cities').change(function() {
        $.cookie('city', $('#cities').val(), {expires: 365, path: "/"});
        top.location.href = top.location.href;
    });
}

function getMarkersList(points) {
    var markers = [];
    for (idx in points) {
        var point = points[idx];

        var markerIcon = new GIcon();
        markerIcon.iconSize = new GSize(16, 16);
        markerIcon.iconAnchor = new GPoint(8, 8);
        markerIcon.infoWindowAnchor = new GPoint(8, 8);
        markerIcon.image = "http://bkme.ru/media/images/icons/"+point.icon+".png";

        var marker = new GMarker(new GLatLng(point.lat, point.lng), { icon:markerIcon });
        marker.info_url = point.info_url;
        GEvent.addListener(marker, "click", function() {
            $('<a href="'+this.info_url+'?iframe"></a>').fancybox().trigger('click.fb');
        });

        markers.push(marker);
    };

    return markers;
}

$().ready(initialize);
