(function ($) {
    var timeout;
    $(document).on('mousemove', function (event) {
        if (timeout !== undefined) {
            window.clearTimeout(timeout);
        }
        timeout = window.setTimeout(function () {
            // trigger the new event on event.target, so that it can bubble appropriately

            var e = jQuery.Event( "mousemoveend" );

            e.pageY = event.pageY;
            e.pageX = event.pageX;

            $(event.target).trigger( e );
        }, 100);
    });
}(jQuery));

if (typeof jQuery === 'undefined') {
    throw new Error('Mobfish_SASS\'s JavaScript requires jQuery');
}


var mfElement = (function($) {

    /**
     * This method will check if an element is visible
     * @param element
     * @returns {boolean}
     */
    function isVisible(element) {
        // console.log( 'isVisible', (element.offsetWidth > 0 && element.offsetHeight > 0), element.offsetWidth, element.offsetHeight );
        return (element.offsetWidth > 0 && element.offsetHeight > 0);
    }

    /**
     * This method will check if an element is in viewport
     * @param element
     * @returns {boolean}
     */
    function isInViewport(element) {

        if( $(element).length ) {
            element = element[0];

            var visible = isVisible( element );
            if( !visible ) {
                element.style.visibility = 'hidden';
                element.style.opacity = '0';
                element.style.display = 'block';
            }

            var rect = element.getBoundingClientRect();
            var html = document.documentElement;
            var inView = (
                rect.top >= 0 &&
                rect.left >= 0 &&
                rect.bottom <= (window.innerHeight || html.clientHeight) &&
                rect.right <= (window.innerWidth || html.clientWidth)
            );


            if( !visible ) {
                element.style.visibility = 'inherit';
                element.style.opacity = 'inherit';
                element.style.display = 'none';
            }

            return {
                inView: inView,
                top: rect.top >= 0,
                left: rect.left >= 0,
                bottom: rect.bottom <= (window.innerHeight || html.clientHeight),
                right: rect.right <= (window.innerWidth || html.clientWidth)
            };
        }

        return {
            inView: false
        };
    }

    /**
     * Method which tries to move a element in viewport
     * @param ele
     */
    function moveElementInViewport(ele) {

        if( !$(ele).length ) return;

        var inView = isInViewport(ele);

        if (! inView.inView ) {

            if( !inView.left || !inView.right ) {
                $(ele).css('max-width', '90vw');

                inView = isInViewport(ele);

                if( !inView.left ) {
                    $(ele).css('left', '0');
                    $(ele).css('right', 'auto');
                }

                if( !inView.right ) {
                    if( $(ele).parents('.dropdown').length > 1 ) {
                        $(ele).css('right', '100%');
                    } else {
                        $(ele).css('right', '0');
                    }

                    $(ele).css('left', 'auto');
                }
            }


            if( !inView.bottom ) {

                $(ele).css('max-height', '50vh');
                $(ele).css('overflow', 'hidden');
                $(ele).css('overflow-y', 'auto');

                inView = isInViewport(ele);
                if( !inView.bottom ) {
                    $(ele).css('bottom', '0');
                    $(ele).css('top', 'auto');
                }
            }
        }
    }


    function isDescendant(parent, child) {
        var node = child;

        while (node != null) {
            if (node === parent) {
                return true;
            }
            node = node.parentNode;
        }
        return false;
    }

    return {
        isVisible: function( element ) {
            return isVisible( element );
        },
        isInViewport: function( element ) {
            return isInViewport( element );
        },
        moveElementInViewport: function( element ) {
            return moveElementInViewport( element );
        },
        isDescendant: function( parent, child ) {
            return isDescendant( parent, child );
        }
    };

})(jQuery);

var mfUtility = (function($) {


    function guid() {
        function s4() {
            return Math.floor((1 + Math.random()) * 0x10000)
                .toString(16)
                .substring(1);
        }
        return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
    }

    return {
        guid: function() {
            return guid();
        }
    };

})(jQuery);
(function($) {

    var body = $('body');

    /**
     * Accordion
     */
    body.on('click', '.accordion .item .head', function() {
        var item = $(this).parent('.item'),
            itemBody = $( item ).children('.item-body');

        itemBody.slideToggle();
        item.toggleClass('open');
    });

    body.on('click', '.accordion .item .close-item', function() {
        var item = $(this).closest('.item'),
            itemBody = $( item ).children('.item-body');

        itemBody.slideToggle();
        item.toggleClass('open');
    });

})(jQuery);
(function ($) {

	var body = $('body');

	function addFixedProperties(dropdown, list, event) {
		var dropdownPos = $(dropdown).offset();

		dropdownPos.top = dropdownPos.top - $(window).scrollTop();

		var zIndex = 99999 + $(list).parents('.dropdown').length;

		$(list).css('position', 'fixed');
		$(list).css('z-index', zIndex);
		$(list).css('max-height', 'inherit');
		$(list).css('overflow', 'inherit');
		$(list).css('overflow-y', 'inherit');
		$(list).css('bottom', 'inherit');

		var parentList = $(list).parents('.default-list').first();
		$(parentList).css('overflow', 'visible');

		var left = $(dropdown).hasClass('outside') ? dropdownPos.left + $(dropdown).innerWidth() : dropdownPos.left;

		$( list ).css('left', left+'px');
		$( list ).css('top', dropdownPos.top+'px');


		var inView = mfElement.isInViewport(list);

		if( !inView.right ) {
			if( $(dropdown).hasClass('outside') ) {
				$( list ).css('left', (dropdownPos.left - $(list).innerWidth())+'px');
			} else {
				$( list ).css('left', (dropdownPos.left + $(dropdown).innerWidth() - $(list).innerWidth())+'px');
			}
		}

		if( !inView.bottom ) {

			$(list).css('max-height', '50vh');
			$(list).css('overflow', 'hidden');
			$(list).css('overflow-y', 'scroll');

			inView = mfElement.isInViewport(list);
			if( !inView.bottom ) {
				$(list).css('bottom', '0');
				$(list).css('top', 'auto');
			}
		}
	}

	/**
	 * DROPDOWN
	 */
	body.on('click', '.dropdown', function (e) {
		var ul = $(this).children('ul').first();

		// console.log($(this).hasClass('disabled'));
		// normal dropdown
		if (!$(this).hasClass('disabled') && !$(this).hasClass('fixed')) {
			mfElement.moveElementInViewport(ul);
			$(ul).fadeToggle('fast');

			//position fixed for overflow hidden/scroll container
		} else if (!$(this).hasClass('disabled') && $(this).hasClass('fixed')) {
			addFixedProperties(this, ul, e);
			$(ul).fadeToggle('fast');
		}
	});


	body.on('mousemove', '.dropdown', function (e) {

		var ul = $(this).children('ul').first();

		if (!$(ul).is(":visible")) {
			if (!$(this).hasClass('fixed') && !$(this).children('.dropdown-btn').first().length && !$(this).hasClass('disabled')) {
				mfElement.moveElementInViewport(ul);
				$(ul).fadeIn('fast');

				//position fixed for overflow hidden/scroll container
			} else if ($(this).hasClass('fixed') && !$(this).children('.dropdown-btn').first().length && !$(this).hasClass('disabled')) {
				addFixedProperties(this, ul, e);
				$(ul).fadeIn('fast');
			}
		}

	});

	body.on('mouseout', '.dropdown', function (event) {
		var e = event.toElement || event.relatedTarget;
		if (!mfElement.isDescendant(this, e)) {
			var ul = $(this).children('ul').first();

			$(ul).hide();
		}
	});

})(jQuery);
var mfFlashMessage = (function ($) {

	var _messages = {},
		_lastCreated,
		_activeFlash = false,
		bodyEl = 'body',
		containerEl = '#flashMessageContainer',
		messageEl = '.flashMessage';


	/**
	 * default options
	 * @type {{}}
	 */
	var _defaults = {
		template: 'fade', // fade, confirm
		delay: 5000, // (template: fade)
		status: 'info', // info, warn, error
		closeButton: 'Dismiss', // Default close text (template: fixed)
		additionalButton: false,
		message: ""
	};


	/**
	 * Create a FlashMessage and return uuid
	 *
	 * @param message FlashMessage as String
	 * @param options Obj {} will be merged with defaults (optional arg)
	 */
	function create(message, options) {
		var tmp = {};
		$.each(_defaults, function (key, value) {
			tmp[key] = value;
		});

		if (options) {
			options = jQuery.extend(tmp, options);
		} else {
			options = Object.assign({}, tmp);
		}

		if (message) {
			options.message = message;
		}

		var uuid = mfUtility.guid();
		_messages[uuid] = options;
		_lastCreated = uuid;
		// console.log('message created', uuid);
	}


	/**
	 * This function will render all flashmessages.
	 */
	function render() {
		var flashContainer;

		// Initialize the flashMessage Container
		if (!$(bodyEl + " " + containerEl).length) {
			flashContainer = $('<div id="' + containerEl.replace('#', '') + '"></div>');
			$(bodyEl).prepend(flashContainer);
		} else {
			flashContainer = $(bodyEl + ' ' + containerEl);
		}

		var timeToWait = 0;

		// Add messages to it
		$.each(_messages, function (key, value) {
			var msg = $('<div class="' + messageEl.replace('.', '') + ' card-3 card ' + value.status + '" data-uuid="' + key + '"><div class="content">' + value.message + '</div></div>');

			// console.log('status:', value.status);
			if (!$(bodyEl + ' ' + containerEl + ' [data-uuid="' + key + '"]').length) {
				if (value.template === 'fade') {
					$(flashContainer).append(msg);
					// console.log('append', key);

					setTimeout(function () {
						$(msg).show();
						// console.log('fade in', key);

						setTimeout(function () {
							clear(key);
						}, value.delay);

					}, timeToWait);

					timeToWait += value.delay + 500;

				} else if (value.template === 'confirm') {
					$(msg).addClass('confirm');
					$(msg).append('<div class="action-bar text-right"><span class="btn primary flat dismiss">' + value.closeButton + '</span></div>');
					$(flashContainer).append(msg);

					$(msg).on('click', '.dismiss', function () {
						clear(key);
					});

					// if( _activeFlash === false ) {
					//     _activeFlash = true;
					$(msg).show();
					// }
				}
			}
		});
	}


	/**
	 * Function to show the next confirm flashmessage
	 */
	function showNextConfirmFlash() {
		$(containerEl).children(messageEl).each(function () {
			if (_activeFlash === false && $(this).hasClass('confirm')) {
				$(this).show();
			}
		});
	}


	/**
	 * Method to remove a flashMessage
	 * @param uuid
	 * @param callback
	 */
	function clear(uuid, callback) {
		var message = _messages[uuid];
		// console.log('clear', uuid);

		if (message.template === 'fade') {
			$('[data-uuid="' + uuid + '"]').fadeOut(function () {
				$(this).remove();
				// console.log('element removed');
				delete _messages[uuid];
				// console.log('message deleted', _messages);
				_activeFlash = false;
				if (callback) callback();
			});
		} else {
			$('[data-uuid="' + uuid + '"]').remove();
			delete _messages[uuid];
			_activeFlash = false;
			if (callback) callback();
		}
	}


	return {
		create: function (message, options) {
			create(message, options);
			return this;
		},
		render: function (uuid) {
			render(uuid);
			return this;
		}
	};

})(jQuery);
(function($) {

    var body = $('body');

    $( body ).on('blur', 'input', function() {

        //console.log($(this));
        if( $(this).val().length !== 0 && $(this).is(':invalid')) {
            $(this).addClass('invalid');
            $(this).parent('.field-group').addClass('invalid');
        } else {
            $(this).removeClass('invalid');
            $(this).parent('.field-group').removeClass('invalid');
        }
    });

})(jQuery);
(function ($) {

    var body = $('body');

    $(body).on('click', 'input, .btn', function (e) {
        if ($(this).prop("disabled") || $(this).hasClass('disabled')) {
            e.preventDefault();
        }
    });

})(jQuery);
(function ($) {

    var body = $('body');


    /**
     * MODAL
     */
    body.on('click', '[data-modal]', function () {
        var modal = $(this).data('modal'),
            element = $( '#'+modal );

        $(document).trigger("modal_open", [element]);
        element.fadeIn();
    });


    body.on('click', '[data-close-modal]', function () {
        var modal = $(this).data('close-modal');
        $('#' + modal).fadeOut();
    });


    body.on('click', '.modal', function (event) {
        var node = event.toElement || event.relatedTarget || event.target;
        // console.log('node', node, event);
        while ($(node).length) {
            if ($(node).hasClass('modal-content')) return;
            node = $(node).parent();
            // console.log('node', node);
        }
        $(this).fadeOut();
    });


    /**
     * Escape event Tracking to close Modalsw
     * @param evt
     */
    document.onkeydown = function (evt) {
        evt = evt || window.event;
        var isEscape = false;
        if ("key" in evt) {
            isEscape = (evt.key == "Escape" || evt.key == "Esc");
        } else {
            isEscape = (evt.keyCode == 27);
        }
        if (isEscape) {
            $('.modal').fadeOut();
        }
    };


})(jQuery);
(function($) {

    var body = $('body'),
        tooltipClass = '.mfTooltip';

    function renderTooltip( element, event ) {
        var tooltipMsg = $(element).attr('tooltip'),
            tooltipShowDelay = $(element).attr('tooltipShowDelay') ? $(element).attr('tooltipShowDelay') : 0,
            toolTipPosition = $(element).attr('toolTipPosition') ? $(element).attr('toolTipPosition') : 'bottom';

        if( tooltipMsg ) {

            //remove all tooltips
            $( tooltipClass ).remove();

            var tooltipElement = $('<span class="'+tooltipClass.replace('.', '')+' '+toolTipPosition+'" style="top: '+event.pageY+'px; left:'+event.pageX+'px;">'+tooltipMsg+'</span>');

            //add new tooltip
            $( element ).append(tooltipElement);

            // console.log(event);

            var tooltipWidth    = $(tooltipElement).width(),
                tooltipHeight   = $(tooltipElement).height();

            switch(toolTipPosition) {
                case "bottom":
                    $(tooltipElement).css('top', (event.pageY + 15) + 'px');
                    $(tooltipElement).css('left', (event.pageX - tooltipWidth/2) + 'px');
                    break;
                case "top":
                    $(tooltipElement).css('top', (event.pageY - 15 - tooltipHeight) + 'px');
                    $(tooltipElement).css('left', (event.pageX - tooltipWidth/2) + 'px');
                    break;
                case "left":
                    $(tooltipElement).css('top', (event.pageY - tooltipHeight/2) + 'px');
                    $(tooltipElement).css('left', (event.pageX - tooltipWidth - 15) + 'px');
                    break;
                case "right":
                    $(tooltipElement).css('top', (event.pageY - tooltipHeight/2) + 'px');
                    $(tooltipElement).css('left', (event.pageX + 15) + 'px');
                    break;
            }


            //show it
            // $(element).css('position', 'relative');
            setTimeout(function(){
                $( tooltipClass ).fadeIn();
            }, tooltipShowDelay);
        }
    }


    function removeToolTip( element ) {
        var tooltipHideDelay = $(element).attr('tooltipHideDelay') ? $(element).attr('tooltipHideDelay') : 100;

        setTimeout(function(){
            $( tooltipClass ).fadeOut(function() {
                $(this).remove();
            });
        }, tooltipHideDelay);
    }


    body.on('mousemoveend', '[tooltip]', function(e){
        if ( !$(this).hasClass( tooltipClass.replace('.', '') ) && !$(this).children(tooltipClass).length ) {
            renderTooltip( $(this), e );
        }
    });


    body.on('mouseout', '[tooltip]', function(event){
        var e = event.toElement || event.relatedTarget;
        if (!mfElement.isDescendant(this, e)) {
            removeToolTip( $(this) );
        }
    });
})(jQuery);