var gMapController = {
    // centrujeme na stred republiky
    defaultZoom: 14, // zaber na republiku
    defaultLat:48.1571184379,
    defaultLng:11.5724415779,
    defaultHotel: null,
    lang:'en',
    firstLoad: true,
    options: false,
    center: false,
    filters: "",
    coordSWMapX: false,
    coordSWMapY: false,
    coordNEMapX: false,
    coordNEMapY: false,
    objType: 0,
    loading: 0, // obsahuje 3 stavy 0: nic se nenacita, 1:nacita se, 2:se znovu spusti jakmile dojede posledni
    marker: Array(),
    container: false, // pole objektu s daty
    containerCities: false,
    containerCountries: false,
    map: false,
    smallTypes: {2:"a_small_blue.png", 3:"p_small_blue.png", 13:"o_small_blue.png", 14:"h_small_blue.png"},
    detailedTypes: {"14":"h_blue.png", "14_1":"h_1_blue.png", "14_2":"h_2_blue.png", "14_3":"h_3_blue.png", "14_4":"h_4_blue.png", "14_5":"h_5_blue.png", "2":"a_blue.png", "2_1":"a_1_blue.png", "2_2":"a_2_blue.png", "2_3":"a_3_blue.png", "2_4":"a_4_blue.png", "2_5":"a_5_blue.png", "3":"p_blue.png", "3_1":"p_1_blue.png", "3_2":"p_2_blue.png", "3_3":"p_3_blue.png", "3_4":"p_4_blue.png", "3_5":"p_5_blue.png", "13":"o_blue.png", "13_1":"o_1_blue.png", "13_2":"o_2_blue.png", "13_3":"o_3_blue.png", "13_4":"o_4_blue.png", "13_5":"o_5_blue.png"},
    defaultTypes: {"14":"h_green.png", "14_1":"h_1_green.png", "14_2":"h_2_green.png", "14_3":"h_3_green.png", "14_4":"h_4_green.png", "14_5":"h_5_green.png", "2":"a_green.png", "2_1":"a_1_green.png", "2_2":"a_2_green.png", "2_3":"a_3_green.png", "2_4":"a_4_green.png", "2_5":"a_5_green.png", "3":"p_green.png", "3_1":"p_1_green.png", "3_2":"p_2_green.png", "3_3":"p_3_green.png", "3_4":"p_4_green.png", "3_5":"p_5_green.png", "13":"o_green.png", "13_1":"o_1_green.png", "13_2":"o_2_green.png", "13_3":"o_3_green.png", "13_4":"o_4_green.png", "13_5":"o_5_green.png"},
    cityTypes: {},
    arrCityMarkers: [],
    arrCountryMarkers: [],
    objMarkers: {},
    arrMarkers: {},
    markerTypes: {},
    markerManager: {},
    translations: {priceFrom: 'Price from', more: 'more', countryWindowText: ' accommodation offers in ', countryDestinations: ' destinations', cityWindowText: ' offers for accommodation in ', continents: '%d accommodation offers in %d countries in %s', notFound: 'not found'},
    smallIcon: function(number) {
        if(!number) {
            number = 13;
        }
        var tiny = new GIcon();
        if(this.smallTypes[gMapController.container[number].type]) {
            tiny.image = "/images/icons/maps/" + this.smallTypes[gMapController.container[number].type];
        }
        else {
            tiny.image = "/images/icons/maps/" + this.smallTypes[13];
        }
        tiny.shadow = "/images/icons/maps/small_shadow.png";
        tiny.iconSize = new GSize(13, 15);
        tiny.iconShadowSize = new GSize(23, 15);
        tiny.infoWindowAnchor = new GPoint(13, 15);
        tiny.iconAnchor = new GPoint(7, 15);
        return tiny;
    },
    bigIcon: function(number) {
        if(!number) {
            number = 13;
        }
        var tiny = new GIcon();

        if(gMapController.container[number].stars != '') {
            tiny.image = "/images/icons/maps/" + this.detailedTypes[gMapController.container[number].type + '_' + gMapController.container[number].stars];
        }
        else {
            tiny.image = "/images/icons/maps/" + this.detailedTypes[gMapController.container[number].type];
        }
        tiny.shadow = "/images/icons/maps/normal_shadow.png";
        tiny.iconSize = new GSize(27, 31);
        tiny.iconShadowSize = new GSize(45, 31);
        tiny.infoWindowAnchor = new GPoint(27, 31);
        tiny.iconAnchor = new GPoint(14, 31);
        return tiny;
    },
    defaultIcon: function(number) {
        if(!number) {
            number = 13;
        }
        var tiny = new GIcon();

        if(gMapController.container[number].stars != '') {
            tiny.image = "/images/icons/maps/" + this.defaultTypes[gMapController.container[number].type + '_' + gMapController.container[number].stars];
        }
        else {
            tiny.image = "/images/icons/maps/" + this.defaultTypes[gMapController.container[number].type];
        }
        tiny.shadow = "/images/icons/maps/normal_shadow.png";
        tiny.iconSize = new GSize(27, 31);
        tiny.iconShadowSize = new GSize(45, 31);
        tiny.infoWindowAnchor = new GPoint(27, 31);
        tiny.iconAnchor = new GPoint(14, 31);
        return tiny;
    },
    cityMarker: function(latLng, number, text) {
        var icon = new GIcon();
        if(gMapController.lang == 'cz') {
            icon.image = "/images/icons/maps/nabidek_red.png";
        }
        else if (gMapController.lang == 'en') {
            icon.image = "/images/icons/maps/offers_red.png";
        }
        else {
            icon.image = "/images/icons/maps/hotels_red.png";
        }

        icon.shadow = "/images/icons/maps/normal_shadow.png";
        icon.iconSize = new GSize(27, 31);
        icon.iconShadowSize = new GSize(45,31);
        icon.iconAnchor = new GPoint(14,31);
        icon.infoWindowAnchor = new GPoint(27, 31);

        opts = {
          "icon": icon,
          /*"zIndexProcess": this.zIndexCity,*/
          "clickable": true,
          "labelText": gMapController.container[number].hotels,
          "labelClass": 'cityMarker',
          "labelOffset": new GSize(-14, -20)
        };
        var marker = new LabeledMarker(latLng, opts);

        GEvent.addListener(marker, "click", function() {
            gMapController.map.panTo(latLng);
            this.openInfoWindowHtml(text);
        });

        return marker;

    },
    zIndexCity: function(marker, b) {
        return -281251;
    },
    countryMarker: function(latLng, number, text) {
        var icon = new GIcon();
        if(gMapController.lang == 'cz') {
            icon.image = "/images/icons/maps/nabidek_big_orange.png";
        }
        else if(gMapController.lang == 'en') {
            icon.image = "/images/icons/maps/offers_big_orange.png";
        }
        else {
            icon.image = "/images/icons/maps/hotels_big_orange.png";
        }

        icon.shadow = "/images/icons/maps/specials-shadow.png";
        icon.iconSize = new GSize(39, 33);
        icon.iconShadowSize = new GSize(57,33);
        icon.iconAnchor = new GPoint(15,33);
        icon.infoWindowAnchor = new GPoint(39, 33);

        opts = {
          "icon": icon,
          "clickable": true,
          "labelText": gMapController.container[number].hotels,
          "labelClass": 'countryMarker',
          "labelOffset": new GSize(-15, -22)
        };
        var marker = new LabeledMarker(latLng, opts);

        GEvent.addListener(marker, "click", function() {
            gMapController.map.panTo(latLng);
            this.openInfoWindowHtml(text);
        });

        return marker;

    },
    continentMarker: function(latLng, number, text) {
        var icon = new GIcon();
        if(gMapController.lang == 'cz') {
            icon.image = "/images/icons/maps/nabidek_big_orange.png";
        }
        else if(gMapController.lang == 'en') {
            icon.image = "/images/icons/maps/offers_big_orange.png";
        }
        else {
            icon.image = "/images/icons/maps/hotels_big_orange.png";
        }

        icon.shadow = "/images/icons/maps/specials-shadow.png";
        icon.iconSize = new GSize(39, 33);
        icon.iconShadowSize = new GSize(57,33);
        icon.iconAnchor = new GPoint(15,33);
        icon.infoWindowAnchor = new GPoint(39, 33);

        opts = {
          "icon": icon,
          "clickable": true,
          "labelText": gMapController.container[number].hotels,
          "labelClass": 'countryMarker',
          "labelOffset": new GSize(-15, -22)
        };
        var marker = new LabeledMarker(latLng, opts);

        GEvent.addListener(marker, "click", function() {
            gMapController.map.panTo(latLng);
            this.openInfoWindowHtml(text);
        });

        return marker;

    },
    load: function() {
       if (GBrowserIsCompatible()) {
            if (this.init()) {
                // odposlouchavame na udalost pohyb s mapou
                GEvent.addListener(this.map, "moveend", function () {
                    gMapController.moveControl();
                });

                gMapController.setObjectsToMap();
            }
       }

    },
    init:function() {

        // jQuery syntaxi nebere
        if (this.center == false) {
            this.center = new GLatLng(this.defaultLat, this.defaultLng);
        }

        this.map = new GMap2(document.getElementById("bigmap")); // nastavime mapu do objektu X

        this.map.setCenter(this.center, this.defaultZoom); // nastavime stred mapy na X
        //this.map.addControl(new GSmallMapControl()); // ovladac na zoom a pohyb, mala varianta
        this.map.addControl(new GLargeMapControl()); // ovladac na zoom a pohyb, velka varianta
        this.map.addControl(new GMapTypeControl()); // prepinani na typy mapy
        this.map.addControl(new GScaleControl()); // meritko
        //this.map.enableScrollWheelZoom(); // zoomovani rolovatkem povolene

        return true;

    },
    hotelMarker: function (markerType, latLng, text, objID) {
        if(markerType) {
            var marker = null;

            if(gMapController.container[objID].id == gMapController.defaultHotel) {
                marker = new GMarker(latLng, {icon: gMapController.defaultIcon(objID)});
                if(gMapController.firstLoad) {
                    gMapController.map.openInfoWindowHtml(latLng, text, {maxWidth: 230} );
                    gMapController.firstLoad = false;
                }
            }
            else if(markerType == 1) {
                marker = new GMarker(latLng, {icon: gMapController.smallIcon(objID)});
            }
            else if(markerType == 2) {
                marker = new GMarker(latLng, {icon: gMapController.bigIcon(objID)});
            }

            GEvent.addListener(marker, "click", function() {
                gMapController.map.panTo(latLng);
                this.openInfoWindowHtml(text, {maxWidth: 230} );
            });

            return marker;
        }
        else {
            return false;
        }
    },
    moveControl: function() {
        //console.log(this.map.getZoom());
        /*if (gMapController.container) {
            gMapController.setObjectsToMap();
            return false;
        }*/

        coordSWMapX = this.map.getBounds().getSouthWest().lng(); // jihozapadni delka
        coordSWMapY = this.map.getBounds().getSouthWest().lat(); // jihozapadni sirka
        coordNEMapX = this.map.getBounds().getNorthEast().lng(); // severovychodni delka
        coordNEMapY = this.map.getBounds().getNorthEast().lat(); // severovychodni sirka

        if (!gMapController.map.getInfoWindow().isHidden()) {
            return false;
        }

        if (this.loading > 0) {
            this.loading = 2;
            return false;
        }
        this.loading = 1;

        //console.log($('#bigmap').offset(), 'offset');
        //console.log($('#bigmap').width(), 'width');
        //console.log($('#bigmap').height(), 'height');
        
        var pos = $('#bigmap').position();

        $('#bigmap').after('<div id="mapOverlay"></div>');
        $('#mapOverlay').css('position', 'absolute');
        //$('#mapOverlay').css('border', '1px solid red');
        $('#mapOverlay').css('z-index', '33000');
        $('#mapOverlay').css('top', pos.top+'px');
        //$('#mapOverlay').css('top', 0);
        $('#mapOverlay').css('left', pos.left+'px');
        //$('#mapOverlay').css('left', 0);

        $('#mapOverlay').css('background-color', '#fff');
        $('#mapOverlay').css('width', $('#bigmap').width()+'px');
        $('#mapOverlay').css('height', $('#bigmap').height()+'px');

        $('#mapOverlay').css('opacity', '0.5');
        $('#mapOverlay').css('filter', 'alpha(opacity=40)');

        $('#mapOverlay').after('<img src="/images/ajax-loader.gif" width="100" height="100" alt="wating bar" id="mapOverlayLoader" style="z-index:33001;position:absolute;" />');
        $('#mapOverlayLoader').css('top', parseInt((pos.top+$('#bigmap').height())/2)+'px');
        $('#mapOverlayLoader').css('left', parseInt(((pos.left+$('#bigmap').width())-50)/2)+'px');

        postData = "lng_min=" + coordSWMapX + "&lat_min=" + coordSWMapY + "&lng_max=" + coordNEMapX + "&lat_max=" + coordNEMapY + '&lang=' + gMapController.lang + "&zoom=" + this.map.getZoom();
        $.ajax({
            type: "POST",
            data: postData,
            dataType: 'json',
            url: "/ajax/getObjects.php",
            success: function (data) {
                gMapController.container = data;
                gMapController.setObjectsToMap();

                if (gMapController.loading == 2) {
                    gMapController.loading = 0;
                    gMapController.moveControl();
                } else {
                    gMapController.loading = 0;
                }

                $('#mapOverlayLoader').remove();
                $('#mapOverlay').remove();
            }
        });


    },
    setObjectsToMap: function() {
        gMapController.removeMarkers();
        gMapController.arrMarkers = {};
        gMapController.markerTypes = {};
        //gMapController.map.clearOverlays();

        for (var i in gMapController.container) {


            var latLng = new GLatLng(gMapController.container[i].latitude, gMapController.container[i].longitude);
            var text = '';

            if(typeof gMapController.arrMarkers[gMapController.container[i].type] == 'undefined') {
                gMapController.markerTypes[gMapController.container[i].type] = gMapController.container[i].type;
                gMapController.arrMarkers[gMapController.container[i].type] = [];
            }
            else {
                //gMapController.arrMarkers[gMapController.container[i].type] = [];
            }

            //-> CITY markers
            if(gMapController.container[i].type == 1000) {

                text = gMapController.getContentCity(gMapController.container[i]);
                gMapController.arrMarkers[gMapController.container[i].type].push(gMapController.cityMarker(latLng, i, text));
            }
            //-> COUNTRY markers
            else if(gMapController.container[i].type == 2000) {

                text = gMapController.getContentCountry(gMapController.container[i]);
                gMapController.arrMarkers[gMapController.container[i].type].push(gMapController.countryMarker(latLng, i, text));
            }
            //-> CONTINENT markers
            else if(gMapController.container[i].type == 3000) {

                text = gMapController.getContentContinent(gMapController.container[i]);
                gMapController.arrMarkers[gMapController.container[i].type].push(gMapController.continentMarker(latLng, i, text));
            }
            //-> HOTELS markers
            else {
                text = gMapController.getContent(gMapController.container[i]);
                gMapController.arrMarkers[gMapController.container[i].type].push(gMapController.hotelMarker(gMapController.container[i].markerType, latLng, text, i));
            }

        }

        for(n in gMapController.markerTypes) {

            if(typeof gMapController.markerManager[n] == 'undefined') {
                gMapController.markerManager[n] = new MarkerManager(gMapController.map);
            }else {
                //gMapController.markerManager[n].clearMarkers();
            }
            
            gMapController.markerManager[n].addMarkers(gMapController.arrMarkers[n], 1);
            gMapController.markerManager[n].refresh();
        }
        gMapController.container = null;
    },
    removeMarkers: function() {
        for( i in gMapController.markerManager) {
            gMapController.markerManager[i].clearMarkers();
        }
    },
    getContent: function(obj) {
        var starText = '';
        if(obj.stars > 0) {
            for(i=1;i<=obj.stars;i++) {
                starText += '<img src="/images/star.png" width="8" height="7" alt="Star" class="infoWindowsStars" />';
            }
        }

        return '<div class="infoWindowsBlock">'+
        '<div class="clearfix"><img width="16" height="11" style="float:left;margin: 0 5px 0 0;" src="/images/flags/'+ obj.countryCode.toLowerCase() +'.gif" alt="Country Flag" />'+ obj.city + ', ' + obj.countryName + '</div>' +
        '<div style="font-size: 9px;">' + obj.address + '</div>' +
        '<h4 class="infoWindowsTitle"><a href="http://' + obj.domain + '/' + obj.url + '">' + obj.name + '</a> <span class="infoWindowsStarsBlock">' + starText + '</span></h4>'+
        '<div class="infoWindowsContent clearfix"><a href="http://' + obj.domain + '/' + obj.url + '"><img src="' + obj.foto + '" width="60" height="60" class="infoWindowsFoto" /></a><p>' + obj.desc + '... <a href="http://' + obj.domain + '/' + obj.url + '">' + this.translations.more + '</a></p></div>' +
        '<div class="infoWindowsPrice">'+ this.translations.priceFrom + ' ' + obj.price + ' ' + obj.currency + '</div>' +
        '</div>';
       

    },
    getContentCity: function(obj) {

        return '<div class="infoWindowsBlock">'+
        '<div class="clearfix"><img width="16" height="11" style="float:left;margin: 0 5px 0 0;" src="/images/flags/'+ obj.countryCode.toLowerCase() +'.gif" alt="Country Flag" />' + obj.countryName + '</div>' +
        '<h4 class="infoWindowsTitle"><a href="http://' + obj.domain + '/' + '">' + obj.name + '</a> </h4>'+
        '<div class="infoWindowsContent clearfix">'+ obj.hotels + this.translations.cityWindowText + (obj.name2 ? obj.name2 : obj.name) +'<br /><a href="http://' + obj.domain + '/' + '">' + this.translations.more + '</a></div>' +
        '</div>';


    },
    getContentCountry: function(obj) {

        return '<div class="infoWindowsBlock">'+
        '<h4 class="infoWindowsTitle"><img width="16" height="11" style="float:left;vertical-align:middle;margin: 3px 5px 0 0;" src="/images/flags/'+ obj.countryCode.toLowerCase() +'.gif" alt="Country Flag" /><a href="http://' + obj.domain + '/">' + obj.name + '</a> </h4>'+
        '<div class="infoWindowsContent clearfix">'+ obj.hotels + this.translations.countryWindowText + obj.cities + this.translations.countryDestinations +'<br /><a href="http://' + obj.domain + '/' + '">' + this.translations.more + '</a></div>' +
        '</div>';


    },
    getContentContinent: function(obj) {

        return '<div class="infoWindowsBlock">'+
        '<h4 class="infoWindowsTitle"><a href="http://' + obj.domain + '/">' + obj.name + '</a> </h4>'+
        '<div class="infoWindowsContent clearfix">'+ sprintf(this.translations.continents, obj.hotels, obj.countries, (obj.name2 ? obj.name2 : obj.name)) +'<br /><a href="http://' + obj.domain + '/' + '">' + this.translations.more + '</a></div>' +
        '</div>';


    },
    searchAddress: function (address) {
      var geocoder = new GClientGeocoder();
      geocoder.getLatLng(address, function (point) {
        if (!point) {
          alert(address + ' '+ gMapController.translations.notFound + ' '+ + '.');
        }
        else {
            gMapController.map.setCenter(point, 15);
            var marker = new GMarker(point);
            gMapController.map.addOverlay(marker);
            marker.openInfoWindowHtml(address);
            GEvent.addListener(marker, "click", function() {
                marker.openInfoWindowHtml(address);
            });
        }
      });
    }
}
