/*
 * lightbox - jQuery Plugin
 * version: 1.8.5
 *
 */
(function($) {
    "use strict";
    var autoplay, bgcolor, blocknum, blocktitle, border, core, container, content, dest, extraCss,
        framewidth, frameheight, gallItems, infinigall, items, keyNavigationDisabled, margine, numeration,
        overlayColor, overlay, title, thisgall, thenext, theprev, nextok, prevok, preloader, $preloader, navigation,
        obj, gallIndex, startouch, Wbheader, images, startY, startX, endY, endX, diff, diffX, diffY, threshold;

    $.fn.extend({
        //plugin name - wlightbox
        wlightbox: function(options) {
            var plugin = this;
            // default options
            var defaults = {
                arrowsColor: '#B6B6B6',
                autoplay: false, // same as data-autoplay
                bgcolor: '#fff',
                border: '0',
                closeBackground: '#161617',
                closeColor: "#d2d2d2",
                framewidth: '',
                frameheight: '',
                gallItems: false,
                infinigall: false,
                htmlClose: '&times;',
                htmlNext: '<span>Next</span>',
                htmlPrev: '<span>Prev</span>',
                numeration: true,
                numerationBackground: '#161617',
                numerationColor: '#d2d2d2',
                numerationPosition: 'top', // 'top' || 'bottom'
                overlayClose: true,
                overlayColor: 'rgba(23,23,23,0.85)',
                titleattr: 'data-title',
                titleBackground: '#161617',
                titleColor: '#d2d2d2',
                titlePosition: 'top', // 'top' || 'bottom'
                cb_pre_open: function() {
                    return true;
                },
                cb_post_open: function() {},
                cb_pre_close: function() {
                    return true;
                },
                cb_post_close: function() {},
                cb_post_resize: function() {},
                cb_after_nav: function() {},
                cb_content_loaded: function() {},
                cb_init: function() {}
            };

            var option = $.extend(defaults, options);
            option.cb_init(plugin);

            return this.each(function() {
                obj = $(this);

                if (obj.data('wlightbox')) {
                    return true;
                }

                plugin.WBclose = function() {
                    closeWbox();
                };
                obj.addClass('wbox-item');
                obj.data('framewidth', option.framewidth);
                obj.data('frameheight', option.frameheight);
                obj.data('border', option.border);
                obj.data('bgcolor', option.bgcolor);
                obj.data('numeration', option.numeration);
                obj.data('gallItems', option.gallItems);
                obj.data('infinigall', option.infinigall);
                obj.data('overlaycolor', option.overlayColor);
                obj.data('titleattr', option.titleattr);

                obj.data('wlightbox', true);

                obj.on('click', function(e) {

                    e.preventDefault();
                    obj = $(this);

                    // callback plugin initialization
                    var cb_pre_open = option.cb_pre_open(obj);

                    if (cb_pre_open === false) {
                        return false;
                    }

                    // methods to be used outside the plugin
                    plugin.WBnext = function() {
                        navigateGall(thenext);
                    };
                    plugin.WBprev = function() {
                        navigateGall(theprev);
                    };

                    overlayColor = obj.data('overlay') || obj.data('overlaycolor');

                    framewidth = obj.data('framewidth');
                    frameheight = obj.data('frameheight');
                    // set data-autoplay="true" for vimeo and youtube videos
                    autoplay = obj.data('autoplay') || option.autoplay;
                    border = obj.data('border');
                    bgcolor = obj.data('bgcolor');
                    nextok = false;
                    prevok = false;
                    keyNavigationDisabled = false;

                    // set a different url to be loaded using data-href=""
                    dest = obj.data('href') || obj.attr('href');
                    extraCss = obj.data('css') || '';
                    title = obj.attr(obj.data('titleattr')) || '';

                    preloader = '<div class="wbox-preloader"></div>';

                    navigation = '<a class="wbox-next">' + option.htmlNext + '</a><a class="wbox-prev">' + option.htmlPrev + '</a>';
                    Wbheader = '<div class="wbox-title"></div><div class="wbox-num">0/0</div><div class="wbox-close">' + option.htmlClose + '</div>';

                    core = '<div class="wbox-overlay ' + extraCss + '" style="background:' + overlayColor + '">' +
                        preloader + '<div class="wbox-container"><div class="wbox-content"></div></div>' + Wbheader + navigation + '</div>';

                    $('body').append(core).addClass('wbox-open');

                    overlay = $('.wbox-overlay');
                    container = $('.wbox-container');
                    content = $('.wbox-content');
                    blocknum = $('.wbox-num');
                    blocktitle = $('.wbox-title');
                    $preloader = $('.wbox-preloader');

                    $preloader.show();

                    blocktitle.css(option.titlePosition, '-1px');
                    blocktitle.css({
                        'color': option.titleColor,
                        'background-color': option.titleBackground
                    });

                    $('.wbox-close').css({
                        'color': option.closeColor,
                        'background-color': option.closeBackground
                    });

                    $('.wbox-num').css(option.numerationPosition, '-1px');
                    $('.wbox-num').css({
                        'color': option.numerationColor,
                        'background-color': option.numerationBackground
                    });

                    $('.wbox-next span, .wbox-prev span').css({
                        'border-top-color': option.arrowsColor,
                        'border-right-color': option.arrowsColor
                    });

                    content.html('');
                    content.css('opacity', '0');
                    overlay.css('opacity', '0');

                    checknav();

                    // fade in overlay
                    overlay.animate({
                        opacity: 1
                    }, 250, function() {

                        if (obj.data('wbox') === 'iframe') {
                            loadIframe();
                        } else if (obj.data('wbox') === 'inline') {
                            loadInline();
                        } else if (obj.data('wbox') === 'ajax') {
                            loadAjax();
                        } else if (obj.data('wbox') === 'video') {
                            loadVid(autoplay);
                        } else {
                            content.html('<img src="' + dest + '">');
                            preloadFirst();
                        }
                        option.cb_post_open(obj, gallIndex, thenext, theprev);
                    });

                    /* -------- KEYBOARD ACTIONS -------- */
                    $('body').keydown(keyboardHandler);

                    /* -------- PREVGALL -------- */
                    $('.wbox-prev').on('click', function() {
                        navigateGall(theprev);
                    });
                    /* -------- NEXTGALL -------- */
                    $('.wbox-next').on('click', function() {
                        navigateGall(thenext);
                    });

                    return false;

                }); // click

                /* -------- CHECK NEXT / PREV -------- */
                function checknav() {

                    thisgall = obj.data('gallery');
                    numeration = obj.data('numeration');
                    gallItems = obj.data('gallItems');
                    infinigall = obj.data('infinigall');

                    if (gallItems) {
                        items = gallItems;
                    } else {
                        items = $('.wbox-item[data-gallery="' + thisgall + '"]');
                    }

                    thenext = items.eq(items.index(obj) + 1);
                    theprev = items.eq(items.index(obj) - 1);

                    if (!thenext.length && infinigall === true) {
                        thenext = items.eq(0);
                    }

                    // update gall numeration
                    if (items.length > 1) {
                        gallIndex = items.index(obj) + 1;
                        blocknum.html(gallIndex + ' / ' + items.length);
                    } else {
                        gallIndex = 1;
                    }
                    if (numeration === true) {
                        blocknum.show();
                    } else {
                        blocknum.hide();
                    }

                    // update title
                    if (title !== '') {
                        blocktitle.show();
                    } else {
                        blocktitle.hide();
                    }

                    // update navigation arrows
                    if (!thenext.length && infinigall !== true) {
                        $('.wbox-next').css('display', 'none');
                        nextok = false;
                    } else {
                        $('.wbox-next').css('display', 'block');
                        nextok = true;
                    }

                    if (items.index(obj) > 0 || infinigall === true) {
                        $('.wbox-prev').css('display', 'block');
                        prevok = true;
                    } else {
                        $('.wbox-prev').css('display', 'none');
                        prevok = false;
                    }
                    // activate swipe
                    if (prevok === true || nextok === true) {
                        content.on(TouchMouseEvent.DOWN, onDownEvent);
                        content.on(TouchMouseEvent.MOVE, onMoveEvent);
                        content.on(TouchMouseEvent.UP, onUpEvent);
                    }
                }

                /* -------- gallery navigation -------- */
                function navigateGall(destination) {

                    if (destination.length < 1) {
                        return false;
                    }
                    if (keyNavigationDisabled) {
                        return false;
                    }
                    keyNavigationDisabled = true;

                    overlayColor = destination.data('overlay') || destination.data('overlaycolor');

                    framewidth = destination.data('framewidth');
                    frameheight = destination.data('frameheight');
                    border = destination.data('border');
                    bgcolor = destination.data('bgcolor');
                    dest = destination.data('href') || destination.attr('href');

                    autoplay = destination.data('autoplay');

                    title = destination.attr(destination.data('titleattr')) || '';

                    // swipe out item
                    if (destination === theprev) {
                        content.addClass('animated').addClass('swipe-right');
                    }
                    if (destination === thenext) {
                        content.addClass('animated').addClass('swipe-left');
                    }

                    $preloader.show();

                    content.animate({
                        opacity: 0,
                    }, 500, function() {

                        overlay.css('background', overlayColor);

                        content
                            .removeClass('animated')
                            .removeClass('swipe-left')
                            .removeClass('swipe-right')
                            .css({
                                'margin-left': 0,
                                'margin-right': 0
                            });

                        if (destination.data('wbox') === 'iframe') {
                            loadIframe();
                        } else if (destination.data('wbox') === 'inline') {
                            loadInline();
                        } else if (destination.data('wbox') === 'ajax') {
                            loadAjax();
                        } else if (destination.data('wbox') === 'video') {
                            loadVid(autoplay);
                        } else {
                            content.html('<img src="' + dest + '">');
                            preloadFirst();
                        }
                        obj = destination;
                        checknav();
                        keyNavigationDisabled = false;
                        option.cb_after_nav(obj, gallIndex, thenext, theprev);
                    });
                }

                /* -------- KEYBOARD HANDLER -------- */
                function keyboardHandler(e) {
                    if (e.keyCode === 27) { // esc
                        closeWbox();
                    }

                    if (e.keyCode === 37 && prevok === true) { // left
                        navigateGall(theprev);
                    }

                    if (e.keyCode === 39 && nextok === true) { // right
                        navigateGall(thenext);
                    }
                }

                /* -------- CLOSE VBOX -------- */
                function closeWbox() {

                    var cb_pre_close = option.cb_pre_close(obj, gallIndex, thenext, theprev);

                    if (cb_pre_close === false) {
                        return false;
                    }

                    $('body').off('keydown', keyboardHandler).removeClass('wbox-open');

                    obj.focus();

                    overlay.animate({
                        opacity: 0
                    }, 500, function() {
                        overlay.remove();
                        keyNavigationDisabled = false;
                        option.cb_post_close();
                    });
                }

                /* -------- CLOSE CLICK -------- */
                var closeclickclass = '.wbox-overlay';
                if (!option.overlayClose) {
                    closeclickclass = '.wbox-close'; // close only on X
                }

                $('body').on('click touchstart', closeclickclass, function(e) {
                    if ($(e.target).is('.wbox-overlay') ||
                        $(e.target).is('.wbox-content') ||
                        $(e.target).is('.wbox-close') ||
                        $(e.target).is('.wbox-preloader') ||
                        $(e.target).is('.wbox-container')
                    ) {
                        closeWbox();
                    }
                });

                startX = 0;
                endX = 0;

                diff = 0;
                threshold = 50;
                startouch = false;

                function onDownEvent(e) {
                    content.addClass('animated');
                    startY = endY = e.pageY;
                    startX = endX = e.pageX;
                    startouch = true;
                }

                function onMoveEvent(e) {
                    if (startouch === true) {
                        endX = e.pageX;
                        endY = e.pageY;

                        diffX = endX - startX;
                        diffY = endY - startY;

                        var absdiffX = Math.abs(diffX);
                        var absdiffY = Math.abs(diffY);

                        if ((absdiffX > absdiffY) && (absdiffX <= 100)) {
                            e.preventDefault();
                            content.css('margin-left', diffX);
                        }
                    }
                }

                function onUpEvent() {
                    if (startouch === true) {
                        startouch = false;
                        var subject = obj;
                        var change = false;
                        diff = endX - startX;

                        if (diff < 0 && nextok === true) {
                            subject = thenext;
                            change = true;
                        }
                        if (diff > 0 && prevok === true) {
                            subject = theprev;
                            change = true;
                        }

                        if (Math.abs(diff) >= threshold && change === true) {
                            navigateGall(subject);
                        } else {
                            content.css({
                                'margin-left': 0,
                                'margin-right': 0
                            });
                        }
                    }
                }

                /* == GLOBAL DECLERATIONS == */
                var TouchMouseEvent = {
                    DOWN: "touchmousedown",
                    UP: "touchmouseup",
                    MOVE: "touchmousemove"
                };

                /* == EVENT LISTENERS == */
                var onMouseEvent = function(event) {
                    var type;
                    switch (event.type) {
                        case "mousedown":
                            type = TouchMouseEvent.DOWN;
                            break;
                        case "mouseup":
                            type = TouchMouseEvent.UP;
                            break;
                        case "mouseout":
                            type = TouchMouseEvent.UP;
                            break;
                        case "mousemove":
                            type = TouchMouseEvent.MOVE;
                            break;
                        default:
                            return;
                    }
                    var touchMouseEvent = normalizeEvent(type, event, event.pageX, event.pageY);
                    $(event.target).trigger(touchMouseEvent);
                };

                var onTouchEvent = function(event) {
                    var type;
                    switch (event.type) {
                        case "touchstart":
                            type = TouchMouseEvent.DOWN;
                            break;
                        case "touchend":
                            type = TouchMouseEvent.UP;
                            break;
                        case "touchmove":
                            type = TouchMouseEvent.MOVE;
                            break;
                        default:
                            return;
                    }

                    var touch = event.originalEvent.touches[0];
                    var touchMouseEvent;

                    if (type === TouchMouseEvent.UP) {
                        touchMouseEvent = normalizeEvent(type, event, null, null);
                    } else {
                        touchMouseEvent = normalizeEvent(type, event, touch.pageX, touch.pageY);
                    }
                    $(event.target).trigger(touchMouseEvent);
                };

                /* == NORMALIZE == */
                var normalizeEvent = function(type, original, x, y) {
                    return $.Event(type, {
                        pageX: x,
                        pageY: y,
                        originalEvent: original
                    });
                };

                /* == LISTEN TO ORIGINAL EVENT == */
                if ("ontouchstart" in window) {
                    $(document).on("touchstart", onTouchEvent);
                    $(document).on("touchmove", onTouchEvent);
                    $(document).on("touchend", onTouchEvent);
                } else {
                    $(document).on("mousedown", onMouseEvent);
                    $(document).on("mouseup", onMouseEvent);
                    $(document).on("mouseout", onMouseEvent);
                    $(document).on("mousemove", onMouseEvent);
                }

                /* -------- LOAD AJAX -------- */
                function loadAjax() {
                    $.ajax({
                        url: dest,
                        cache: false
                    }).done(function(msg) {
                        content.html('<div class="wbox-inline">' + msg + '</div>');
                        preloadFirst();

                    }).fail(function() {
                        content.html('<div class="wbox-inline"><p>Error retrieving contents, please retry</div>');
                        updateoverlay();
                    });
                }

                /* -------- LOAD IFRAME -------- */
                function loadIframe() {
                    content.html('<iframe class="wboxframe" src="' + dest + '"></iframe>');
                    updateoverlay();
                }

                /* -------- LOAD VIDEOs -------- */
                function loadVid(autoplay) {

                    var player;
                    var videoObj = parseVideo(dest);

                    // set rel=0 to hide related videos at the end of YT + optional autoplay
                    var stringAutoplay = autoplay ? "?rel=0&autoplay=1" : "?rel=0";
                    var queryvars = stringAutoplay + getUrlParameter(dest);

                    if (videoObj.type === 'vimeo') {
                        player = 'https://player.vimeo.com/video/';
                    } else if (videoObj.type === 'youtube') {
                        player = 'https://www.youtube.com/embed/';
                    }
                    content.html('<iframe class="wboxframe wbvid" webkitallowfullscreen mozallowfullscreen allowfullscreen allow="autoplay" frameborder="0" src="' + player + videoObj.id + queryvars + '"></iframe>');
                    updateoverlay();
                }

                /**
                 * Parse Youtube or Vimeo videos and get host & ID
                 */
                function parseVideo(url) {
                    url.match(/(http:|https:|)\/\/(player.|www.)?(vimeo\.com|youtu(be\.com|\.be|be\.googleapis\.com))\/(video\/|embed\/|watch\?v=|v\/)?([A-Za-z0-9._%-]*)(\&\S+)?/);
                    var type;
                    if (RegExp.$3.indexOf('youtu') > -1) {
                        type = 'youtube';
                    } else if (RegExp.$3.indexOf('vimeo') > -1) {
                        type = 'vimeo';
                    }
                    return {
                        type: type,
                        id: RegExp.$6
                    };
                }

                /**
                 * get additional video url parameters
                 */
                function getUrlParameter(name) {
                    var result = '';
                    var sPageURL = decodeURIComponent(name);
                    var firstsplit = sPageURL.split('?');

                    if (firstsplit[1] !== undefined) {
                        var sURLVariables = firstsplit[1].split('&');
                        var sParameterName;
                        var i;
                        for (i = 0; i < sURLVariables.length; i++) {
                            sParameterName = sURLVariables[i].split('=');
                            result = result + '&' + sParameterName[0] + '=' + sParameterName[1];
                        }
                    }
                    return encodeURI(result);
                }

                /* -------- LOAD INLINE -------- */
                function loadInline() {
                    content.html('<div class="wbox-inline">' + $(dest).html() + '</div>');
                    updateoverlay();
                }

                /* -------- PRELOAD IMAGE -------- */
                function preloadFirst() {
                    images = content.find('img');

                    if (images.length) {
                        images.each(function() {
                            $(this).one('load', function() {
                                updateoverlay();
                            });
                        });
                    } else {
                        updateoverlay();
                    }
                }

                /* -------- FADE-IN THE NEW CONTENT -------- */
                function updateoverlay() {

                    blocktitle.html(title);

                    content.find(">:first-child").addClass('children').css({
                        'width': framewidth,
                        'height': frameheight,
                        'padding': border,
                        'background': bgcolor
                    });

                    $('img.children').on('dragstart', function(event) {
                        event.preventDefault();
                    });

                    updateOL();

                    content.animate({
                        'opacity': '1'
                    }, 'slow', function() {
                        $preloader.hide();
                    });
                    option.cb_content_loaded(obj, gallIndex, thenext, theprev);
                }

                /* -------- CENTER FRAME -------- */
                function updateOL() {

                    var sonH = content.outerHeight();
                    var finH = $(window).height();

                    if (sonH + 60 < finH) {
                        margine = (finH - sonH) / 2;
                    } else {
                        margine = '30px';
                    }
                    content.css('margin-top', margine);
                    content.css('margin-bottom', margine);
                    option.cb_post_resize();
                }

                $(window).resize(function() {
                    if ($('.wbox-content').length) {
                        setTimeout(updateOL(), 800);
                    }
                });
            });
        }
    });
})(jQuery);