var map_gmap = null;
var myLatlng = null;
var infoWindow = null;
var markerArray = [];
var infowindows = [];

function resizeLargeMap() {
    var h = $('.large-map .modal-header').height() + 31;
    var f = $('.large-map .modal-footer').height() + 31;
    var b = $('.large-map .modal-body').height();
    var wh = $(window).height();
    var bb = wh - (f + h);

    var $topnav = $('#main-container > .topnav');
    var tn = $topnav.height();
    var tn_visible = $topnav && $topnav.is(':visible');
    var pad = 30;
    if(tn_visible) {
        wh = wh - tn;
        bb = wh - (f + h);
        $('.modal.large-map').css('top', tn + 'px');
        pad = 0;
    }
    else {
        $('.modal.large-map').css('top', '0px');
        pad = 30;
    }


    $('.large-map .bootstrap-dialog-message').css('height', bb-pad + 'px');
    $('.large-map .bootstrap-dialog-body').css('height', bb-pad + 'px');
    $('.large-map .modal-body').css('height', bb + 'px');
    $('.large-map  .modal-dialog').css('height', wh + 'px');
}

function openDirections(loc_id) {
    BootstrapDialog.show({
        title: 'Get Map Directions',
        cssClass: 'large-map',
        message: function(dialog){
            var $frm = $('<iframe id="process_frm" name="process_frm"></iframe>');
            $frm.attr('src', full_uri + '/amodules/adverts_map/map_directions.php?location_id=' + loc_id);
            $frm.attr('width', '100%');
            $frm.attr('height', '100%');
            $frm.css('border', '0px solid #000000');
            $frm.css('overflow-y', 'hidden');
            return $frm;
        },
        buttons: [
            {
                label: 'Close',
                cssClass: 'btn btn-danger btn-sm',
                action: function(dlg) {
                    dlg.close();
                }
            }
        ],
        onshown: function(dialog) {
            $('.scrollup').addClass('hidden');
            resizeLargeMap();
        },
        onhide:function(dialog) {
            $('.scrollup').removeClass('hidden');
        }
    });

}

$(window).on('resize', function(e){
    resizeLargeMap();
});


function openBigMap(loc_id) {
    BootstrapDialog.show({
        title: big_map_title,
        cssClass: 'large-map',
        message: function(dialog){
            var $frm = $('<iframe id="process_frm" name="process_frm"></iframe>');
            $frm.attr('src', full_uri + '/amodules/adverts_map/map_enlarge.php?location_id=' + loc_id);
            $frm.attr('width', '100%');
            $frm.attr('height', '100%');
            $frm.css('border', '0px solid #000000');
            $frm.css('overflow-y', 'hidden');
            return $frm;
        },
        buttons: [
            {
                label: 'Close',
                cssClass: 'btn btn-danger btn-sm',
                action: function(dlg) {
                    dlg.close();
                }
            }
        ],
        onshown: function(dialog) {
            $('.scrollup').addClass('hidden');
            resizeLargeMap();
        },
        onhide:function(dialog) {
            $('.scrollup').removeClass('hidden');
        }
    });

}


function init_gmap(lat, lng, zoom) {

    myLatlng = new google.maps.LatLng(lat * 1, lng * 1);
    var myOptions = {
        zoom: zoom * 1 - 1,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        scrollwheel: false
    };
    map_gmap = new google.maps.Map(document.getElementById("gmap_canvas"), myOptions);


    // Creating a marker and positioning it on the map
    var marker = new google.maps.Marker({
        position: myLatlng,
        map: map_gmap
    });

    markerArray.push(marker);

    google.maps.event.trigger(map_gmap, 'resize');
    map_gmap.setZoom( map_gmap.getZoom() );
    //AutoCenter();
}

function AutoCenter() {
    //  Create a new viewpoint bound
    var bounds = new google.maps.LatLngBounds();
    //  Go through each...
    $.each(markerArray, function (index, marker) {
        bounds.extend(marker.position);
    });
    //  Fit these bounds to the map
    map_gmap.fitBounds(bounds);
}



function resizeMap(){
    google.maps.event.trigger(map_gmap, "resize");
    map_gmap.setCenter(myLatlng);
}

function init_gmap_null() {
    return true;
}


function appendBootstrap() {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyDxpjfVxlLazmPt1gkiw_wIy55ofWAUJvY&sensor=false&callback=init_gmap_null&language=en&region=CY";
    //document.body.appendChild(script);
    $('head').append(script);
}

function makeMarker(options, info_content){
    var pushPin = new google.maps.Marker({map:map_gmap});
    pushPin.setOptions(options);
    markerArray.push(pushPin);
    google.maps.event.addListener(pushPin, 'click', function(){
        var infowindow = new google.maps.InfoWindow({
            content: info_content
        });

        infowindows.push(infowindow);
        infowindow.open(map_gmap, pushPin);
    });


    return pushPin;
}

function showMarker(i){
    google.maps.event.trigger(markerArray[i], 'click');
}

function open_popup(url, win, specs) {
    var new_win = window.open(url, win, specs + "menubar=no,location=no,resizable=yes,scrollbars=yes,status=yes");
}

$(document).ready(function(){

    $(".fancyvideo").fancybox({
        maxWidth	: 800,
        maxHeight	: 600,
        fitToView	: false,
        width		: '70%',
        height		: '70%',
        autoSize	: false,
        closeClick	: false,
        openEffect	: 'none',
        closeEffect	: 'none'
    });

    /*
     $('#business_gallery').galleryView({
     enable_overlays: true,
     overlay_position: 'top',
     panel_width: 400,
     panel_height: 300,
     frame_width: 60,
     frame_height: 60,
     show_infobar: true,	//BOOLEAN - flag to show or hide infobar
     infobar_opacity: 1,
     show_captions: false //BOOLEAN - flag to show or hide frame captions
     });
     */

    Galleria.loadTheme(window.full_uri + 'assets/plugins/galleria/themes/cyprusnet/galleria.cyprusnet.js');
    Galleria.run('#business_gallery', {
        lightbox: true,
        imageCrop: true,
        idleTime: 3000,
        swipe: 'auto'
    });



    $('.click-link').each(function(){
        var sub_content = '<a href="' + click_link + '" target="_blank">' + $(this).html() + '</a>';
        $(this).replaceWith(sub_content);
    });

    //appendBootstrap();

    $('a.mailto').each(function(){
        var email = $(this).attr('rel');
        email = email.replace('[ at ]', '@');
        $(this).attr('href', 'mailto:' + email);
    });

    $('.email-str').each(function(){
        var email = $(this).html();
        email = email.replace('[ at ]', '@');
        $(this).html(email);
    });


    $('.map_directions_link').on('click', function(e){
        e.preventDefault();
        var loc_id = $(this).attr('rel');
        openDirections(loc_id);
        return false;
    });

    $('.map_enlarge_link').on('click', function(e){
        e.preventDefault();
        var loc_id = $(this).attr('rel');
        openBigMap(loc_id);
        return false;
    });

    /*$('a.click-count').each(function(i){
     var field = "cc";
     var href = $(this).attr('href');
     var cc_type = -1;


     if(href.indexOf('?' + field + '=') != -1) {
     cc_type = 1;
     }
     else if(href.indexOf('&' + field + '=') != -1) {
     cc_type = 2;
     }
     else if(href.indexOf('?') != -1) {
     cc_type = 0;
     $(this).attr('href', href + '&cc=1');
     }
     else {
     cc_type = -1;
     $(this).attr('href', href + '?cc=1');
     }
     });*/


    $('#datetimepicker-1').datetimepicker({
        format: 'DD/MM/YYYY'
    });
    $('#datetimepicker-2').datetimepicker({
        format: 'DD/MM/YYYY',
        useCurrent: false //Important! See issue #1075
    });
    $("#datetimepicker-1").on("dp.change", function (e) {
        $('#datetimepicker-2').data("DateTimePicker").minDate(e.date);
    });
    $("#datetimepicker-2").on("dp.change", function (e) {
        $('#datetimepicker-1').data("DateTimePicker").maxDate(e.date);
    });

    // Dates
    /*$( "#checkin" ).datepicker({
        minDate: minDate,
        changeMonth: true,
        numberOfMonths: 2,
        dateFormat: 'dd/mm/yy',
        onClose: function( selectedDate, dtp ) {
            $("#checkin, #checkout").css({'z-index': '1'});
        },
        onSelect: function( selectedDate, dtp ) {
            $(this).css({'z-index': '9999'});
            var curDate = $(this).datepicker( "getDate" );
            var chekout_min_date = new Date();
            var chekout_max_date = new Date();
            chekout_min_date.setTime(curDate.getTime()+ 1 * 24 * 60 * 60 * 1000);
            chekout_max_date.setTime(curDate.getTime()+ 28 * 24 * 60 * 60 * 1000);

            setTimeout(function(){
                $( "#checkout" ).datepicker("show");
            }, 16);

            $( "#checkout" ).datepicker( "option", "minDate", chekout_min_date );
            $( "#checkout" ).datepicker( "option", "maxDate", chekout_max_date );
        }
    });
    $( "#checkout" ).datepicker({
        minDate: min_checkout_date,
        maxDate: max_checkout_date,
        changeMonth: true,
        numberOfMonths: 2,
        dateFormat: 'dd/mm/yy',
        onClose: function( selectedDate, dtp ) {
            $("#checkin, #checkout" ).css({'z-index': '1'});
        },
        onSelect: function( selectedDate, dtp ) {
            $(this).css({'z-index': '9999'});
        }
    });*/

    $('#ui-datepicker-div').wrap('<div class="booking-form"></div>');


    // Check prices on Affiliate
    $('#check-prices').on('click', function(){

        var $frm = $('#booking-form');
        var num_win = $('input.aff_chk:checked').length;
        if(num_win > 0) {

            var win_width = Math.floor($(window).width() / num_win);
            var win_height = $(window).height();

            $('input.aff_chk').each(function(index){
                var open_left = index * win_width;
                if(index > 0) open_left += 10;
                $.ajax({
                    url: window.full_uri + 'amodules/client_stand/aff/aff_jump.php',
                    data: $frm.serialize() + '&current_affiliate=' + $(this).val() + '&act=check-prices',
                    async: true,
                    cache: false,
                    dataType: 'json',
                    type: 'post',
                    success: function(r) {
                        console.log(r);
                        if(r != null) {
                            $.each(r, function(win, url){
                                open_popup(url, win, 'left=' + open_left + ',width=' + win_width + ',height=' + win_height + ',top=0,');
                            });
                        }
                    }
                });
            });
        }
    });

    $('.check-prices').each(function(){
        $(this).on('click', function(){

            var $frm = $('#booking-form');
            var hotel_data = $(this).attr('rel');
            $.ajax({
                url: window.full_uri + 'amodules/client_stand/aff/aff_jump.php',
                data: $frm.serialize() + '&current_affiliate=' + hotel_data + '&act=check-prices',
                async: false,
                cache: false,
                dataType: 'json',
                type: 'post',
                success: function(r) {

                    if(r != null) {
                        open_popup(r.url, r.affiliate, 'left=' + 20 + ',width=' + ($(window).width() -40) + ',height=' + ($(window).height() - 40) + ',top=20,');
                        /*
                         $.each(r, function(win, url){

                         });
                         */
                    }
                }
            });

        });
    });



    // Find other Affiliate hotels
    $('#find-hotels').on('click', function(){

        var $frm = $('#booking-form');
        var num_win = $('input.aff_chk').length;
        if(num_win > 0) {

            var win_width = Math.floor($(window).width() / num_win);
            var win_height = $(window).height();

            $('input.aff_chk').each(function(index){
                var open_left = index * win_width;
                if(index > 0) open_left += 10;
                $.ajax({
                    url: window.full_uri + 'amodules/client_stand/aff/aff_jump.php',
                    data: $frm.serialize() + '&current_affiliate=' + $(this).val() + '&act=find-hotels',
                    async: false,
                    cache: false,
                    dataType: 'json',
                    type: 'post',
                    success: function(r) {
                        if(r != null) {
                            $.each(r, function(win, url){
                                open_popup(url, win, 'left=' + open_left + ',width=' + win_width + ',height=' + win_height + ',top=0,');
                            });
                        }
                    }
                });
            });
        }
    });

    $('.find-hotels').each(function(){
        $(this).on('click', function(){

            var $frm = $('#booking-form');
            var hotel_data = $(this).attr('rel');
            $.ajax({
                url: window.full_uri + 'amodules/client_stand/aff/aff_jump.php',
                data: $frm.serialize() + '&current_affiliate=' + hotel_data + '&act=find-hotels',
                async: false,
                cache: false,
                dataType: 'json',
                type: 'post',
                success: function(r) {
                    if(r != null) {
                        open_popup(r.url, r.affiliate, 'left=' + 20 + ',width=' + ($(window).width() -40) + ',height=' + ($(window).height() - 40) + ',top=20,');
                    }
                }
            });
        });
    });


});