//SETUP USING BELOW VARS....
var maxZoom = 5;
var svgobj;
var currentZoom;
var initialZoom;
var svg;
var stepHotspots = 7;
var seenHotspots = 0;
var currentFrame = 1;

var info_open = false;
var help_open = false;

var hotspotdata = (function() {
    var json = null;
    $.ajax({
        'async': false,
        'global': false,
        'url': "js/hotspot-info.json",
        'dataType': "json",
        'success': function (data) {
            json = data;
            loadSVGFrame('assets/frame1_slimmed.svg');
        }
    });
    return json;
})();

var step = 0;

var animatedbirds = false;
var animatedclouds = false;

// $(window).load(function() {
//     loadSVGFrame('assets/frame1_slimmed.svg');
// });

$(document).ready(function(){

    // tippy('[data-tippy-content]');

    setTimeout(function(){
        window.dispatchEvent(new Event('resize'));
    }, 500);

    swal({
      icon: 'info',
      title: 'Πλήρης Οθόνη;',
      text: 'Τι θα έλεγες να ανοίξει το αντικείμενο σε λειτουργία πλήρους οθόνης; Θα είναι περισσότερο απολαυστικό!',
      buttons: {
        confirm: {
          text: "Ναι! Τέλεια ιδέα!",
          value: true,
          visible: true,
          className: "go-fullscreen-ok",
          closeModal: true
        },
        cancel: {
          text: "Όχι...",
            value: null,
            visible: true,
            className: "go-fullscreen-cancel",
            closeModal: true,
        }
      }
    }).then(function(result) {
        if(result){
          if (screenfull.enabled) {
            screenfull.request();
          }
        }

        $('#help-button').click();
    });

    $('#fullscreen-toggle').click(function(){
       if(screenfull.isFullscreen){
           screenfull.exit();
       } else {
           if (screenfull.enabled) {
               screenfull.request();
           }
       }
    });

    $('#info-button').click(function(){
        if (!info_open && !help_open) {
            info_open = true;
            var html = '<div class="iframe-container">\n' +
              '        <div class="close-iframe"><img src="assets/close.svg" class="close-button-x"></div>\n' +
              '        <iframe src="info.html" class="info-iframe"></iframe>\n' +
              '    </div>';
            $('body').append(html);
            $('.svg-container').addClass('blurred');


            $('.close-iframe').click(function(){
               $('.iframe-container').remove();
               $('.svg-container').removeClass('blurred');
               info_open = false;
            });
        }
    });

    $('#help-button').click(function(){
        if (!info_open && !help_open) {
            help_open = true;

            var html = '<div class="iframe-container help-page">\n' +
              '        <div class="close-iframe"><img src="assets/close.svg" class="close-button-x"></div>\n' +
              '        <img class="help-container" src="assets/help.png">\n' +
              '    </div>';
            $('body').append(html);
            $('.svg-container').addClass('blurred');


            $('.close-iframe').click(function(){
               $('.iframe-container').remove();
               $('.svg-container').removeClass('blurred');
               help_open = false;
            });
        }
    });

    $('#next-button').click(function() {
        checkChangeFrame(2);
    });

});

function changeFrame(step) {
    if (step === 2) {
        stepHotspots = 6;
        seenHotspots = 0;
        currentFrame = 2;
        $('.hotspots-no').html(stepHotspots);
        $('.next-prev-buttons').html('<div id="prev-button" data-tippy-content="Προηγούμενο"><img src="assets/chevron-left.svg"></div><div id="next-button" data-tippy-content="Επόμενο"><img src="assets/chevron-right.svg"></div>');
        $('#prev-button').click(function() {
            checkChangeFrame(1);
        });
        $('#next-button').click(function() {
            checkChangeFrame(3);
        });
        loadSVGFrame('assets/frame2_slimmed.svg');
    } else if (step === 1) {
        stepHotspots = 7;
        seenHotspots = 0;
        currentFrame = 1;
        $('.hotspots-no').html(stepHotspots);
        $('.next-prev-buttons').html('<div id="next-button" data-tippy-content="Επόμενο"><img src="assets/chevron-right.svg"></div>');
        $('#next-button').click(function() {
            checkChangeFrame(2);
        });
        loadSVGFrame('assets/frame1_slimmed.svg');
    } else if (step === 3){
        window.location.href = 'ending.html';
    }

}

function loadSVGFrame(svglocation) {
    $('#svg-container').empty().removeClass('hasSVG').svg({loadURL: svglocation, onLoad: setupSVGhandlers});
}

function checkChangeFrame(step) {
    $('.hotspot-popup').remove();
    if (stepHotspots - seenHotspots > 0) {
        swal({
          icon: 'warning',
          title: 'Μήπως σου ξέφυγε κάτι;',
          text: 'Δεν έχεις εξερευνήσει όλες τις ενεργές περιοχές... Θέλεις σίγουρα να συνεχίσεις χωρίς να δεις όλες τις περιοχές; Επάνω αριστερά μπορείς να δεις πόσες περιοχές δεν έχεις εξερευνήσει.',
          buttons: {
            confirm: {
              text: "Όχι, Θα ψάξω καλύτερα...",
              value: 0,
              visible: true,
              className: "alert-see-hotspots",
              closeModal: true
            },
            cancel: {
              text: "Ναι, θέλω να συνεχίσω!",
                value: 1,
                visible: true,
                className: "alert-move-next",
                closeModal: true,
            }
          }
        }).then(function(result) {

            setTimeout(function(){
                $('#hotspots-info').addClass('animated tada');
            },200);
            setTimeout(function(){
                $('#hotspots-info').removeClass('animated tada');
            }, 2000);

            if(result === 1){
                changeFrame(step);
            }
        });
    } else {
        changeFrame(step);
    }
}

function showHotspotInfo(element){
    var image = '<div style="padding-top: 20px;"></div>';
    var hasimage = hotspotdata[element].image !== undefined && hotspotdata[element].image !== '';

    if (hasimage){
        var imagename = hotspotdata[element].image;
        // image = '<img class="top-image" src="images/'+hotspotdata[element].image+'"/>';
        image = ''+
        '<div class="col-lg-6">' +
        '    <a class="popup-image-link" href="images/' + imagename + '.jpg" data-lightbox="' + imagename + '">' +
        '       <img class="popup-image" src="images/' + imagename + '-small.jpg" alt="' + imagename + '" />' +
        '       <div class="zoom-text">μεγέθυνση εικόνας</div>' +
        '    </a>' +
        '</div>';
    }

    var spanning = '';

    if (hasimage) {
      spanning = 'col-lg-6';
    } else {
      spanning = 'col-lg-12';
    }

    var text = hotspotdata[element].text;
    var title = hotspotdata[element].title;

    var hotspotInfo = ''+
    '<div class="hotspot-popup">'+
    '   <div class="close-popup">'+
    '       <img src="assets/close.svg" class="close-button-x">'+
    '   </div>' +
    '   <div class="row">' + image +
    '      <div class="' + spanning + ' text">' +
    '          <div class="popup-title">' + title + '</div><hr>' +
    '          <p>' + text + '</p>' +
    '      </div>' +
    '   </div>' +
    '</div>';

    $('body').append(hotspotInfo);
    $('.close-popup').click(function(){
        $('.hotspot-popup').remove();
        if (seenHotspots - stepHotspots === 0) {
            if (currentFrame === 1) {
                swal({
                  icon: 'success',
                  title: 'Τέλεια! Έχεις εξερευνήσει όλες τις ενεργές περιοχές!',
                  text: 'Θέλεις να συνεχίσεις και στην επόμενη σελίδα για να εξερευνήσεις περισσότερες ενεργές περιοχές;',
                  buttons: {
                    confirm: {
                      text: "Όχι, Θα μείνω σε αυτή τη σελίδα",
                      value: 0,
                      visible: true,
                      className: "alert-see-hotspots",
                      closeModal: true
                    },
                    cancel: {
                      text: "Ναι, θέλω να εξερευνήσω περισσότερα!",
                        value: 1,
                        visible: true,
                        className: "alert-move-next",
                        closeModal: true,
                    }
                  }
                }).then(function(result) {
                    if(result === 1){
                        changeFrame(2);
                    }
                });
            } else if (currentFrame === 2) {
                swal({
                  icon: 'success',
                  title: 'Τέλεια! Έχεις εξερευνήσει όλες τις ενεργές περιοχές!',
                  text: 'Έχεις δει όμως ποτέ φράγμα από κοντά;',
                  allowOutsideClick: false,
                  closeOnClickOutside: false,
                  buttons: {
                    confirm: {
                      text: "Αναζήτησε στοιχεία για ελληνικά φράγματα!",
                      value: 1,
                      visible: true,
                      className: "alert-see-hotspots",
                      closeModal: true
                    }
                  }
                }).then(function(result) {
                    if(result === 1){
                        window.location.href = 'ending.html';
                    }
                });
            }
        }

    });

}

function showHotspot(element){
    var el = $(element);
    el.attr('display','');
    if (!el.hasClass('seen')) {
        el.addClass('custom-animated infinite custom-pulse');
    } else {
        seenHotspots ++;
    }
    if (!el.hasClass('bound')){
        el.addClass('bound');
        el.click(function(){
            if (!el.hasClass('seen')){
                el.addClass('seen');
                seenHotspots ++;
            }
            el.removeClass('custom-animated infinite custom-pulse');
            $('.hotspots-no').html(stepHotspots - seenHotspots);
            showHotspotInfo(element);
        });
    }
    $('.hotspots-no').html(stepHotspots - seenHotspots);
}

function initializeFrame1TippyContent() {
    initTippyAndHotspot('g#info1');
    initTippyAndHotspot('g#info2');
    initTippyAndHotspot('g#info3');
    initTippyAndHotspot('g#info4');
    initTippyAndHotspot('g#info5');
    initTippyAndHotspot('g#info6');
    initTippyAndHotspot('g#info7');

    tippy('[data-tippy-content]');
}

function initializeFrame2TippyContent() {
    initTippyAndHotspot('g#info8');
    initTippyAndHotspot('g#info9');
    initTippyAndHotspot('g#info10');
    initTippyAndHotspot('g#info11');
    initTippyAndHotspot('g#info12');
    initTippyAndHotspot('g#info13');

    tippy('[data-tippy-content]');
}

function initTippyAndHotspot(elemID) {
    $(elemID).attr('data-tippy-content', hotspotdata[elemID].title);
    showHotspot(elemID);
}

function setupSVGhandlers(){

    // setup tippy after the svg has loaded
    if (currentFrame === 1) {
        initializeFrame1TippyContent();
    } else {
        initializeFrame2TippyContent();
    }

    $('#svgobject').attr('width','100%').attr('height', '100%');

    initializeFrameZoomPan();

    $('#svg-pan-zoom-zoom-in').on('click', function(){
        if (currentZoom < maxZoom) {
            currentZoom += 0.5;
            svgobj.zoom(currentZoom);
        }
    });
    $('#svg-pan-zoom-zoom-out').on('click', function(){
        if (currentZoom < maxZoom) {
            currentZoom -= 0.5;
            svgobj.zoom(currentZoom);
        }
    });
    $('#svg-pan-zoom-reset-pan-zoom').on('click', function(){
        currentZoom = 1;
        svgobj.reset();
    });

    $(window).resize(function(){
        svgobj.resize();
        svgobj.fit();
        svgobj.center();
    });

    svg = $('.hasSVG').svg('get');
}

function initializeFrameZoomPan(){
    //to limit the panning to always contain the graphics
    var beforePan;

    beforePan = function(oldPan, newPan){

        var stopHorizontal = false
            , stopVertical = false
            , gutterWidth = $(window).width()
            , gutterHeight = $(window).height()
            // Computed variables
            , sizes = this.getSizes()
            , leftLimit = -((sizes.viewBox.x + sizes.viewBox.width) * sizes.realZoom) + gutterWidth
            , rightLimit = sizes.width - gutterWidth - (sizes.viewBox.x * sizes.realZoom)
            , topLimit = -((sizes.viewBox.y + sizes.viewBox.height) * sizes.realZoom) + gutterHeight
            , bottomLimit = sizes.height - gutterHeight - (sizes.viewBox.y * sizes.realZoom);

        customPan = {};
        customPan.x = Math.max(leftLimit, Math.min(rightLimit, newPan.x));
        customPan.y = Math.max(topLimit, Math.min(bottomLimit, newPan.y));

        return customPan;
    };

    svgobj = svgPanZoom('#svgobject', {
        viewportSelector: '.svg-pan-zoom_viewport'
        , panEnabled: true
        , controlIconsEnabled: false
        , zoomEnabled: true
        , dblClickZoomEnabled: false
        , mouseWheelZoomEnabled: true
        , preventMouseEventsDefault: true
        , zoomScaleSensitivity: 0.2
        , minZoom: 1
        , maxZoom: maxZoom
        , fit: false
        , contain: true
        , center: true
        , refreshRate: 'auto'
        , beforePan: beforePan
//            , beforeZoom: function(){}
//            , onZoom: function(){}
//            , beforePan: function(){}
//            , onPan: function(){}
//            , onUpdatedCTM: function(){}
//            , customEventsHandler: {}
//            , eventsListenerElement: null
    });

    initialZoom = svgobj.getZoom();
    currentZoom = initialZoom;
}
