// Top Map Search
console.log('init_wb_search_map should exist');
var wb_search_map = 'large';
var markerClusterer = null;
var map = null;
var icon_styles;
var imageUrl = 'https://chart.apis.google.com/chart?cht=mm&amp;chs=24x32&amp;' + 'chco=FFFFFF,008CFF,084272&amp;ext=.png';
var cyprus_min_zoom = 8;
var info_bubble;
var js_prop_text = {
    "Hotels" 		: "Hotels"
};

var styles = [[{
    url: window.full_uri + 'amodules/wb_search_map/res/markerclusterer/m1.png',
    height: 52,
    width: 53,
    opt_anchor: [27, 10],
    textColor: '#ffffff',
    textSize: 11
}, {
    url: window.full_uri + 'amodules/wb_search_map/res/markerclusterer/m2.png',
    height: 55,
    width: 56,
    opt_anchor: [28, 28],
    textColor: '#ffffff',
    textSize: 11
}
    , {
        url: window.full_uri + 'amodules/wb_search_map/res/markerclusterer/m3.png',
        height: 65,
        width: 66,
        opt_anchor: [33, 33],
        textColor: '#ffffff',
        textSize: 12
    }
    , {
        url: window.full_uri + 'amodules/wb_search_map/res/markerclusterer/m4.png',
        height: 77,
        width: 78,
        opt_anchor: [39, 39],
        textColor: '#ffffff',
        textSize: 12
    }
    , {
        url: window.full_uri + 'amodules/wb_search_map/res/markerclusterer/m5.png',
        height: 89,
        width: 90,
        opt_anchor: [45, 45],
        textColor: '#ffffff',
        textSize: 12
    }
]];

var infowindow = null;
var info_bubble = null;

function init_wb_search_map() {

    console.log('I am in init_wb_search_map');

    //infowindow = new google.maps.InfoWindow();

    icon_styles = {
        'hotels': window.full_uri + 'amodules/wb_search_map/res/markers/icon_hotels.png'
    };


    var mapStyle = [{"featureType":"administrative","elementType":"labels.text.fill","stylers":[{"color":"#444444"}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2f2f2"}]},{"featureType":"poi","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"all","stylers":[{"saturation":-100},{"lightness":45}]},{"featureType":"road.highway","elementType":"all","stylers":[{"visibility":"simplified"}]},{"featureType":"road.arterial","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"transit","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"all","stylers":[{"color":"#46bcec"},{"visibility":"on"}]},{"featureType":"water","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"saturation":"2"},{"lightness":"-63"},{"gamma":"1.19"},{"invert_lightness":true}]}];


    var myOptions = {
        zoom: 7,
        center: new google.maps.LatLng(35.05181, 33.40537),
        styles: mapStyle,
        mapTypeControl: true,
        mapTypeControlOptions: {
            style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
        },
        zoomControl: true,
        zoomControlOptions: {
            style: google.maps.ZoomControlStyle.SMALL
        },
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        scrollwheel: false
    };


    map = new google.maps.Map(document.getElementById('cyprus_map'), myOptions);

    // Add a Snazzy Info Window to the marker
    info_bubble = new SnazzyInfoWindow({
        map: map,
        //marker: marker,
        content: '',
        closeOnMapClick: true
    });

    google.maps.event.addListener(map, 'click', function () {
        info_bubble.close();
    });

    google.maps.event.addListener(map, "zoom_changed", function () {
        //if(map.getZoom() < 8) map.setZoom(8);
        if (info_bubble.isOpen()) {
            info_bubble.close();
        }
    });


    //var refresh = document.getElementById('refresh');
    //google.maps.event.addDomListener(refresh, 'click', refresh_wb_search_map);

    //var clear = document.getElementById('clear');
    //google.maps.event.addDomListener(clear, 'click', clearClusters);

    refresh_wb_search_clusterer_map();

    if (json_locations.length > 0) {
        console.log(json_locations);
        $('#wb_search_map_container').show();
    }

}

function wb_enlarge_map(r) {
    refresh_wb_search_map();
    markerClusterer.setZoomOnClick(true);

}


function refresh_wb_search_map() {
    google.maps.event.trigger(map, "resize");
    map.setCenter(new google.maps.LatLng(35.05181, 33.40537));
    map.setZoom(8);
    refresh_wb_search_clusterer_map();
}

function mycalc(mc, st) {
    return AA;
}

function refresh_wb_search_clusterer_map() {
    if (markerClusterer != null) {
        markerClusterer.clearMarkers();
    }

    var markers = [];

    var bounds = new google.maps.LatLngBounds();
    //var markerImage = new google.maps.MarkerImage(imageUrl, new google.maps.Size(24, 32));

    for (var i = 0; i < json_locations.length; i++) {
        var adv_code = json_locations[i]['adv_code'];
        var ilat = json_locations[i].lat;
        var ilng = json_locations[i].lng;
        var latLng = new google.maps.LatLng(ilat, ilng);

        bounds.extend(latLng);

        var fm_uid = json_locations[i].fm_uid;
        var fm_name = json_locations[i].fm_name;
        var num_venues = 1;
        var icon_url = "";
        icon_url = icon_styles['hotels'];

        var marker = new google.maps.Marker({
            'position': latLng,
            'draggable': false,
            'icon': icon_url,
            'adv_code': adv_code,
            'fm_uid': fm_uid,
            'fm_name': fm_name,
            'num_venues': num_venues,
            'title': ' Click Me NOW! '
        });


        //

        loadInfoWindow(marker, info_bubble);
        markers.push(marker);


    }


    //var zoom = parseInt(document.getElementById('zoom').value, 10);
    //var size = parseInt(document.getElementById('size').value, 10);
    //var style = parseInt(document.getElementById('style').value, 10);
    //zoom = zoom == -1 ? null : zoom;
    //size = size == -1 ? null : size;
    //style = style == -1 ? null: style;
    //alert('maxZoom=' + zoom + ' ; gridSize=' + size + ' ; styles=styles[' + style + ']');
    markerClusterer = new MarkerClusterer(map, markers, {
        maxZoom: 18,//zoom,
        gridSize: 30,//size,
        zoomOnClick: true,
        styles: [{
            url: window.full_uri + 'amodules/wb_search_map/res/markerclusterer/m1.png',
            height: 52,
            width: 53,
            opt_anchor: [27, 10],
            textColor: '#ffffff',
            textSize: 11
        }, {
            url: window.full_uri + 'amodules/wb_search_map/res/markerclusterer/m2.png',
            height: 55,
            width: 56,
            opt_anchor: [28, 28],
            textColor: '#ffffff',
            textSize: 11
        }
            , {
                url: window.full_uri + 'amodules/wb_search_map/res/markerclusterer/m3.png',
                height: 65,
                width: 66,
                opt_anchor: [33, 33],
                textColor: '#ffffff',
                textSize: 12
            }
            , {
                url: window.full_uri + 'amodules/wb_search_map/res/markerclusterer/m4.png',
                height: 77,
                width: 78,
                opt_anchor: [39, 39],
                textColor: '#ffffff',
                textSize: 12
            }
            , {
                url: window.full_uri + 'amodules/wb_search_map/res/markerclusterer/m5.png',
                height: 89,
                width: 90,
                opt_anchor: [45, 45],
                textColor: '#ffffff',
                textSize: 12
            }
        ],
        calculator: function (mc, ind) {
            var nf = {};
            nf.text = 0;
            nf.index = (ind - 2 > 0) ? (ind - 2) : 0;

            for (var key in mc) {
                nf.text += mc[key].num_venues;
            }

            return nf;
        }
    });


    google.maps.event.addListener(markerClusterer, "click", function (c) {
        //wb_enlarge_map('cluster');
        //markerClusterer.setZoomOnClick(true);
        //map.setCenter(c.getCenter());
        //refresh_wb_search_clusterer_map();
    });


    map.fitBounds(bounds);
}

function loadInfoWindow(marker, info_bubble) {

    google.maps.event.addListener(marker, 'click', function () {

        if(info_bubble != null && info_bubble.isOpen()) {
            info_bubble.close();
        }
        $.ajax({
            url: window.full_uri + 'amodules/wb_search_map/ajax/getInfoWindow.php?adv_code=' + marker.adv_code+ '&domainname=' + window.domainname,
            cache: false,
            dataType: 'json',
            success: function(data){

                var closeDelayed = false;
                var closeDelayHandler = function() {
                    $(info_bubble.getWrapper()).removeClass('active');
                    setTimeout(function() {
                        closeDelayed = true;
                        info_bubble.close();
                    }, 300);
                };
                // Run JS in infowindow content
                info_bubble = new SnazzyInfoWindow({
                    marker: marker,
                    content: '',
                    closeOnMapClick: true,
                    maxWidth: 320,
                    maxHeight: 320,
                    edgeOffset: {
                        top: 20,
                        right: 20,
                        bottom: 20,
                        left: 20
                    },
                    padding: '0px',
                    closeWhenOthersOpen: true,
                    panOnOpen: true,
                    wrapperClass: 'custom-window',
                    border: false,
                    closeButtonMarkup: '<button type="button" class="custom-close">&#215;</button>',
                    callbacks: {
                        open: function() {
                            $(this.getWrapper()).addClass('open');
                        },
                        afterOpen: function() {
                            var wrapper = $(this.getWrapper());
                            wrapper.addClass('active');
                            wrapper.find('.custom-close').on('click', closeDelayHandler);
                        },
                        beforeClose: function() {
                            if (!closeDelayed) {
                                closeDelayHandler();
                                return false;
                            }
                            return true;
                        },
                        afterClose: function() {
                            var wrapper = $(this.getWrapper());
                            wrapper.find('.custom-close').off();
                            wrapper.removeClass('open');
                            closeDelayed = false;
                        }
                    }
                });
                var tmp_click_links = data.tmp_click_links;
                var $tmp_div = $('<div style="display: none;"></div>');
                $tmp_div.html(data.html);
                $('.click-link', $tmp_div).each(function () {
                    var click_link_id = $(this).attr('rel');
                    var extra_class = $(this).attr('extra_class');
                    var sub_content = '<a href="' + click_link_id + '" class="' + extra_class + '" target="_blank">' + $(this).html() + '<\/a>';
                    $(this).replaceWith(sub_content);
                });
                var ibc = $tmp_div.html();
                $tmp_div.remove();
                info_bubble.setContent(ibc);
                info_bubble.open();
            }
        });

    });
}

/***********************************************************************************************************/


init_wb_search_map();

$('#map_menu_center').on('click', function(e){
    e.preventDefault();
    refresh_wb_search_map();
    return false;
});