/*
 * Arcana by HTML5 UP (html5up.net | @ajlkn)
 * Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
 *
 * This file contains the theme's utility scripts (panel, polyfills, etc.)
 */

(function($) {

    /**
     * Converts a navigation menu (ul) into a flat list of links for use in a mobile panel.
     * @return {jQuery} jQuery object
     */
    $.fn.navList = function() {

        var $this = $(this),
            $a = $this.find('a'),
            b = [];

        $a.each(function() {
            var $this = $(this),
                indent = Math.max(0, $this.parents('li').length - 1),
                href = $this.attr('href'),
                target = $this.attr('target'),
                // [Modified] Get the class and 'to' attribute of the original link to open the popup.
                originalClass = $this.attr('class'),
                toAttr = $this.attr('to');

            // [Modified] Include both the default class and the original class for the mobile panel link.
            var classes = 'link depth-' + indent;
            if (typeof originalClass !== 'undefined' && originalClass != '') {
                classes += ' ' + originalClass;
            }

            b.push(
                '<a ' +
                'class="' + classes + '"' + // Apply modified classes
                ( (typeof target !== 'undefined' && target != '') ? ' target="' + target + '"' : '') +
                ( (typeof href !== 'undefined' && href != '') ? ' href="' + href + '"' : '') +
                // [Modified] Add the 'to' attribute to specify the popup target.
                ( (typeof toAttr !== 'undefined' && toAttr != '') ? ' to="' + toAttr + '"' : '') +
                '>' +
                '<span class="indent-' + indent + '"></span>' +
                $this.text() +
                '</a>'
            );
        });

        return b.join('');

    };

    /**
     * Transforms a specific element into a slide-out panel.
     * @param {object} userConfig User settings object
     * @return {jQuery} jQuery object
     */
    $.fn.panel = function(userConfig) {

        // Return if no element
        if (this.length == 0)
            return $this;

        // If multiple elements, recursively call for each
        if (this.length > 1) {
            for (var i=0; i < this.length; i++)
                $(this[i]).panel(userConfig);
            return $this;
        }

        // Set variables
        var	$this = $(this),
            $body = $('body'),
            $window = $(window),
            id = $this.attr('id'),
            config;

        // Merge default and user settings
        config = $.extend({
            delay: 0,					// Delay time
            hideOnClick: false,			// Whether to hide the panel on link click
            hideOnEscape: false,		// Whether to hide the panel on ESC key press
            hideOnSwipe: false,			// Whether to hide the panel on swipe
            resetScroll: false,			// Whether to reset scroll on hide
            resetForms: false,			// Whether to reset forms on hide
            side: null,					// Which side the panel appears on (top, bottom, left, right)
            target: $this,				// The target to which the class is applied when the panel is visible
            visibleClass: 'visible'		// The class name to apply when the panel is visible
        }, userConfig);

        // Internal function to hide the panel
        $this._hide = function(event) {
            if (!config.target.hasClass(config.visibleClass))
                return;
            if (event) {
                event.preventDefault();
                event.stopPropagation();
            }
            config.target.removeClass(config.visibleClass);
            window.setTimeout(function() {
                if (config.resetScroll)
                    $this.scrollTop(0);
                if (config.resetForms)
                    $this.find('form').each(function() {
                        this.reset();
                    });
            }, config.delay);
        };

        // CSS settings for browser compatibility
        $this
            .css('-ms-overflow-style', '-ms-autohiding-scrollbar')
            .css('-webkit-overflow-scrolling', 'touch');

        // Event handler to hide the panel on link click
        if (config.hideOnClick) {

            $this.find('a')
                .css('-webkit-tap-highlight-color', 'rgba(0,0,0,0)');

            $this
                .on('click', 'a', function(event) {

                    var $a = $(this),
                        href = $a.attr('href'),
                        target = $a.attr('target');

                    // --- ⬇️ Modified Logic Start ⬇️ ---

                    // 1. First check if it is a popup link.
                    // If the link has the 'open-login-popup' class, close the menu, and this handler's action ends here.
                    // (The action to open the popup is handled by another event handler in common.js.)
                    if ($a.hasClass('open-login-popup')) {
                        $this._hide();
                        return;
                    }

                    // 2. The existing logic for regular links (page navigation) remains unchanged.
                    if (!href || href == '#' || href == '' || href == '#' + id)
                        return;

                    // --- ⬆️ Modified Logic End ⬆️ ---

                    // Cancel original event.
                    event.preventDefault();
                    event.stopPropagation();

                    // Hide panel.
                    $this._hide();

                    // Redirect to href.
                    window.setTimeout(function() {
                        if (target == '_blank')
                            window.open(href);
                        else
                            window.location.href = href;
                    }, config.delay + 10);

                });
        }

        // Touch and swipe event handlers
        $this.on('touchstart', function(event) {
            $this.touchPosX = event.originalEvent.touches[0].pageX;
            $this.touchPosY = event.originalEvent.touches[0].pageY;
        });
        $this.on('touchmove', function(event) {
            if ($this.touchPosX === null || $this.touchPosY === null) return;
            var diffX = $this.touchPosX - event.originalEvent.touches[0].pageX,
                diffY = $this.touchPosY - event.originalEvent.touches[0].pageY,
                th = $this.outerHeight(),
                ts = ($this.get(0).scrollHeight - $this.scrollTop());

            if (config.hideOnSwipe) {
                var result = false, boundary = 20, delta = 50;
                switch (config.side) {
                    case 'left': result = (diffY < boundary && diffY > (-1 * boundary)) && (diffX > delta); break;
                    case 'right': result = (diffY < boundary && diffY > (-1 * boundary)) && (diffX < (-1 * delta)); break;
                    case 'top': result = (diffX < boundary && diffX > (-1 * boundary)) && (diffY > delta); break;
                    case 'bottom': result = (diffX < boundary && diffX > (-1 * boundary)) && (diffY < (-1 * delta)); break;
                    default: break;
                }
                if (result) {
                    $this.touchPosX = null;
                    $this.touchPosY = null;
                    $this._hide();
                    return false;
                }
            }

            if (($this.scrollTop() < 0 && diffY < 0) || (ts > (th - 2) && ts < (th + 2) && diffY > 0)) {
                event.preventDefault();
                event.stopPropagation();
            }
        });

        // Prevent events inside the panel from propagating upwards
        $this.on('click touchend touchstart touchmove', function(event) {
            event.stopPropagation();
        });

        // Hide panel on click of a link pointing to the panel ID
        $this.on('click', 'a[href="#' + id + '"]', function(event) {
            event.preventDefault();
            event.stopPropagation();
            config.target.removeClass(config.visibleClass);
        });

        // Hide panel on body click
        $body.on('click touchend', function(event) {
            $this._hide(event);
        });

        // Event handler for the link (toggle) that opens the panel
        $body.on('click', 'a[href="#' + id + '"]', function(event) {
            event.preventDefault();
            event.stopPropagation();
            config.target.toggleClass(config.visibleClass);
        });

        // Hide panel on ESC key press
        if (config.hideOnEscape) {
            $window.on('keydown', function(event) {
                if (event.keyCode == 27) $this._hide(event);
            });
        }

        return $this;
    };

    /**
     * Polyfill for the 'placeholder' attribute of input elements in older browsers.
     * @return {jQuery} jQuery object
     */
    $.fn.placeholder = function() {
        if (typeof (document.createElement('input')).placeholder != 'undefined')
            return $(this);
        if (this.length == 0) return $this;
        if (this.length > 1) {
            for (var i=0; i < this.length; i++) $(this[i]).placeholder();
            return $this;
        }
        var $this = $(this);
        $this.find('input[type=text],textarea').each(function() {
            var i = $(this);
            if (i.val() == '' || i.val() == i.attr('placeholder'))
                i.addClass('polyfill-placeholder').val(i.attr('placeholder'));
        }).on('blur', function() {
            var i = $(this);
            if (i.attr('name').match(/-polyfill-field$/)) return;
            if (i.val() == '')
                i.addClass('polyfill-placeholder').val(i.attr('placeholder'));
        }).on('focus', function() {
            var i = $(this);
            if (i.attr('name').match(/-polyfill-field$/)) return;
            if (i.val() == i.attr('placeholder'))
                i.removeClass('polyfill-placeholder').val('');
        });
        $this.find('input[type=password]').each(function() {
            var i = $(this);
            var x = $($('<div>').append(i.clone()).remove().html().replace(/type="password"/i, 'type="text"').replace(/type=password/i, 'type=text'));
            if (i.attr('id') != '') x.attr('id', i.attr('id') + '-polyfill-field');
            if (i.attr('name') != '') x.attr('name', i.attr('name') + '-polyfill-field');
            x.addClass('polyfill-placeholder').val(x.attr('placeholder')).insertAfter(i);
            if (i.val() == '') i.hide(); else x.hide();
            i.on('blur', function(event) {
                event.preventDefault();
                var x = i.parent().find('input[name=' + i.attr('name') + '-polyfill-field]');
                if (i.val() == '') { i.hide(); x.show(); }
            });
            x.on('focus', function(event) {
                event.preventDefault();
                var i = x.parent().find('input[name=' + x.attr('name').replace('-polyfill-field', '') + ']');
                x.hide();
                i.show().focus();
            }).on('keypress', function(event) {
                event.preventDefault();
                x.val('');
            });
        });
        $this.on('submit', function() {
            $this.find('input[type=text],input[type=password],textarea').each(function(event) {
                var i = $(this);
                if (i.attr('name').match(/-polyfill-field$/)) i.attr('name', '');
                if (i.val() == i.attr('placeholder')) {
                    i.removeClass('polyfill-placeholder');
                    i.val('');
                }
            });
        }).on('reset', function(event) {
            event.preventDefault();
            $this.find('select').val($('option:first').val());
            $this.find('input,textarea').each(function() {
                var i = $(this), x;
                i.removeClass('polyfill-placeholder');
                switch (this.type) {
                    case 'submit': case 'reset': break;
                    case 'password':
                        i.val(i.attr('defaultValue'));
                        x = i.parent().find('input[name=' + i.attr('name') + '-polyfill-field]');
                        if (i.val() == '') { i.hide(); x.show(); } else { i.show(); x.hide(); }
                        break;
                    case 'checkbox': case 'radio': i.attr('checked', i.attr('defaultValue')); break;
                    case 'text': case 'textarea':
                        i.val(i.attr('defaultValue'));
                        if (i.val() == '') { i.addClass('polyfill-placeholder'); i.val(i.attr('placeholder')); }
                        break;
                    default: i.val(i.attr('defaultValue')); break;
                }
            });
        });
        return $this;
    };

    /**
     * Moves elements to the front of their parent or back to their original position based on a condition.
     * (Mainly used for changing element positions in responsive layouts.)
     * @param {jQuery} $elements Elements to move
     * @param {bool} condition If true, move to the front; if false, move to the original position
     */
    $.prioritize = function($elements, condition) {
        var key = '__prioritize';
        if (typeof $elements != 'jQuery') $elements = $($elements);
        $elements.each(function() {
            var $e = $(this), $p, $parent = $e.parent();
            if ($parent.length == 0) return;
            if (!$e.data(key)) {
                if (!condition) return;
                $p = $e.prev();
                if ($p.length == 0) return;
                $e.prependTo($parent);
                $e.data(key, $p);
            } else {
                if (condition) return;
                $p = $e.data(key);
                $e.insertAfter($p);
                $e.removeData(key);
            }
        });
    };

})(jQuery);


/*
	Arcana by HTML5 UP
	html5up.net | @ajlkn
	Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
*/

(function($) {

    var	$window = $(window),
        $body = $('body');

    // Breakpoints.
    breakpoints({
        wide:      [ '1281px',  '1680px' ],
        normal:    [ '981px',   '1280px' ],
        narrow:    [ '841px',   '980px'  ],
        narrower:  [ '737px',   '840px'  ],
        mobile:    [ '481px',   '736px'  ],
        mobilep:   [ null,      '480px'  ]
    });

    // Play initial animations on page load.
    $window.on('load', function() {
        window.setTimeout(function() {
            $body.removeClass('is-preload');
        }, 100);
    });

    // Dropdowns.
    $('#nav > ul').dropotron({
        offsetY: -15,
        hoverDelay: 0,
        alignment: 'center'
    });

    // Nav.

    // Bar.
    $(
        '<div id="titleBar">' +
        '<a href="#navPanel" class="toggle"></a>' +
        '<span class="title" onclick="javascript:gotoHome()">' + $('#logo').html() + '</span>' +
        '</div>'
    )
        .appendTo($body);

    // Panel.
    $(
        '<div id="navPanel">' +
        '<nav>' +
        $('#nav').navList() +
        '</nav>' +
        '</div>'
    )
        .appendTo($body)
        .panel({
            delay: 500,
            hideOnClick: true,
            hideOnSwipe: true,
            resetScroll: true,
            resetForms: true,
            side: 'left',
            target: $body,
            visibleClass: 'navPanel-visible'
        });

})(jQuery);