var map;
window.addEvent('domready', function(){
    var url = window.location.pathname;
    var resulturl;
    var markers = [];
    var cities = $A(new Array());
    
    try {
        resulturl = url.match("/([a-z]{2}).*")[1];
    } 
    catch (e) {
    }
    //współrzędne i zoomy miast 
    var citiesZoom = $H({
        "Białystok": [53.13214796651392, 23.13617706298828, 12],
        "Bielsko-Biała": [49.836653876277474, 19.042739868164062, 12],
        "Bydgoszcz": [53.12133245371114, 18.01654815673828, 12],
        "Częstochowa": [50.810273774885715, 19.136123657226562, 11],
        "Gdańsk": [54.36935859782678, 18.60260009765625, 10],
        "Gdynia": [54.5019475090286, 18.494110107421875, 11],
        "Gliwice": [50.29350677155152, 18.67229461669922, 12],
        "Gorzów Wlkp.": [52.729400000, 15.2366000000, 12],
        "Jelenia Góra": [50.894155023517996, 15.71868896484375, 12],
        "Katowice": [50.25444939627204, 19.040679931640625, 12],
        "Kielce": [50.87292803971143, 20.637130737304688, 12],
        "Koszalin": [54.18674924927684, 16.195220947265625, 12],
        "Kraków": [50.046116449029974, 19.958038330078125, 11],
        "Lublin": [51.2365569677084, 22.56866455078125, 11],
        "Łódź": [51.76614013468048, 19.473953247070312, 11],
        "Nowy Sącz": [49.614046805354874, 20.71197509765625, 12],
        "Olsztyn": [53.77529751362436, 20.49276351928711, 13],
        "Opole": [50.66382571601043, 17.926254272460938, 12],
        "Poznań": [52.40995897800503, 16.907272338867188, 11],
        "Pszczyna": [49.98368235554624, 18.94420623779297, 10],
        "Płock": [52.53251395547033, 19.71050262451172, 12],
        "Pruszków": [52.167805,20.804464, 12],
        "Radom": [51.398563061696656, 21.15863800048828, 12],
        "Rzeszów": [50.03884032635863, 22.01007843017578, 12],
        "Siedlce": [52.16361362747181, 22.27924346923828, 12],
        "Sopot": [54.44009946480451, 18.57135772705078, 13],
        "Sosnowiec": [50.28517137001351, 19.12067413330078, 13],
        "Szczecin": [53.42155344186486, 14.550275802612305, 14],
        "Słupsk": [54.46584759009005, 17.050437927246094, 12],
        "Toruń": [53.015402879526796, 18.64654541015625, 12],
        "Warszawa": [52.25596977807852, 21.038131713867188, 11],
        "Wejherowo": [54.60200268707043, 18.244171142578125, 13],
        "Wolbrom": [50.379736222268704, 19.764575958251953, 13],
        "Włocławek": [52.648745, 19.0623, 13],
        "Wrocław": [51.10847996087536, 17.02880859375, 12],
        "Zielona Góra ": [51.93452867390717, 15.500335693359375, 12]
    })
    
    showCountry = function(a){
        if (resulturl) 
            url = "/" + resulturl + "/distr/country/" + a.value;
        if (a.value != '') 
            window.location.href = url;
    }
    function showAddress(address){
        if (address == "Polska") {
            showCityMarkers();
        }
        else {
            showDistributorsMarkers(address);
        }
    }
    var showCityMarkers = function(){
        map.clearOverlays();
        map.setCenter(new GLatLng(52.025459, 19.204102), 6);
        cities.each(function(city){
            var cityPosZoom = citiesZoom.get(city);
            if (cityPosZoom) {
                var cityMarker = new GMarker(new GLatLng(cityPosZoom[0], cityPosZoom[1]));
                cityMarker.cityZoom = cityPosZoom[2];
                cityMarker.cityName = city;
                GEvent.addListener(cityMarker, "click", function(){
                    map.setCenter(this.getLatLng(), this.cityZoom);
                    $('citySelect').set('value', this.cityName);
                    showDistributorsMarkers(null);
                });
                map.addOverlay(cityMarker);
            }
            else 
            if (geocoder) {
                geocoder.getLatLng(city, function(point){
                    if (point) {
                        var cityMarker = new GMarker(new GLatLng(point.y, point.x));
                        cityMarker.cityZoom = 12;
                        cityMarker.cityName = city;
                        GEvent.addListener(cityMarker, "click", function(){
                            map.setCenter(this.getLatLng(), this.cityZoom);
                            $('citySelect').set('value', this.cityName);
                            showDistributorsMarkers(null);
                        });
                        map.addOverlay(cityMarker);
                    }
                });
            }
        })
    }
    var showDistributorsMarkers = function(zoomToCity){
        map.clearOverlays();
        if (zoomToCity != null) {
            var ct = citiesZoom.get(zoomToCity);
            map.setCenter(new GLatLng(ct[0], ct[1]), ct[2]);
        }
        markers.each(function(marker, i){
            markers[i].overlay = map.addOverlay(marker);
        })
    }
    function initialize(){
        if (GBrowserIsCompatible()) {
            map = new GMap2(document.getElementById("map_canvas"));
            map.addControl(new GLargeMapControl());
            map.addControl(new GMapTypeControl());
            
            var icon = new GIcon(G_DEFAULT_ICON);
            icon.image = "http://chart.apis.google.com/chart?cht=mm&chs=24x32&chco=FFFFFF,008CFF,000000&ext=.png";
            
            geocoder = new GClientGeocoder();
            //centruj na Polskę
            map.setCenter(new GLatLng(52.025459, 19.204102), 6);
            new Request.JSON({
                url: "/dystr.php?t=fetch",
                data:{
                    region: '',
                    country: $('countrySelect').value
                },
                onSuccess: function(result){
                
                    result = $H(result);
                    result.each(function(point, i){
                        var latlng = new GLatLng(point.lat, point.lng);
                        
                        var markerOptions = {
                            draggable: false
                        };
                        var marker = new GMarker(latlng, markerOptions);
                        marker.info = {
                            "name": point.name,
                            "address1": point.address1,
                            "address2": point.address2,
                            "address3": point.address3,
                            "phone1": point.phone1,
                            "phone2": point.phone2,
                            "phone3": point.phone3,
                            "fax": point.fax,
                            "email": point.email,
                            "www": point.website
                        };
                        cities = cities.include(point.city);
                        //map.addOverlay(marker);
                        
                        GEvent.addListener(marker, "click", function(){
                            var tabs = [];
                            var tip = "";
                            tip += "<b>" + this.info.name + "</b><br />";
                            tip += this.info.address1 + "<br />";
                            if (this.info.address2 != "") 
                                tip += this.info.address2 + "<br />";
                            if (this.info.address3 != "") 
                                tip += this.info.address3 + "<br />";
                            if (this.info.phone1 != "") 
                                tip += "tel." + this.info.phone1 + "<br />";
                            if (this.info.phone2 != "") 
                                tip += "tel." + this.info.phone2 + "<br />";
                            if (this.info.fax != "") 
                                tip += "fax." + this.info.fax + "<br />";
                            if (this.info.www != "") 
                                tip += "<a href='http://" + this.info.www + "' target='_blank'>" + this.info.www + "</a><br />";
                            if (this.info.email != "") 
                                tip += "<a href='mailto:" + this.info.email + ">" + this.info.email + "</a>";
                            var stars = ["szybkość realizacji", "jakość obsługi"];
                            var opinie = "";
                            for (var i = 0; i < stars.length; i++) {
                                opinie += "<img src='/img/stars" + $random(1, 5) + ".gif' /> - " + stars[i] + "<br />";
                            }
                            var labels = ["adres", "opinie"];
                            //var htmls = [tip,opinie];
                            var htmls = [tip];
                            for (var i = 0; i < htmls.length; i++) {
                                tabs.push(new GInfoWindowTab(labels[i], htmls[i]));
                            }
                            marker.openInfoWindowTabsHtml(tabs);
                        });
                        
                        markers.push(marker);
                    });
                    
                    var select = new Element('select', {
                        id: 'citySelect',
                        style: "width: 200px;margin-top:10px;margin-bottom:20px"
                    });
                    new Element('option', {
                        value: "Polska",
                        text: "wszystkie"
                    }).inject(select);
                    
                    function sortUnicode(a, b){
                        if (a.charCodeAt(0) >= 77 && a.charCodeAt(0) < 300) 
                            a = a.replace(/^./, String.fromCharCode(a.charCodeAt(0) + 1));
                        if (b.charCodeAt(0) >= 77 && b.charCodeAt(0) < 300) 
                            b = b.replace(/^./, String.fromCharCode(b.charCodeAt(0) + 1));
                        if (a.charCodeAt(0) == 321) 
                            a = a.replace(/^./, "M");
                        if (b.charCodeAt(0) == 321) 
                            b = b.replace(/^./, "M");
                        return a > b;
                        
                    }
                    cities.sort(sortUnicode);
                    
                    cities.each(function(c){
                        new Element('option', {
                            value: c,
                            text: c
                        }).inject(select);
                    });
                    select.inject($('map_canvas').getParent('div'), 'before');
                    new Element('div', {
                        style: "margin-top:10px;",
                        html: "Wybierz miasto: "
                    }).injectBefore(select);
                    
                    select.addEvent('change', function(el){
                        showAddress(this.value);
                    })
                    //                    var mcOptions = {
                    //                        gridSize: 10,
                    //                        maxZoom: 15
                    //                    };
                    showCityMarkers();
                
                }
            }).send();
            
            
        }
    }
    
    initialize();
    
})
window.addEvent('unload', function(){
    GUnload();
});

