"use strict";

var abb = {};

function is_touch_device() {
    return (!!('ontouchstart' in window) || !!('onmsgesturechange' in window)) && $(window).width() < 1140;
}

$.exists = function(selector) {
    return ($(selector).length > 0);
};

$.fn.hasAttr = function(name) {
    return this.attr(name) !== undefined;
};


var BrowserDetect = {
        init: function () {
            this.browser = this.searchString(this.dataBrowser) || "Other";
            this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "Unknown";
        },
        searchString: function (data) {
            for (var i = 0; i < data.length; i++) {
                var dataString = data[i].string;
                this.versionSearchString = data[i].subString;

                if (dataString.indexOf(data[i].subString) !== -1) {
                    return data[i].identity;
                }
            }
        },
        searchVersion: function (dataString) {
            var index = dataString.indexOf(this.versionSearchString);
            if (index === -1) {
                return;
            }

            var rv = dataString.indexOf("rv:");
            if (this.versionSearchString === "Trident" && rv !== -1) {
                return parseFloat(dataString.substring(rv + 3));
            } else {
                return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
            }
        },

        dataBrowser: [
            {string: navigator.userAgent, subString: "Chrome", identity: "Chrome"},
            {string: navigator.userAgent, subString: "MSIE", identity: "IE"},
            {string: navigator.userAgent, subString: "Trident", identity: "IE"},
            {string: navigator.userAgent, subString: "Firefox", identity: "Firefox"},
            {string: navigator.userAgent, subString: "Safari", identity: "Safari"},
            {string: navigator.userAgent, subString: "Opera", identity: "Opera"}
        ]
};

BrowserDetect.init();
$('html').addClass(BrowserDetect.browser).addClass(BrowserDetect.browser + BrowserDetect.version);



/* Gets IE version */
/* -------------------------------------------------------------------- */

function mk_detect_ie() {
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf('MSIE ');
    var trident = ua.indexOf('Trident/');
    if (msie > 0) {
        return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
    }
    if (trident > 0) {
        var rv = ua.indexOf('rv:');
        return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
    }
    return false;
}
var scrollY = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop, // Updated in global event handler
    global_window_width = $(window).width(),
    global_window_height = $(window).height(),
    global_admin_bar,
    global_admin_bar_height = 0;


$(window).load(function() {
    if ($.exists("#wpadminbar")) {
        global_admin_bar = $("#wpadminbar");
    }
});

if(php.hasAdminbar) {
    if($(window).width() > 782) {
        global_admin_bar_height = 32;
    } else {
        global_admin_bar_height = 46;
    }
}

function mk_update_globals() {
    global_window_width = $(window).width();
    global_window_height = $(window).height();
}

window.scroll = function() {
        scrollY = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
}

abb.fullHeight = function() {
    var $header = $('#mk-header'),
        windowHeight = $(window).height(),
        adminbar = global_admin_bar_height,
        totalHeight;

        var headerHeight = 0;
        if($header) headerHeight = $header.data('height');
        if($header.hasClass('transparent-header')) headerHeight = 0;
        if($header.hasClass('sticky-trigger-header')) headerHeight = $header.data('sticky-height');
        if($header.hasClass('header-structure-vertical')) headerHeight = 0;

        totalHeight = windowHeight - (adminbar + headerHeight);

        return totalHeight;
}

abb.smoothScrollTo = function(offsetTop, duration) {
    $('html, body').stop().animate({
      scrollTop: offsetTop
    }, {
      duration: duration,
      easing: "easeInOutExpo"
    });
};

//////////////////////////////////////////////////////////////////////////
//
//   Global scroll handler
//
//////////////////////////////////////////////////////////////////////////


var animationThrottle = function(toThrottle, wait) {
    var lastTick = Date.now(),
        endTimeout = null;

    return function run() {
        if(Date.now() - lastTick > wait) {
            lastTick = Date.now();
            clearTimeout(endTimeout);
            window.requestAnimationFrame(toThrottle);
        }
        else {
            clearTimeout(endTimeout);
            endTimeout = setTimeout(run, wait);
        }
    };
};


var scrollAnimations = {
    sets: [],

    init: function() {
        this.update();
        this.attachEvents();
        // console.table(this.sets);
    },

    attachEvents: function() {
        window.addEventListener('scroll', animationThrottle(
            this.play.bind(this), 0
        ));
    },

    add: function(handler) {
        this.sets.push(handler);
    },

    play: function() {
        this.update();
        this.sets.forEach( function(animationSet) {
            animationSet(scrollY);
        }.bind(this));
    },

    update: function() {
        scrollY = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
    },

};
scrollAnimations.init();


var debouncedScrollAnimations = {
    sets: [],

    init: function() {
        this.attachEvents();
    },

    attachEvents: function() {
        window.addEventListener('scroll', animationThrottle(
            this.play.bind(this), 200
        ));
    },

    add: function(handler) {
        this.sets.push(handler);
    },

    play: function() {
        this.sets.forEach( function(animationSet) {
            animationSet(scrollY);
        }.bind(this));
    },
};
debouncedScrollAnimations.init();



/* Logo placement */
/* -------------------------------------------------------------------- */

function mk_logo_middle() {
    if($.exists('#mk-header.theme-main-header.header-align-center')) {
    var $menu = $('.theme-main-header .main-navigation-ul'),
        menuItems = $menu.find('> .menu-item'),
        $logo = $menu.find('.mk-header-logo'),
        menuWidthLeftFloor = 0,
        menuWidthLeftCeil = 0,
        menuWidthRightFloor = 0,
        menuWidthRightCeil = 0,
        halfFloor = Math.floor(menuItems.length/2),
        halfCeil = Math.ceil(menuItems.length/2);

    // Left widths
    for (var i = 0; i < halfFloor; i++) {
        menuWidthLeftFloor += $(menuItems[i]).width();
    }
    for (var i = 0; i < halfCeil; i++) {
        menuWidthLeftCeil += $(menuItems[i]).width();
    }

    // Right wdths
    for (var i = halfFloor-1; i < menuItems.length; i++) {
        menuWidthRightFloor += $(menuItems[i]).width();
    }
    for (var i = halfCeil-1; i < menuItems.length; i++) {
        menuWidthRightCeil += $(menuItems[i]).width();
    }

    if( menuWidthLeftCeil >= menuWidthRightCeil) {
        $logo.clone().addClass('mk-header-logo-center').insertAfter(menuItems[halfCeil-1]);
        $logo.remove();
    } else {
        $logo.clone().addClass('mk-header-logo-center').insertAfter(menuItems[halfFloor-1]);
        $logo.remove();
    }
}
}
mk_logo_middle();

/* Marge double menu */
/* -------------------------------------------------------------------- */

function mk_double_menu() {
  "use strict";

  var $header_1 = $('.theme-main-header'),
      $header_2 = $('#theme-page .vc_row').first().find('.mk-secondary-header'),
      $stickyPadding = $('.sticky-header-padding');

  if($header_1.length && $header_2.length) {
    // Merge headers if placed one under the other
    $header_1.append($header_2);
    $header_2.removeClass('sticky-header');

    // Get heights values
    var header_1_height = $header_1.data('height'),
        header_1_sticky_height = $header_1.data('sticky-height'),
        header_2_height = $header_2.height(),
        header_2_sticky_height = $header_2.data('sticky-height');

    if(mk_header_sticky == 1) {
        var stickyPaddingVal = parseInt($stickyPadding.css('padding-top').replace('px', ''));
    }
        // Lets check what we have
        // console.log('header_1_height: ' + header_1_height);
        // console.log('header_1_sticky_height: ' + header_1_sticky_height);
        // console.log('header_2_height: ' + header_2_height);
        // console.log('header_2_sticky_height: ' + header_2_sticky_height);
        // console.log('stickyPaddingVal: ' + stickyPaddingVal);

    // Update height values of marged header
    $header_1.attr('data-height', (header_1_height + header_2_height));
    $header_1.attr('data-sticky-height', (header_1_sticky_height + header_2_sticky_height));

    // Update top padding
    $stickyPadding.css({
        'padding-top': (stickyPaddingVal + header_2_height) + 'px'
    });
  }
}
mk_double_menu();


/* Page Title Intro */
/* -------------------------------------------------------------------- */

function mk_page_title_intro() {

    "use strict";

    if (!is_touch_device()) {
        $('#mk-page-title').each(function() {
            var progressVal,
                currentPoint,
                $this = $(this),
                parentHeight = $this.outerHeight(),
                $fullHeight = $this.attr('data-fullHeight'),
                startPoint = 0,
                endPoint = $this.offset().top + parentHeight,
                effectLayer = $this.find('.mk-page-title-bg'),
                gradientLayer = $this.find('.mk-effect-gradient-layer'),
                animation = $this.attr('data-intro');

            var layout = function() {
                var $heading = $this.find('.mk-page-heading'),
                    $fullHeight = $this.attr('data-fullHeight'),
                    $header_height = 0,
                    $height = $this.attr('data-height'),
                    page_title_full_height = 0;

                if ($.exists('#mk-header.sticky-header') && !$('#mk-header').hasClass('transparent-header')) {
                    var $header_height = parseInt($('#mk-header.sticky-header').attr('data-sticky-height'));
                }

                if ($fullHeight === 'true') {
                    page_title_full_height = global_window_height - $header_height - global_admin_bar_height;
                }
                else {
                    page_title_full_height = $height;
                }

                $this.css('height', page_title_full_height);

                if ($('#mk-header').hasClass('transparent-header') && $fullHeight == 'true') {
                    var header_height = parseInt($('#mk-header').attr('data-height'));
                    var padding = parseInt($this.css('padding-top'));
                    $this.css({
                        'padding' : 0
                    });
                    $heading.css({
                        'padding-top' : (page_title_full_height/2 - $heading.height()/2)+'px'
                    });
                }
            }
            layout();

            if ($fullHeight == 'true') {
                $(window).on("debouncedresize", function() {
                    layout();
                })
            }

            if ($('#mk-header').hasClass('transparent-header') && $fullHeight != 'true' ) {
                var header_height = parseInt($('#mk-header').attr('data-height'));
                var padding = parseInt($this.css('padding-top'));
                $this.css({
                    'padding-top' : (padding + header_height)+'px'
                })
            }


            var parallaxSpeed = .7,
                zoomFactor = 1.4;

                if (animation == "parallax") {
                    var set = function() {
                        currentPoint = (startPoint + scrollY) * parallaxSpeed;
                        effectLayer.css({
                            'transform': 'translateY(' + currentPoint + 'px)'
                        });
                    }
                    set();
                    scrollAnimations.add(set);
                }

                if (animation == "parallaxZoomOut") {
                    var set = function() {
                        currentPoint = (startPoint + scrollY) * parallaxSpeed;
                        progressVal = (1 / (endPoint - startPoint) * (scrollY - startPoint));
                        var zoomCalc = zoomFactor - ((zoomFactor - 1.2) * progressVal);

                        effectLayer.css({
                            'transform': 'translateY(' + currentPoint + 'px), scale(' + zoomCalc + ')'
                        });
                    }
                    set();
                    scrollAnimations.add(set);
                }

                if (animation == "gradient") {
                    var set = function() {
                        progressVal = (1 / (endPoint - startPoint) * (scrollY - startPoint));
                        gradientLayer.css({
                            opacity: progressVal * 2
                        });
                    }
                    set();
                    scrollAnimations.add(set);
                }
        });
    }
}

/* Progress Button */
/* -------------------------------------------------------------------- */

var progressButton = {
    loader: function(form) {
        var $form = form,
            progressBar = $form.find(".mk-progress-button .mk-progress-inner"),
            buttonText = $form.find(".mk-progress-button .mk-progress-button-content"),
            progressButton = new TimelineLite();

        progressButton
            .to(progressBar, 0, {
                width: "100%",
                scaleX: 0,
                scaleY: 1
            })
            .to(buttonText, .3, {
                y: -5
            })
            .to(progressBar, 1.5, {
                scaleX: 1,
                ease: Power2.easeInOut
            }, "-=.1")
            .to(buttonText, .3, {
                y: 0
            })
            .to(progressBar, .3, {
                scaleY: 0
            });
    },

    success: function(form) {
        var $form = form,
            buttonText = $form.find(".mk-button .mk-progress-button-content, .mk-contact-button .mk-progress-button-content"),
            successIcon = $form.find(".mk-progress-button .state-success"),
            progressButtonSuccess = new TimelineLite({
                onComplete: hideSuccessMessage
            });

        progressButtonSuccess
            .to(buttonText, .3, {
                paddingRight: 20,
                ease: Power2.easeInOut
            }, "+=1")
            .to(successIcon, .3, {
                opacity: 1
            })
            .to(successIcon, 2, {
                opacity: 1
            });

        function hideSuccessMessage() {
            progressButtonSuccess.reverse()
        }
    },

    error: function(form) {
        var $form = form,
            buttonText = $form.find(".mk-button .mk-progress-button-content, .mk-contact-button .mk-progress-button-content"),
            errorIcon = $form.find(".mk-progress-button .state-error"),
            progressButtonError = new TimelineLite({
                onComplete: hideErrorMessage
            });

        progressButtonError
            .to(buttonText, .3, {
                paddingRight: 20
            }, "+=1")
            .to(errorIcon, .3, {
                opacity: 1
            })
            .to(errorIcon, 2, {
                opacity: 1
            });

        function hideErrorMessage() {
            progressButtonError.reverse()
        }
    }
}


/* Progress Button */
/* -------------------------------------------------------------------- */

function mk_fixed_footer() {
  var $this = $('#mk-footer'),
      $spacer = $('#mk-footer-fixed-spacer'),
      $footerHeight = $this.outerHeight();

  // Stick with CSS media query breakpoint to target exact screen width
  if( !window.matchMedia("(max-width: 767px)").matches ) {
      if ($this.hasClass('mk-footer-fixed')) {
        $spacer.css('height', $footerHeight);
      }
  } else {
     $spacer.css('height', 0);
  }
}

mk_fixed_footer();

$(window).on("debouncedresize", function() {
    mk_fixed_footer();
})


