(function($) {
	"use strict";

    var common = {};
    qodef.modules.common = common;

    common.qodefFluidVideo = qodefFluidVideo;
    common.qodefEnableScroll = qodefEnableScroll;
    common.qodefDisableScroll = qodefDisableScroll;
    common.qodefOwlSlider = qodefOwlSlider;
    common.qodefInitParallax = qodefInitParallax;
    common.qodefInitSelfHostedVideoPlayer = qodefInitSelfHostedVideoPlayer;
    common.qodefSelfHostedVideoSize = qodefSelfHostedVideoSize;
    common.qodefPrettyPhoto = qodefPrettyPhoto;
	common.qodefStickySidebarWidget = qodefStickySidebarWidget;
    common.getLoadMoreData = getLoadMoreData;
    common.setLoadMoreAjaxData = setLoadMoreAjaxData;
    common.setFixedImageProportionSize = setFixedImageProportionSize;
    common.qodefInitPerfectScrollbar = qodefInitPerfectScrollbar;

    common.qodefOnDocumentReady = qodefOnDocumentReady;
    common.qodefOnWindowLoad = qodefOnWindowLoad;
    common.qodefOnWindowResize = qodefOnWindowResize;

    $(document).ready(qodefOnDocumentReady);
    $(window).on('load', qodefOnWindowLoad);
    $(window).resize(qodefOnWindowResize);
    
    /*
        All functions to be called on $(document).ready() should be in this function
    */
    function qodefOnDocumentReady() {
	    qodefIconWithHover().init();
        qodefIconListWithHover().init();
	    qodefDisableSmoothScrollForMac();
	    qodefInitAnchor().init();
	    qodefInitBackToTop();
        qodefBackToTopBehaviour();
	    qodefBackButtonShowHide();
	    qodefInitSelfHostedVideoPlayer();
	    qodefSelfHostedVideoSize();
	    qodefFluidVideo();
	    qodefOwlSlider();
	    qodefPreloadBackgrounds();
	    qodefPrettyPhoto();
	    qodefSearchPostTypeWidget();
	    qodefDashboardForm();
		qodefInitGridMasonryListLayout();
        qodefSmoothTransition();
        qodefRowBackgroundText();
        qodefSearchWidgetAnimation();
        qodefInitRevSliderParamsTweaks();
        qodefInitIconWithTextHover();
    }

    /*
        All functions to be called on $(window).on('load', ) should be in this function
    */
    function qodefOnWindowLoad() {
	    qodefInitParallax();
	    qodefStickySidebarWidget().init();
        qodefInitIwtBgGrid();
        qodefInitImageWithTextBgGrid();
        qodefInitProductListBgGrid();
        qodefInitClientsGridBgGrid();
		qodefInitEHBgGrid();
		qodefInitOverlayFollowHover();
    }

    /*
        All functions to be called on $(window).resize() should be in this function
    */
    function qodefOnWindowResize() {
	    qodefInitGridMasonryListLayout();
    	qodefSelfHostedVideoSize();
        qodefInitIwtBgGrid();
        qodefInitImageWithTextBgGrid();
        qodefInitProductListBgGrid();
        qodefInitClientsGridBgGrid();
        qodefInitEHBgGrid();
    }
	
	/*
	 ** Disable smooth scroll for mac if smooth scroll is enabled
	 */
	function qodefDisableSmoothScrollForMac() {
		var os = navigator.appVersion.toLowerCase();
		
		if (os.indexOf('mac') > -1 && qodef.body.hasClass('qodef-smooth-scroll')) {
			qodef.body.removeClass('qodef-smooth-scroll');
		}
	}
	
	function qodefDisableScroll() {
		if (window.addEventListener) {
			window.addEventListener('DOMMouseScroll', qodefWheel, false);
		}
		
		window.onmousewheel = document.onmousewheel = qodefWheel;
		document.onkeydown = qodefKeydown;
	}
	
	function qodefEnableScroll() {
		if (window.removeEventListener) {
			window.removeEventListener('DOMMouseScroll', qodefWheel, false);
		}
		
		window.onmousewheel = document.onmousewheel = document.onkeydown = null;
	}
	
	function qodefWheel(e) {
		qodefPreventDefaultValue(e);
	}
	
	function qodefKeydown(e) {
		var keys = [37, 38, 39, 40];
		
		for (var i = keys.length; i--;) {
			if (e.keyCode === keys[i]) {
				qodefPreventDefaultValue(e);
				return;
			}
		}
	}
	
	function qodefPreventDefaultValue(e) {
		e = e || window.event;
		if (e.preventDefault) {
			e.preventDefault();
		}
		e.returnValue = false;
	}
	
	/*
	 **	Anchor functionality
	 */
	var qodefInitAnchor = function() {
		/**
		 * Set active state on clicked anchor
		 * @param anchor, clicked anchor
		 */
		var setActiveState = function(anchor){
			var headers = $('.qodef-main-menu, .qodef-mobile-nav, .qodef-fullscreen-menu, .qodef-vertical-menu');
			
			headers.each(function(){
				var currentHeader = $(this);
				
				if (anchor.parents(currentHeader).length) {
					currentHeader.find('.qodef-active-item').removeClass('qodef-active-item');
					anchor.parent().addClass('qodef-active-item');
					
					currentHeader.find('a').removeClass('current');
					anchor.addClass('current');
				}
			});
		};
		
		/**
		 * Check anchor active state on scroll
		 */
		var checkActiveStateOnScroll = function(){
			var anchorData = $('[data-qodef-anchor]'),
				anchorElement,
				siteURL = window.location.href.split('#')[0];
			
			if (siteURL.substr(-1) !== '/') {
				siteURL += '/';
			}
			
			anchorData.waypoint( function(direction) {
				if(direction === 'down') {
					if ($(this.element).length > 0) {
						anchorElement = $(this.element).data("qodef-anchor");
					} else {
						anchorElement = $(this).data("qodef-anchor");
					}
				
					setActiveState($("a[href='"+siteURL+"#"+anchorElement+"']"));
				}
			}, { offset: '50%' });
			
			anchorData.waypoint( function(direction) {
				if(direction === 'up') {
					if ($(this.element).length > 0) {
						anchorElement = $(this.element).data("qodef-anchor");
					} else {
						anchorElement = $(this).data("qodef-anchor");
					}
					
					setActiveState($("a[href='"+siteURL+"#"+anchorElement+"']"));
				}
			}, { offset: function(){
				return -($(this.element).outerHeight() - 150);
			} });
		};
		
		/**
		 * Check anchor active state on load
		 */
		var checkActiveStateOnLoad = function(){
			var hash = window.location.hash.split('#')[1];
			
			if(hash !== "" && $('[data-qodef-anchor="'+hash+'"]').length > 0){
				anchorClickOnLoad(hash);
			}
		};
		
		/**
		 * Handle anchor on load
		 */
		var anchorClickOnLoad = function ($this) {
			var scrollAmount,
				anchor = $('.qodef-main-menu a, .qodef-mobile-nav a, .qodef-fullscreen-menu a, .qodef-vertical-menu a'),
				hash = $this,
				anchorData = hash !== '' ? $('[data-qodef-anchor="' + hash + '"]') : '';
			
			if (hash !== '' && anchorData.length > 0) {
				var anchoredElementOffset = anchorData.offset().top;
				scrollAmount = anchoredElementOffset - headerHeightToSubtract(anchoredElementOffset) - qodefGlobalVars.vars.qodefAddForAdminBar;
				
				if(anchor.length) {
					anchor.each(function(){
						var thisAnchor = $(this);
						
						if(thisAnchor.attr('href').indexOf(hash) > -1) {
							setActiveState(thisAnchor);
						}
					});
				}
				
				qodef.html.stop().animate({
					scrollTop: Math.round(scrollAmount)
				}, 1000, function () {
					//change hash tag in url
					if (history.pushState) {
						history.pushState(null, '', '#' + hash);
					}
				});
				
				return false;
			}
		};
		
		/**
		 * Calculate header height to be substract from scroll amount
		 * @param anchoredElementOffset, anchorded element offset
		 */
		var headerHeightToSubtract = function (anchoredElementOffset) {
			
			if (qodef.modules.stickyHeader.behaviour === 'qodef-sticky-header-on-scroll-down-up') {
				qodef.modules.stickyHeader.isStickyVisible = (anchoredElementOffset > qodef.modules.header.stickyAppearAmount);
			}
			
			if (qodef.modules.stickyHeader.behaviour === 'qodef-sticky-header-on-scroll-up') {
				if ((anchoredElementOffset > qodef.scroll)) {
					qodef.modules.stickyHeader.isStickyVisible = false;
				}
			}
			
			var headerHeight = qodef.modules.stickyHeader.isStickyVisible ? qodefGlobalVars.vars.qodefStickyHeaderTransparencyHeight : qodefPerPageVars.vars.qodefHeaderTransparencyHeight;
			
			if (qodef.windowWidth < 1025) {
				headerHeight = 0;
			}
			
			return headerHeight;
		};
		
		/**
		 * Handle anchor click
		 */
		var anchorClick = function () {
			qodef.document.on("click", ".qodef-main-menu a, .qodef-fullscreen-menu a, .qodef-btn, .qodef-anchor, .qodef-mobile-nav a, .qodef-vertical-menu a", function () {
				var scrollAmount,
					anchor = $(this),
					hash = anchor.prop("hash").split('#')[1],
					anchorData = hash !== '' ? $('[data-qodef-anchor="' + hash + '"]') : '';
				
				if (hash !== '' && anchorData.length > 0) {
					var anchoredElementOffset = anchorData.offset().top;
					scrollAmount = anchoredElementOffset - headerHeightToSubtract(anchoredElementOffset) - qodefGlobalVars.vars.qodefAddForAdminBar;
					
					setActiveState(anchor);
					
					qodef.html.stop().animate({
						scrollTop: Math.round(scrollAmount)
					}, 1000, function () {
						//change hash tag in url
						if (history.pushState) {
							history.pushState(null, '', '#' + hash);
						}
					});
					
					return false;
				}
			});
		};
		
		return {
			init: function () {
				if ($('[data-qodef-anchor]').length) {
					anchorClick();
					checkActiveStateOnScroll();
					
					$(window).on('load', function () {
						checkActiveStateOnLoad();
					});
				}
			}
		};
	};

	function qodefInitOverlayFollowHover(){
		var productListHolder = $('.qodef-pl-holder.qodef-grid-list.qodef-no-space.qodef-with-bg-grid');

		if (productListHolder.length) {
			var plItem = productListHolder.find('.qodef-pli');
			plItem.prepend("<span class='qodef-hover-follow-overlay'></span>");
		}

		var hoverElements = $('.qodef-iwt-boxed.qodef-iwt-transparent-hover, .qodef-clients-grid-holder .qodef-cc-item, .qodef-pl-holder.qodef-grid-list.qodef-no-space.qodef-with-bg-grid .qodef-pli, .qodef-image-with-text-holder.qodef-image-with-text-boxed');

		if(hoverElements.length){
			hoverElements.each(function(){
				var thisHoverElement = $(this);

                thisHoverElement.hoverdir({
                    hoverElem:'.qodef-hover-follow-overlay',
                    speed: 500,
                    hoverDelay: 0,
                    easing: 'easeOutExpo'
                });


			})
		}
	}
	
	function qodefInitBackToTop() {
		var backToTopButton = $('#qodef-back-to-top');
		var textWidth = $('.qodef-back-to-top-text').width();
		var buttonOfset = 40;
		backToTopButton.on('click', function (e) {
			e.preventDefault();
			qodef.html.animate({scrollTop: 0}, qodef.window.scrollTop() / 4, 'easeInOutCubic');
		});
		if(qodef.windowWidth > 1024) {
            backToTopButton.on('mouseenter', function (e) {
                $('.qodef-icon-stack').height(textWidth + buttonOfset);
            });

            backToTopButton.on('mouseleave', function (e) {
                $('.qodef-icon-stack').height('');
            });
        }
    }

    /**
     * Back to Top button behaviour
     */
    function qodefBackToTopBehaviour(){
        var btt = $('#qodef-back-to-top'),
            skinElements = $('.qodef-footer-light-btt-skin'),
            skinSet = false,
            skinTrigger = new Array();

        //Control button skin
        var bttSkin = function() {
            if (skinElements.length) {
                skinElements.each(function(i){
                    var skinElement = $(this);

                    if (qodef.scroll + btt.position().top >= skinElement.offset().top && qodef.scroll + btt.position().top <= skinElement.offset().top + skinElement.outerHeight()) {
                        skinTrigger[i] = true;
                    } else {
                        skinTrigger[i] = false;
                    }
                });

                if (jQuery.inArray(true, skinTrigger) != -1) {
                    if (!skinSet) {
                        btt.addClass('qodef-light');
                        skinSet = true;
                    }
                } else {
                    if (skinSet && !btt.hasClass('qodef-back-to-top-footer')) {
                        btt.removeClass('qodef-light');
                        skinSet = false;
                    }
                }
            }
        }

        if (btt.length && skinElements.length) {
            $(window).scroll(function() {
                bttSkin();
            });
        }
    }

	function qodefBackButtonShowHide() {
		qodef.window.scroll(function () {
			var b = $(this).scrollTop(),
				c = $(this).height(),
				d;
			
			if (b > 0) {
				d = b + c / 2;
			} else {
				d = 1;
			}
			
			if (d < 1e3) {
				qodefToTopButton('off');
			} else {
				qodefToTopButton('on');
			}
		});
	}
	
	function qodefToTopButton(a) {
		var b = $("#qodef-back-to-top");
		b.removeClass('off on');
		if (a === 'on') {
			b.addClass('on');
		} else {
			b.addClass('off');
		}
	}
	
	function qodefInitSelfHostedVideoPlayer() {
		var players = $('.qodef-self-hosted-video');
		
		if (players.length) {
			players.mediaelementplayer({
				audioWidth: '100%'
			});
		}
	}
	
	function qodefSelfHostedVideoSize(){
		var selfVideoHolder = $('.qodef-self-hosted-video-holder .qodef-video-wrap');
		
		if(selfVideoHolder.length) {
			selfVideoHolder.each(function(){
				var thisVideo = $(this),
					videoWidth = thisVideo.closest('.qodef-self-hosted-video-holder').outerWidth(),
					videoHeight = videoWidth / qodef.videoRatio;
				
				if(navigator.userAgent.match(/(Android|iPod|iPhone|iPad|IEMobile|Opera Mini)/)){
					thisVideo.parent().width(videoWidth);
					thisVideo.parent().height(videoHeight);
				}
				
				thisVideo.width(videoWidth);
				thisVideo.height(videoHeight);
				
				thisVideo.find('video, .mejs-overlay, .mejs-poster').width(videoWidth);
				thisVideo.find('video, .mejs-overlay, .mejs-poster').height(videoHeight);
			});
		}
	}
	
	function qodefFluidVideo() {
        fluidvids.init({
			selector: ['iframe'],
			players: ['www.youtube.com', 'player.vimeo.com']
		});
	}
	
	function qodefSmoothTransition() {

		if (qodef.body.hasClass('qodef-smooth-page-transitions')) {

			//check for preload animation
			if (qodef.body.hasClass('qodef-smooth-page-transitions-preloader')) {
				var loader = $('body > .qodef-smooth-transition-loader.qodef-mimic-ajax'),
					mainRevHolder = $('#qodef-main-rev-holder'),
					cevianSpinner = $('.qodef-cevian-spinner-holder'),
					hidingImagesLanding = $('.qodef-hiding-images').first();

				if (cevianSpinner.length) {
					loader.addClass('qodef-cevian-loader');

					var numberHolder = cevianSpinner.find('.qodef-cevian-spinner-number'),
						percentNumber = 0,
						numberIntervalFastest,
						windowLoaded = false;

					var animatePercent = function() {
						if(percentNumber < 100) {
							percentNumber+=1;
							numberHolder.text(percentNumber);
						}
					}
						
					var numberInterval = setInterval(function() {
						animatePercent();
						if(windowLoaded) {
							clearInterval(numberInterval);
						}
					}, 100);

					$(window).on('load', function() {
						hidingImagesLanding.removeClass('qodef-appeared');
						windowLoaded = true;
						numberIntervalFastest = setInterval(function() {
							if(percentNumber >= 100) {
								clearInterval(numberIntervalFastest);
								setTimeout(function(){
									loader.addClass('qodef-cevian-loader-ready');
									mainRevHolder.find('#rev_slider_11_3').revstart();
								}, 500);
								setTimeout(function() {
									hidingImagesLanding.addClass('qodef-appeared');
								}, 1600);
							} else {
								animatePercent();
							}
						}, 6);
					});
				}

				/**
				 * Loader Fade Out function
				 *
				 * @param {number} speed - fade out duration
				 * @param {number} delay - fade out delay
				 * @param {string} easing - fade out easing function
				 */
				var fadeOutLoader = function(speed, delay, easing) {
					speed = speed ? speed : 600;
					delay = delay ? delay : 0;
					easing = easing ? easing : 'easeOutSine';

					loader.delay(delay).fadeOut(speed, easing);
					$(window).on('bind', 'pageshow', function (event) {
						if (event.originalEvent.persisted) {
							loader.fadeOut(speed, easing);
						}
					});
				};
				
				$(window).on('load', function() {
					if (cevianSpinner.length) {
						
					} else {
						fadeOutLoader();
					}
				});
			}

			// if back button is pressed, than reload page to avoid state where content is on display:none

            window.addEventListener( "pageshow", function ( event ) {
                var historyPath = event.persisted || ( typeof window.performance != "undefined" && window.performance.navigation.type === 2 );
                if ( historyPath ) {
                    $('.qodef-wrapper-inner').show();
                }
            });

			//check for fade out animation
			if (qodef.body.hasClass('qodef-smooth-page-transitions-fadeout')) {
				var linkItem = $('a');
				
				linkItem.on('click', function (e) {
					var a = $(this);

					if ((a.parents('.qodef-shopping-cart-dropdown').length || a.parent('.product-remove').length) && a.hasClass('remove')) {
						return;
					}

					if (
						e.which === 1 && // check if the left mouse button has been pressed
						a.attr('href').indexOf(window.location.host) >= 0 && // check if the link is to the same domain
						(typeof a.data('rel') === 'undefined') && //Not pretty photo link
						(typeof a.attr('rel') === 'undefined') && //Not VC pretty photo link
                        (!a.hasClass('lightbox-active')) && //Not lightbox plugin active
						(typeof a.attr('target') === 'undefined' || a.attr('target') === '_self') && // check if the link opens in the same window
						(a.attr('href').split('#')[0] !== window.location.href.split('#')[0]) // check if it is an anchor aiming for a different page
					) {
						e.preventDefault();
						$('.qodef-wrapper-inner').fadeOut(600, 'easeOutSine', function () {
							window.location = a.attr('href');
						});
					}
				});
			}
		}
	}
	
	/*
	 *	Preload background images for elements that have 'qodef-preload-background' class
	 */
	function qodefPreloadBackgrounds(){
		var preloadBackHolder = $('.qodef-preload-background');
		
		if(preloadBackHolder.length) {
			preloadBackHolder.each(function() {
				var preloadBackground = $(this);
				
				if(preloadBackground.css('background-image') !== '' && preloadBackground.css('background-image') !== 'none') {
					var bgUrl = preloadBackground.attr('style');
					
					bgUrl = bgUrl.match(/url\(["']?([^'")]+)['"]?\)/);
					bgUrl = bgUrl ? bgUrl[1] : "";
					
					if (bgUrl) {
						var backImg = new Image();
						backImg.src = bgUrl;
						$(backImg).load(function(){
							preloadBackground.removeClass('qodef-preload-background');
						});
					}
				} else {
					$(window).on('load', function(){ preloadBackground.removeClass('qodef-preload-background'); }); //make sure that qodef-preload-background class is removed from elements with forced background none in css
				}
			});
		}
	}
	
	function qodefPrettyPhoto() {
		/*jshint multistr: true */
		var markupWhole = '<div class="pp_pic_holder"> \
                        <div class="ppt">&nbsp;</div> \
                        <div class="pp_top"> \
                            <div class="pp_left"></div> \
                            <div class="pp_middle"></div> \
                            <div class="pp_right"></div> \
                        </div> \
                        <div class="pp_content_container"> \
                            <div class="pp_left"> \
                            <div class="pp_right"> \
                                <div class="pp_content"> \
                                    <div class="pp_loaderIcon"></div> \
                                    <div class="pp_fade"> \
                                        <a href="#" class="pp_expand" title="'+qodefGlobalVars.vars.ppExpand+'">'+qodefGlobalVars.vars.ppExpand+'</a> \
                                        <div class="pp_hoverContainer"> \
                                            <a class="pp_next" href="#"><span class="fa fa-angle-right"></span></a> \
                                            <a class="pp_previous" href="#"><span class="fa fa-angle-left"></span></a> \
                                        </div> \
                                        <div id="pp_full_res"></div> \
                                        <div class="pp_details"> \
                                            <div class="pp_nav"> \
                                                <a href="#" class="pp_arrow_previous">'+qodefGlobalVars.vars.ppPrev+'</a> \
                                                <p class="currentTextHolder">0/0</p> \
                                                <a href="#" class="pp_arrow_next">'+qodefGlobalVars.vars.ppNext+'</a> \
                                            </div> \
                                            <p class="pp_description"></p> \
                                            {pp_social} \
                                            <a class="pp_close" href="#">'+qodefGlobalVars.vars.ppClose+'</a> \
                                        </div> \
                                    </div> \
                                </div> \
                            </div> \
                            </div> \
                        </div> \
                        <div class="pp_bottom"> \
                            <div class="pp_left"></div> \
                            <div class="pp_middle"></div> \
                            <div class="pp_right"></div> \
                        </div> \
                    </div> \
                    <div class="pp_overlay"></div>';
		
		$("a[data-rel^='prettyPhoto']").prettyPhoto({
			hook: 'data-rel',
			animation_speed: 'normal', /* fast/slow/normal */
			slideshow: false, /* false OR interval time in ms */
			autoplay_slideshow: false, /* true/false */
			opacity: 0.80, /* Value between 0 and 1 */
			show_title: true, /* true/false */
			allow_resize: true, /* Resize the photos bigger than viewport. true/false */
			horizontal_padding: 0,
			default_width: 960,
			default_height: 540,
			counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
			theme: 'pp_default', /* light_rounded / dark_rounded / light_square / dark_square / facebook */
			hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */
			wmode: 'opaque', /* Set the flash wmode attribute */
			autoplay: true, /* Automatically start videos: True/False */
			modal: false, /* If set to true, only the close button will close the window */
			overlay_gallery: false, /* If set to true, a gallery will overlay the fullscreen image on mouse over */
			keyboard_shortcuts: true, /* Set to false if you open forms inside prettyPhoto */
			deeplinking: false,
			custom_markup: '',
			social_tools: false,
			markup: markupWhole
		});
	}

    function qodefSearchWidgetAnimation() {
        var holder = $('header .widget_search'),
            field = $('header .widget.widget_search input.search-field'),
        	isOpen = $('.qodef-search-opened');


        holder.on('click', function (e) {
            //e.preventDefault();
            field.toggleClass('qodef-search-opened');
        });

        holder.on('focusout', function (e) {

                field.removeClass('qodef-search-opened');

        });

        // field.keypress(function (e) {
        //     if (e.which == 13) {
        //         $('.widget_search form').submit();
        //         return false;
        //     }
        // });

    }

    function qodefSearchPostTypeWidget() {
        var searchPostTypeHolder = $('.qodef-search-post-type');

        if (searchPostTypeHolder.length) {
            searchPostTypeHolder.each(function () {
                var thisSearch = $(this),
                    searchField = thisSearch.find('.qodef-post-type-search-field'),
                    resultsHolder = thisSearch.siblings('.qodef-post-type-search-results'),
                    searchLoading = thisSearch.find('.qodef-search-loading'),
                    searchIcon = thisSearch.find('.qodef-search-icon');

                searchLoading.addClass('qodef-hidden');

                var postType = thisSearch.data('post-type'),
                    keyPressTimeout;

                searchField.on('keyup paste', function() {
                    var field = $(this);
                    field.attr('autocomplete','off');
                    searchLoading.removeClass('qodef-hidden');
                    searchIcon.addClass('qodef-hidden');
                    clearTimeout(keyPressTimeout);

                    keyPressTimeout = setTimeout( function() {
                        var searchTerm = field.val();
                        
                        if(searchTerm.length < 3) {
                            resultsHolder.html('');
                            resultsHolder.fadeOut();
                            searchLoading.addClass('qodef-hidden');
                            searchIcon.removeClass('qodef-hidden');
                        } else {
                            var ajaxData = {
                                action: 'cevian_select_search_post_types',
                                term: searchTerm,
                                postType: postType
                            };

                            $.ajax({
                                type: 'POST',
                                data: ajaxData,
                                url: qodefGlobalVars.vars.qodefAjaxUrl,
                                success: function (data) {
                                    var response = JSON.parse(data);
                                    if (response.status === 'success') {
                                        searchLoading.addClass('qodef-hidden');
                                        searchIcon.removeClass('qodef-hidden');
                                        resultsHolder.html(response.data.html);
                                        resultsHolder.fadeIn();
                                    }
                                },
                                error: function(XMLHttpRequest, textStatus, errorThrown) {
                                    searchLoading.addClass('qodef-hidden');
                                    searchIcon.removeClass('qodef-hidden');
                                    resultsHolder.fadeOut();
                                }
                            });
                        }
                    }, 500);
                });

                searchField.on('focusout', function () {
                    searchLoading.addClass('qodef-hidden');
                    searchIcon.removeClass('qodef-hidden');
                    resultsHolder.fadeOut();
                });
            });
        }
    }
	
	/**
	 * Initializes load more data params
	 * @param container with defined data params
	 * return array
	 */
	function getLoadMoreData(container){
		var dataList = container.data(),
			returnValue = {};
		
		for (var property in dataList) {
			if (dataList.hasOwnProperty(property)) {
				if (typeof dataList[property] !== 'undefined' && dataList[property] !== false) {
					returnValue[property] = dataList[property];
				}
			}
		}
		
		return returnValue;
	}
	
	/**
	 * Sets load more data params for ajax function
	 * @param container with defined data params
	 * @param action with defined action name
	 * return array
	 */
	function setLoadMoreAjaxData(container, action) {
		var returnValue = {
			action: action
		};
		
		for (var property in container) {
			if (container.hasOwnProperty(property)) {
				
				if (typeof container[property] !== 'undefined' && container[property] !== false) {
					returnValue[property] = container[property];
				}
			}
		}
		
		return returnValue;
	}
	
	/*
	 ** Init Masonry List Layout
	 */
	function qodefInitGridMasonryListLayout() {
		var holder = $('.qodef-grid-masonry-list');
		
		if (holder.length) {
			holder.each(function () {
				var thisHolder = $(this),
					masonry = thisHolder.find('.qodef-masonry-list-wrapper'),
					size = thisHolder.find('.qodef-masonry-grid-sizer').width();
				
				masonry.waitForImages(function () {
					masonry.isotope({
						layoutMode: 'packery',
						itemSelector: '.qodef-item-space',
						percentPosition: true,
						masonry: {
							columnWidth: '.qodef-masonry-grid-sizer',
							gutter: '.qodef-masonry-grid-gutter'
						}
					});
					
					if (thisHolder.find('.qodef-fixed-masonry-item').length || thisHolder.hasClass('qodef-fixed-masonry-items')) {
						setFixedImageProportionSize(masonry, masonry.find('.qodef-item-space'), size, true);
					}
					
					setTimeout(function () {
						qodefInitParallax();
					}, 600);
					
					masonry.isotope('layout').css('opacity', 1);
				});
			});
		}
	}
	
	/**
	 * Initializes size for fixed image proportion - masonry layout
	 */
	function setFixedImageProportionSize(container, item, size, isFixedEnabled) {
		if (container.hasClass('qodef-masonry-images-fixed') || isFixedEnabled === true) {
			var padding = parseInt(item.css('paddingLeft'), 10),
				newSize = size - 2 * padding,
				defaultMasonryItem = container.find('.qodef-masonry-size-small'),
				largeWidthMasonryItem = container.find('.qodef-masonry-size-large-width'),
				largeHeightMasonryItem = container.find('.qodef-masonry-size-large-height'),
				largeWidthHeightMasonryItem = container.find('.qodef-masonry-size-large-width-height');

			defaultMasonryItem.css('height', newSize);
			largeHeightMasonryItem.css('height', Math.round(2 * (newSize + padding)));

			if (qodef.windowWidth > 680) {
				largeWidthMasonryItem.css('height', newSize);
				largeWidthHeightMasonryItem.css('height', Math.round(2 * (newSize + padding)));
			} else {
				largeWidthMasonryItem.css('height', Math.round(newSize / 2));
				largeWidthHeightMasonryItem.css('height', newSize);
			}
		}
	}

	/**
	 * Object that represents icon with hover data
	 * @returns {{init: Function}} function that initializes icon's functionality
	 */
	var qodefIconWithHover = function() {
		//get all icons on page
		var icons = $('.qodef-icon-has-hover');
		
		/**
		 * Function that triggers icon hover color functionality
		 */
		var iconHoverColor = function(icon) {
			if(typeof icon.data('hover-color') !== 'undefined') {
				var changeIconColor = function(event) {
					event.data.icon.css('color', event.data.color);
				};
				
				var hoverColor = icon.data('hover-color'),
					originalColor = icon.css('color');
				
				if(hoverColor !== '') {
					icon.on('mouseenter', {icon: icon, color: hoverColor}, changeIconColor);
					icon.on('mouseleave', {icon: icon, color: originalColor}, changeIconColor);
				}
			}
		};
		
		return {
			init: function() {
				if(icons.length) {
					icons.each(function() {
						iconHoverColor($(this));
					});
				}
			}
		};
	};


    /**
     * Object that represents icon list item with hover data
     * @returns {{init: Function}} function that initializes icon's functionality
     */

    var qodefIconListWithHover = function() {
        //get all icons on page
        var icons = $('.qodef-il-text');

        /**
         * Function that triggers icon hover color functionality
         */
        var iconHoverColor = function(icon) {
            if(typeof icon.data('hover-color') !== 'undefined') {
                var changeIconColor = function(event) {
                    event.data.icon.css('color', event.data.color);
                };

                var hoverColor = icon.data('hover-color'),
                    originalColor = icon.css('color');

                if(hoverColor !== '') {
                    icon.on('mouseenter', {icon: icon, color: hoverColor}, changeIconColor);
                    icon.on('mouseleave', {icon: icon, color: originalColor}, changeIconColor);
                }
            }
        };

        return {
            init: function() {
                if(icons.length) {
                    icons.each(function() {
                        iconHoverColor($(this));
                    });
                }
            }
        };
    };
	
	/*
	 ** Init parallax
	 */
	function qodefInitParallax(){
		var parallaxHolder = $('.qodef-parallax-row-holder');
		
		if(parallaxHolder.length){
			parallaxHolder.each(function() {
				var parallaxElement = $(this),
					image = parallaxElement.data('parallax-bg-image'),
					speed = parallaxElement.data('parallax-bg-speed') * 0.4,
					height = 0;
				
				if (typeof parallaxElement.data('parallax-bg-height') !== 'undefined' && parallaxElement.data('parallax-bg-height') !== false) {
					height = parseInt(parallaxElement.data('parallax-bg-height'));
				}
				
				parallaxElement.css({'background-image': 'url('+image+')'});
				
				if(height > 0) {
					parallaxElement.css({'min-height': height+'px', 'height': height+'px'});
				}
				
				parallaxElement.parallax('50%', speed);
			});
		}
	}
	
	/*
	 **  Init sticky sidebar widget
	 */
	function qodefStickySidebarWidget(){
		var sswHolder = $('.qodef-widget-sticky-sidebar'),
			headerHolder = $('.qodef-page-header'),
			headerHeight = headerHolder.length ? headerHolder.outerHeight() : 0,
			widgetTopOffset = 0,
			widgetTopPosition = 0,
			sidebarHeight = 0,
			sidebarWidth = 0,
			objectsCollection = [];
		
		function addObjectItems() {
			if (sswHolder.length) {
				sswHolder.each(function () {
					var thisSswHolder = $(this),
						mainSidebarHolder = thisSswHolder.parents('aside.qodef-sidebar'),
						widgetiseSidebarHolder = thisSswHolder.parents('.wpb_widgetised_column'),
						sidebarHolder = '',
						sidebarHolderHeight = 0;
					
					widgetTopOffset = thisSswHolder.offset().top;
					widgetTopPosition = thisSswHolder.position().top;
					sidebarHeight = 0;
					sidebarWidth = 0;
					
					if (mainSidebarHolder.length) {
						sidebarHeight = mainSidebarHolder.outerHeight();
						sidebarWidth = mainSidebarHolder.outerWidth();
						sidebarHolder = mainSidebarHolder;
						sidebarHolderHeight = mainSidebarHolder.parent().parent().outerHeight();
						
						var blogHolder = mainSidebarHolder.parent().parent().find('.qodef-blog-holder');
						if (blogHolder.length) {
							sidebarHolderHeight -= parseInt(blogHolder.css('marginBottom'));
						}
					} else if (widgetiseSidebarHolder.length) {
						sidebarHeight = widgetiseSidebarHolder.outerHeight();
						sidebarWidth = widgetiseSidebarHolder.outerWidth();
						sidebarHolder = widgetiseSidebarHolder;
						sidebarHolderHeight = widgetiseSidebarHolder.parents('.vc_row').outerHeight();
					}
					
					objectsCollection.push({
						'object': thisSswHolder,
						'offset': widgetTopOffset,
						'position': widgetTopPosition,
						'height': sidebarHeight,
						'width': sidebarWidth,
						'sidebarHolder': sidebarHolder,
						'sidebarHolderHeight': sidebarHolderHeight
					});
				});
			}
		}
		
		function initStickySidebarWidget() {
			
			if (objectsCollection.length) {
				$.each(objectsCollection, function (i) {
					var thisSswHolder = objectsCollection[i]['object'],
						thisWidgetTopOffset = objectsCollection[i]['offset'],
						thisWidgetTopPosition = objectsCollection[i]['position'],
						thisSidebarHeight = objectsCollection[i]['height'],
						thisSidebarWidth = objectsCollection[i]['width'],
						thisSidebarHolder = objectsCollection[i]['sidebarHolder'],
						thisSidebarHolderHeight = objectsCollection[i]['sidebarHolderHeight'];
					
					if (qodef.body.hasClass('qodef-fixed-on-scroll')) {
						var fixedHeader = $('.qodef-fixed-wrapper.fixed');
						
						if (fixedHeader.length) {
							headerHeight = fixedHeader.outerHeight() + qodefGlobalVars.vars.qodefAddForAdminBar;
						}
					} else if (qodef.body.hasClass('qodef-no-behavior')) {
						headerHeight = qodefGlobalVars.vars.qodefAddForAdminBar;
					}
					
					if (qodef.windowWidth > 1024 && thisSidebarHolder.length) {
						var sidebarPosition = -(thisWidgetTopPosition - headerHeight),
							sidebarHeight = thisSidebarHeight - thisWidgetTopPosition - 40; // 40 is bottom margin of widget holder
						
						//move sidebar up when hits the end of section row
						var rowSectionEndInViewport = thisSidebarHolderHeight + thisWidgetTopOffset - headerHeight - thisWidgetTopPosition - qodefGlobalVars.vars.qodefTopBarHeight;
						
						if ((qodef.scroll >= thisWidgetTopOffset - headerHeight) && thisSidebarHeight < thisSidebarHolderHeight) {
							if (thisSidebarHolder.hasClass('qodef-sticky-sidebar-appeared')) {
								thisSidebarHolder.css({'top': sidebarPosition + 'px'});
							} else {
								thisSidebarHolder.addClass('qodef-sticky-sidebar-appeared').css({
									'position': 'fixed',
									'top': sidebarPosition + 'px',
									'width': thisSidebarWidth,
									'margin-top': '-10px'
								}).animate({'margin-top': '0'}, 200);
							}
							
							if (qodef.scroll + sidebarHeight >= rowSectionEndInViewport) {
								var absBottomPosition = thisSidebarHolderHeight - sidebarHeight + sidebarPosition - headerHeight;
								
								thisSidebarHolder.css({
									'position': 'absolute',
									'top': absBottomPosition + 'px'
								});
							} else {
								if (thisSidebarHolder.hasClass('qodef-sticky-sidebar-appeared')) {
									thisSidebarHolder.css({
										'position': 'fixed',
										'top': sidebarPosition + 'px'
									});
								}
							}
						} else {
							thisSidebarHolder.removeClass('qodef-sticky-sidebar-appeared').css({
								'position': 'relative',
								'top': '0',
								'width': 'auto'
							});
						}
					} else {
						thisSidebarHolder.removeClass('qodef-sticky-sidebar-appeared').css({
							'position': 'relative',
							'top': '0',
							'width': 'auto'
						});
					}
				});
			}
		}
		
		return {
			init: function () {
				addObjectItems();
				initStickySidebarWidget();
				
				$(window).scroll(function () {
					initStickySidebarWidget();
				});
			},
			reInit: initStickySidebarWidget
		};
	}

    /**
     * Init Owl Carousel
     */
    function qodefOwlSlider() {
        var sliders = $('.qodef-owl-slider');

        if (sliders.length) {
            sliders.each(function(){
                var slider = $(this),
                    owlSlider = $(this),
	                slideItemsNumber = slider.children().length,
	                numberOfItems = 1,
	                loop = true,
	                autoplay = true,
	                autoplayHoverPause = true,
	                sliderSpeed = 5000,
	                sliderSpeedAnimation = 600,
	                margin = 0,
	                responsiveMargin = 0,
	                responsiveMargin1 = 0,
	                stagePadding = 0,
	                stagePaddingEnabled = false,
	                center = false,
	                autoWidth = false,
	                animateInClass = false, // keyframe css animation
	                animateOutClass = false, // keyframe css animation
	                navigation = true,
	                pagination = false,
	                thumbnail = false,
                    thumbnailSlider,
	                sliderIsCPTList = !!slider.hasClass('qodef-list-is-slider'),
	                sliderDataHolder = sliderIsCPTList ? slider.parent() : slider;  // this is condition for cpt to set list to be slider
	
	            if (typeof slider.data('number-of-items') !== 'undefined' && slider.data('number-of-items') !== false && ! sliderIsCPTList) {
		            numberOfItems = slider.data('number-of-items');
	            }
	            if (typeof sliderDataHolder.data('number-of-columns') !== 'undefined' && sliderDataHolder.data('number-of-columns') !== false && sliderIsCPTList) {
		            switch (sliderDataHolder.data('number-of-columns')) {
			            case 'one':
				            numberOfItems = 1;
				            break;
			            case 'two':
				            numberOfItems = 2;
				            break;
			            case 'three':
				            numberOfItems = 3;
				            break;
			            case 'four':
				            numberOfItems = 4;
				            break;
			            case 'five':
				            numberOfItems = 5;
				            break;
			            case 'six':
				            numberOfItems = 6;
				            break;
			            default :
				            numberOfItems = 4;
				            break;
		            }
	            }
	            if (sliderDataHolder.data('enable-loop') === 'no') {
		            loop = false;
	            }
	            if (sliderDataHolder.data('enable-autoplay') === 'no') {
		            autoplay = false;
	            }
	            if (sliderDataHolder.data('enable-autoplay-hover-pause') === 'no') {
		            autoplayHoverPause = false;
	            }
	            if (typeof sliderDataHolder.data('slider-speed') !== 'undefined' && sliderDataHolder.data('slider-speed') !== false) {
		            sliderSpeed = sliderDataHolder.data('slider-speed');
	            }
	            if (typeof sliderDataHolder.data('slider-speed-animation') !== 'undefined' && sliderDataHolder.data('slider-speed-animation') !== false) {
		            sliderSpeedAnimation = sliderDataHolder.data('slider-speed-animation');
	            }
	            if (typeof sliderDataHolder.data('slider-margin') !== 'undefined' && sliderDataHolder.data('slider-margin') !== false) {
		            if (sliderDataHolder.data('slider-margin') === 'no') {
			            margin = 0;
		            } else {
			            margin = sliderDataHolder.data('slider-margin');
		            }
	            } else {
		            if(slider.parent().hasClass('qodef-huge-space')) {
			            margin = 60;
		            } else if (slider.parent().hasClass('qodef-large-space')) {
			            margin = 50;
		            } else if (slider.parent().hasClass('qodef-medium-space')) {
			            margin = 40;
		            } else if (slider.parent().hasClass('qodef-normal-space')) {
			            margin = 30;
		            } else if (slider.parent().hasClass('qodef-small-space')) {
			            margin = 20;
		            } else if (slider.parent().hasClass('qodef-tiny-space')) {
			            margin = 10;
		            }
	            }
	            if (sliderDataHolder.data('slider-padding') === 'yes') {
		            stagePaddingEnabled = true;
		            stagePadding = parseInt(slider.outerWidth() * 0.28);
		            margin = 50;
	            }
	            if (sliderDataHolder.data('enable-center') === 'yes') {
		            center = true;
	            }
	            if (sliderDataHolder.data('enable-auto-width') === 'yes') {
		            autoWidth = true;
	            }
	            if (typeof sliderDataHolder.data('slider-animate-in') !== 'undefined' && sliderDataHolder.data('slider-animate-in') !== false) {
		            animateInClass = sliderDataHolder.data('slider-animate-in');
	            }
	            if (typeof sliderDataHolder.data('slider-animate-out') !== 'undefined' && sliderDataHolder.data('slider-animate-out') !== false) {
                    animateOutClass = sliderDataHolder.data('slider-animate-out');
	            }
	            if (sliderDataHolder.data('enable-navigation') === 'no') {
		            navigation = false;
	            }
	            if (sliderDataHolder.data('enable-pagination') === 'yes') {
		            pagination = true;
	            }

	            if (sliderDataHolder.data('enable-thumbnail') === 'yes') {
                    thumbnail = true;
	            }

	            if(thumbnail && !pagination) {
                    /* page.index works only when pagination is enabled, so we add through html, but hide via css */
	                pagination = true;
                    owlSlider.addClass('qodef-slider-hide-pagination');
                }

	            if(navigation && pagination) {
		            slider.addClass('qodef-slider-has-both-nav');
	            }

	            if (slideItemsNumber <= 1) {
		            loop       = false;
		            autoplay   = false;
		            navigation = false;
		            pagination = false;
	            }

	            var responsiveNumberOfItems1 = 1,
		            responsiveNumberOfItems2 = 2,
		            responsiveNumberOfItems3 = 3,
		            responsiveNumberOfItems4 = numberOfItems,
		            responsiveNumberOfItems5 = numberOfItems;

	            if (numberOfItems < 3) {
		            responsiveNumberOfItems2 = numberOfItems;
		            responsiveNumberOfItems3 = numberOfItems;
	            }

	            if (numberOfItems > 4) {
		            responsiveNumberOfItems4 = 4;
	            }
	
	            if (numberOfItems > 5) {
		            responsiveNumberOfItems5 = 5;
	            }

	            if (stagePaddingEnabled || margin > 30) {
		            responsiveMargin = 20;
		            responsiveMargin1 = 30;
	            }

	            if (margin > 0 && margin <= 30) {
		            responsiveMargin = margin;
		            responsiveMargin1 = margin;
	            }

	            slider.waitForImages(function () {
		            owlSlider = slider.owlCarousel({
			            items: numberOfItems,
			            loop: loop,
			            autoplay: autoplay,
			            autoplayHoverPause: autoplayHoverPause,
			            autoplayTimeout: sliderSpeed,
			            smartSpeed: sliderSpeedAnimation,
			            margin: margin,
			            stagePadding: stagePadding,
			            center: center,
			            autoWidth: autoWidth,
			            animateIn: animateInClass,
			            animateOut: animateOutClass,
			            dots: pagination,
			            nav: navigation,
			            navText: [
				            '<span class="qodef-prev-icon ' + qodefGlobalVars.vars.sliderNavPrevArrow + '"></span>',
				            '<span class="qodef-next-icon ' + qodefGlobalVars.vars.sliderNavNextArrow + '"></span>'
			            ],
			            responsive: {
				            0: {
					            items: responsiveNumberOfItems1,
					            margin: responsiveMargin,
					            stagePadding: 0,
					            center: false,
					            autoWidth: false
				            },
				            681: {
					            items: responsiveNumberOfItems2,
					            margin: responsiveMargin1
				            },
				            769: {
					            items: responsiveNumberOfItems3,
					            margin: responsiveMargin1
				            },
				            1025: {
					            items: responsiveNumberOfItems4
				            },
				            1281: {
					            items: responsiveNumberOfItems5
				            },
				            1367: {
					            items: numberOfItems
				            }
			            },
			            onInitialize: function () {
				            slider.css('visibility', 'visible');
				            qodefInitParallax();
				            if (slider.find('iframe').length || slider.find('video').length) {
					            setTimeout(function () {
						            qodefSelfHostedVideoSize();
						            qodefFluidVideo();
					            }, 500);
				            }
				            if (thumbnail) {
					            thumbnailSlider.find('.qodef-slider-thumbnail-item:first-child').addClass('active');
				            }
			            },
			            onRefreshed: function () {
				            if (autoWidth === true) {
					            var oldSize = parseInt(slider.find('.owl-stage').css('width'));
					            slider.find('.owl-stage').css('width', (oldSize + 1) + 'px');
				            }
			            },
			            onTranslate: function (e) {
				            if (thumbnail) {
					            var index = e.page.index + 1;
					            thumbnailSlider.find('.qodef-slider-thumbnail-item.active').removeClass('active');
					            thumbnailSlider.find('.qodef-slider-thumbnail-item:nth-child(' + index + ')').addClass('active');
				            }
			            },
			            onDrag: function (e) {
				            if (qodef.body.hasClass('qodef-smooth-page-transitions-fadeout')) {
					            var sliderIsMoving = e.isTrigger > 0;
					
					            if (sliderIsMoving) {
						            slider.addClass('qodef-slider-is-moving');
					            }
				            }
			            },
			            onDragged: function () {
				            if (qodef.body.hasClass('qodef-smooth-page-transitions-fadeout') && slider.hasClass('qodef-slider-is-moving')) {
					
					            setTimeout(function () {
						            slider.removeClass('qodef-slider-is-moving');
					            }, 500);
				            }
			            }
		            });
	            });
	
	            if (thumbnail) {
		            thumbnailSlider = slider.parent().find('.qodef-slider-thumbnail');
		
		            var numberOfThumbnails = parseInt(thumbnailSlider.data('thumbnail-count'));
		            var numberOfThumbnailsClass = '';
		
		            switch (numberOfThumbnails % 6) {
			            case 2 :
				            numberOfThumbnailsClass = 'two';
				            break;
			            case 3 :
				            numberOfThumbnailsClass = 'three';
				            break;
			            case 4 :
				            numberOfThumbnailsClass = 'four';
				            break;
			            case 5 :
				            numberOfThumbnailsClass = 'five';
				            break;
			            case 0 :
				            numberOfThumbnailsClass = 'six';
				            break;
			            default :
				            numberOfThumbnailsClass = 'six';
				            break;
		            }
		
		            if (numberOfThumbnailsClass !== '') {
			            thumbnailSlider.addClass('qodef-slider-columns-' + numberOfThumbnailsClass);
		            }
		
		            thumbnailSlider.find('.qodef-slider-thumbnail-item').on('click', function () {
			            $(this).siblings('.active').removeClass('active');
			            $(this).addClass('active');
			            owlSlider.trigger('to.owl.carousel', [$(this).index(), sliderSpeedAnimation]);
		            });
	            }
            });
        }
    }

	function qodefDashboardForm() {
		var forms = $('.qodef-dashboard-form');

		if (forms.length) {
			forms.each(function () {
				var thisForm = $(this),
					btnText = thisForm.find('button.qodef-dashboard-form-button'),
					updatingBtnText = btnText.data('updating-text'),
					updatedBtnText = btnText.data('updated-text'),
					actionName = thisForm.data('action');

				thisForm.on('submit', function (e) {
					e.preventDefault();
					var prevBtnText = btnText.html(),
						gallery = $(this).find('.qodef-dashboard-gallery-upload-hidden'),
						namesArray = [];

					btnText.html(updatingBtnText);

					//get data
					var formData = new FormData();

					//get files
					gallery.each(function () {
						var thisGallery = $(this),
							thisName = thisGallery.attr('name'),
							thisRepeaterID = thisGallery.attr('id'),
							thisFiles = thisGallery[0].files,
							newName;

						//this part is needed for repeater with image uploads
						//adding specific names so they can be sorted in regular files and files in repeater
						if (thisName.indexOf("[") > -1) {
							newName = thisName.substring(0, thisName.indexOf("[")) + '_qodef_regarray_';

							var firstIndex = thisRepeaterID.indexOf('['),
								lastIndex = thisRepeaterID.indexOf(']'),
								index = thisRepeaterID.substring(firstIndex + 1, lastIndex);

							namesArray.push(newName);
							newName = newName + index + '_';
						} else {
							newName = thisName + '_qodef_reg_';
						}

						//if file not sent, send dummy file - so repeater fields are sent
						if (thisFiles.length === 0) {
							formData.append(newName, new File([""], "qodef-dummy-file.txt", {
								type: "text/plain"
							}));
						}

						for (var i = 0; i < thisFiles.length; i++) {
							var allowedTypes = ['image/png','image/jpg','image/jpeg','application/pdf'];
							//security purposed - check if there is more than one dot in file name, also check whether the file type is in allowed types
							if (thisFiles[i].name.match(/\./g).length === 1 && $.inArray(thisFiles[i].type, allowedTypes) !== -1) {
								formData.append(newName + i, thisFiles[i]);
							}
						}
					});

					formData.append('action', actionName);

					//get data from form
					var otherData = $(this).serialize();
					formData.append('data', otherData);

					$.ajax({
						type: 'POST',
						data: formData,
						contentType: false,
						processData: false,
						url: qodefGlobalVars.vars.qodefAjaxUrl,
						success: function (data) {
							var response;
							response = JSON.parse(data);

							// append ajax response html
							qodef.modules.socialLogin.qodefRenderAjaxResponseMessage(response);
							if (response.status === 'success') {
								btnText.html(updatedBtnText);
								window.location = response.redirect;
							} else {
								btnText.html(prevBtnText);
							}
						}
					});

					return false;
				});
			});
		}
	}

    /**
     * Init Perfect Scrollbar
     */
    function qodefInitPerfectScrollbar() {
	    var defaultParams = {
		    wheelSpeed: 0.6,
		    suppressScrollX: true
	    };
	
	    var qodefInitScroll = function ( holder ) {
			if ( holder.length ) {
				var ps = new PerfectScrollbar(
					holder[0],
					defaultParams
				);

				$( window ).resize( function () {
					ps.update();
				} );
			}
		};
	
	    return {
		    init: function (holder) {
			    if (holder.length) {
				    qodefInitScroll(holder);
			    }
		    }
	    };
    }

    /*function qodefInitBackgroundGrid(){
    	var backgroundHolders = $('.qodef-with-bg-grid');

    	if(backgroundHolders.length){
    		backgroundHolders.each(function(){
    			var holder = $(this),
					gridHolder = holder.find('.qodef-grid-outer-holder'),
					children = holder.hasClass('vc_row') ? holder.children().filter('.wpb_column') : holder.find('> div:not(.qodef-grid-outer-holder)').children(),
					holderWidth = holder.outerWidth(),
					childrenWidth = children.outerWidth(),
					columnsNumber = Math.round( holderWidth / childrenWidth ),
					gridColor = '',
					output = '';

                if(holder.data('grid-color') !== 'undefined' && holder.data('grid-color') !== false && holder.data('grid-color') !== ''){
                    gridColor = holder.data('grid-color');
                }

    			for(var i = 0; i < children.length - 1; i++){
    				if(children.eq(i).position().top !== children.eq(i+1).position().top){
                        output += '<div class="qodef-grid-horizontal-line" style="top: ' + Math.floor(children.eq(i+1).position().top - 1) + 'px; background-color: ' + gridColor + ';"></div>';
					}
				}

    			if( columnsNumber > 0 ){

                    for(i = 0; i < columnsNumber - 1; i++){
                        output += '<div class="qodef-grid-vertical-line" style="left: ' + ( ( i + 1 ) * 100 / columnsNumber ) + '%; background-color: ' + gridColor + ';"></div>';
					}

				}

                gridHolder.html(output);
			})
		}
	}*/

	function qodefInitBgGrid(holder, itemStr){
    	if(itemStr.length){
    		//console.log(holder.length);

            var item = holder.find('.' + itemStr);

            //thisHolder = item.closest('.' + holderStr);

            var gridHolder = holder.find('.qodef-grid-outer-holder'),
                children = item,
                holderWidth = holder.outerWidth(),
                childrenWidth = children.outerWidth(),
                columnsNumber = Math.round( holderWidth / childrenWidth ),
                gridColor = ' ',
                output = '<div class="qodef-grid-outer-holder">';

            // console.log(typeof thisHolder.data('grid-color') !== 'undefined');
            // console.log(thisHolder.data('grid-color') !== false);
            // console.log(thisHolder.data('grid-color') !== '');

            if(typeof holder.data('grid-color') !== 'undefined' && holder.data('grid-color') !== false && holder.data('grid-color') !== ''){
                gridColor = holder.data('grid-color');
            }

            //console.log(children.length);

            if(itemStr !== 'qodef-iwt' && itemStr !== 'qodef-image-with-text-holder') {
                for (var i = 0; i < children.length - 1; i++) {
                    // console.log(children.eq(i+1).position().top);
                    // console.log('text');
                    if (children.eq(i).position().top !== children.eq(i + 1).position().top && children.eq(i + 1).position().top !== 0) {
                        //console.log(itemStr);
                        //console.log(holderStr);
                        output += '<div class="qodef-grid-horizontal-line" style="top: ' + Math.floor(children.eq(i + 1).position().top - 1) + 'px; background-color: ' + gridColor + ';"></div>';
                    }
                }
            }

            if(itemStr == 'qodef-iwt' || itemStr == 'qodef-image-with-text-holder'){
                for( var i = 0; i < children.length - 1; i++){
                    if(children.eq(i).closest('.wpb_column').position().top !== children.eq(i+1).closest('.wpb_column').position().top && children.eq(i+1).closest('.wpb_column').position().top !== 0){
                        //console.log(itemStr);
                        //console.log(holderStr);
                        output += '<div class="qodef-grid-horizontal-line" style="top: ' + Math.floor(children.eq(i+1).closest('.wpb_column').position().top - 1) + 'px; background-color: ' + gridColor + ';"></div>';
                    }
                }
			}
            //console.log("columns number: "+columnsNumber);
            if(columnsNumber === Infinity){
                columnsNumber = 0;
            }

            if( columnsNumber > 0 ){
                for( var i = 0; i < columnsNumber - 1; i++){

                    output += '<div class="qodef-grid-vertical-line" style="left: ' + ( ( i + 1 ) * 100 / columnsNumber ) + '%; background-color: ' + gridColor + ';"></div>';
                }

            }

            output += '</div>';

            if(gridHolder.length){
                gridHolder.remove();
            }

            holder.append(output);

            // holder.each(function(){
            	// //var thisHolder = $(this);
            //
			// })

		}
	}

    function qodefInitIwtBgGrid(){
		var rowWithIwt = $('.vc_row.qodef-with-bg-grid, .vc_row_inner.qodef-with-bg-grid');

		if(rowWithIwt.length && rowWithIwt.find('.qodef-iwt').length){
            rowWithIwt.each(function() {
                qodefInitBgGrid($(this), 'qodef-iwt');
			})
		}
	}

	function qodefInitImageWithTextBgGrid(){
		var rowWithIwt = $('.vc_row.qodef-with-bg-grid, .vc_row_inner.qodef-with-bg-grid');

		if(rowWithIwt.length && rowWithIwt.find('.qodef-image-with-text-holder').length){
			rowWithIwt.each(function(){
                qodefInitBgGrid($(this), 'qodef-image-with-text-holder');
			})
		}
	}

	function qodefInitProductListBgGrid(){
		var rowWithPL = $('.qodef-pl-holder.qodef-with-bg-grid');

		if(rowWithPL.length){
            rowWithPL.each(function(){
                qodefInitBgGrid($(this), 'qodef-pli');
			})
		}
	}

	function qodefInitEHBgGrid(){
		var rowWithEH = $('.qodef-elements-holder.qodef-with-bg-grid');

		if(rowWithEH.length && rowWithEH.find('.qodef-eh-item').length){
            rowWithEH.each(function(){
                qodefInitBgGrid($(this), 'qodef-eh-item');
			})
		}
	}

	function qodefInitClientsGridBgGrid(){
		var rowWithClients = $('.qodef-clients-grid-holder.qodef-with-bg-grid');

		if(rowWithClients.length){
            //rowWithPL.each(function(){
                qodefInitBgGrid(rowWithClients, 'qodef-cc-item');
			//})
		}
	}



    function qodefRowBackgroundText() {
        var backgroundText = $('.qodef-row-background-text-holder');

        backgroundText.each(function () {
            var backgroundTextInstance = $(this),
                backgroundTextWrapper = backgroundTextInstance.find('.qodef-row-background-text-wrapper'),
                backgroundTextInner = backgroundTextInstance.find('.qodef-row-background-text-wrapper-inner'),
                row = backgroundTextInstance.parent().addClass('qodef-row-has-background-text');

            if(qodef.windowWidth > 1280 && qodef.windowWidth <=1440) {
                if( typeof backgroundTextInner.data('font-size-1440') !== 'undefined' && backgroundTextInner.data('font-size-1440') !== false){
                    backgroundTextInner.css('font-size', backgroundTextInner.data('font-size-1440'));
                }

                if( typeof backgroundTextInner.data('padding-size-1440') !== 'undefined' && backgroundTextInner.data('padding-size-1440') !== false){
                    backgroundTextInner.css('padding-top', backgroundTextInner.data('padding-size-1440'));
                }
            }

            if(qodef.windowWidth > 1024 && qodef.windowWidth <=1280){
                if( typeof backgroundTextInner.data('font-size-1280') !== 'undefined' && backgroundTextInner.data('font-size-1280') !== false){
                    backgroundTextInner.css('font-size', backgroundTextInner.data('font-size-1280'));
                }

                if( typeof backgroundTextInner.data('padding-size-1280') !== 'undefined' && backgroundTextInner.data('padding-size-1280') !== false){
                    backgroundTextInner.css('padding-top', backgroundTextInner.data('padding-size-1280'));
                }
            }

            //backgroundTextInstance.prev().css('z-index', 10);

            //appear fx
            if (backgroundTextWrapper.hasClass('qodef-row-background-text-animation') && !qodef.htmlEl.hasClass('touch')) {
                var bgrndTextElements = backgroundTextInstance.find('.qodef-row-background-text-1, .qodef-row-background-text-2'),
                    delay = 120;

                bgrndTextElements.each(function(i){
                    var bgrndTextElement = $(this),
                        txt = bgrndTextElement.text(),
                        newTxt = txt.replace(/[^\s]/g,function(c){
                            return '<span class="qodef-char-mask"><span>'+c+'</span></span>';
                        });

                    bgrndTextElement.html(newTxt);


                    var showText = function() {
                        backgroundTextWrapper.css('visibility','visible');

                        backgroundTextInstance.find('.qodef-char-mask > span').each(function(j){
                            var bgrndChar = $(this);

                            bgrndChar
                                .css('transition-delay', j*delay +'ms')
                                .addClass('qodef-show');
                        });
                    }

                    if ( $('#qodef-dynamic-intro-section').length) {
                        $(document).on('qodefPreloaded', function(){
                            backgroundTextInstance.appear(function(){
                                showText();
                            }, {accX: 0, accY: qodefGlobalVars.vars.qodefElementAppearAmount});
                        });
                    } else {
                        $(window).on('load', function(){
                            backgroundTextInstance.appear(function(){
                                showText();
                            }, {accX: 0, accY: qodefGlobalVars.vars.qodefElementAppearAmount});
                        });
                    }
                });
            }

        })
    }

    function qodefInitRevSliderParamsTweaks(){
        var revHolder = $('.rev_slider');

        if (revHolder.length) {
            revHolder.each(function(){
            	var thisRevHolder = $(this);
				thisRevHolder.on('revolution.slide.onloaded', function () {
                    setTimeout(function(){
                        thisRevHolder.addClass('qodef-show-navigation');
					}, 2000);
                });
			});
        }
	}

	function qodefInitIconWithTextHover(){
    	var iwts = $('.qodef-iwt');

    	if( iwts.length ){
    		iwts.each(function(){
    			var iwt = $(this),
					iwtTitle = iwt.find('.qodef-iwt-title'),
					iwtTitleLink = iwtTitle.find('a'),
					iwtInitialColor,
					iwtHoverColor;

    			if( iwtTitle.length ){
    				if( typeof iwtTitle.data('hover-color') !== 'undefined' &&  iwtTitle.data('hover-color') !== ''){
                        iwtHoverColor = iwtTitle.data('hover-color');
					}

                    iwtInitialColor = iwtTitle.css('color');

                    iwt.on('mouseenter', function(){
                        iwtTitle.css('color', iwtHoverColor);
                        iwtTitleLink.css('color', iwtHoverColor);
					});

                    iwt.on('mouseleave', function(){
                        iwtTitle.css('color', iwtInitialColor);
                        iwtTitleLink.css('color', iwtInitialColor);
					});
				}

			});
		}
	}

})(jQuery);