(function($){

"use strict";

/******************************************************
*
*   Check parent
*
******************************************************/
jQuery.expr[':'].notparents = function(a,i,m){
    return jQuery(a).parents(m[3]).length < 1;
};

/*! Copyright 2012, Ben Lin (http://dreamerslab.com/)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * Version: 1.0.14
 *
 * Requires: jQuery 1.2.3 ~ 1.9.0
 */
;(function(e){e.fn.extend({actual:function(t,n){if(!this[t]){throw'$.actual => The jQuery method "'+t+'" you called does not exist'}var r={absolute:false,clone:false,includeMargin:false};var i=e.extend(r,n);var s=this.eq(0);var o,u;if(i.clone===true){o=function(){var e="position: absolute !important; top: -1000 !important; ";s=s.clone().attr("style",e).appendTo("body")};u=function(){s.remove()}}else{var a=[];var f="";var l;o=function(){if(e.fn.jquery>="1.8.0")l=s.parents().addBack().filter(":hidden");else l=s.parents().andSelf().filter(":hidden");f+="visibility: hidden !important; display: block !important; ";if(i.absolute===true)f+="position: absolute !important; ";l.each(function(){var t=e(this);a.push(t.attr("style"));t.attr("style",f)})};u=function(){l.each(function(t){var n=e(this);var r=a[t];if(r===undefined){n.removeAttr("style")}else{n.attr("style",r)}})}}o();var c=/(outer)/g.test(t)?s[t](i.includeMargin):s[t]();u();return c}})})(jQuery);

/*
 * Function for finding elements in viewport
 *
 */
(function ($) {

   var $window = $(window),
       _watch = [],
       _buffer;

   function test($el, tolerance) {
      var docViewTop = $window.scrollTop() - tolerance,
          docViewBottom = $window.scrollTop() + $window.height() + tolerance,
          elemTop = $el.offset().top,
          elemBottom = elemTop + $el.outerHeight();

      return ( ( elemBottom >= docViewTop && elemTop <= docViewBottom ) || ( elemBottom <= docViewBottom && elemTop >= docViewTop ) || ( elemBottom >= docViewTop && elemTop <= docViewTop ) );
   }

   function scroller( e ) {
         if ( !_buffer ) {

            _buffer = setTimeout(function () {

               checkInView( e );

               _buffer = null;

            }, 300);
         }
   }

	if (window.addEventListener) {
		//window.addEventListener('load', scroller, false);
		window.addEventListener('scroll', scroller, false);
	} else if (window.attachEvent) {
		//window.attachEvent('onload', scroller);
		window.attachEvent('onscroll', scroller);
	}
	$window.on('resize', scroller);
	$(function() {
		setTimeout(scroller, 0);
	});



   function checkInView( e ) {

      $.each(_watch, function () {

         if ( test( this.element, this.options.tolerance ) ) {
            if ( !this.invp ) {
               this.invp = true;
               if ( this.options.scrolledin ) 
                   this.options.scrolledin.call( this.element, e );
                
               this.element.trigger( 'scrolledin', e );
            }
         } else if ( this.invp ) {
            this.invp = false;
            if ( this.options.scrolledout ) 
                this.options.scrolledout.call( this.element, e );
             
            this.element.trigger( 'scrolledout', e );
         }
      });
   }

   function monitor( element, options ) {
      var item = { element: element, options: options, invp: false };
      _watch.push(item);
      return item;
   }

   function unmonitor( item ) {
      for ( var i=0;i<_watch.length;i++ ) {
         if ( _watch[i] === item ) {
            _watch.splice( i, 1 );
            item.element = null;
            break;
         }
      }
   }

	var pluginName = 'pixGridderScrolledIntoView',
		settings = {
			tolerance: null,
			scrolledin: null,
			scrolledout: null
		};


		$.fn[pluginName] = function( options ) {

			var options = $.extend({}, settings, options);

			this.each( function () {

				var $el = $(this),
					instance = $.data( this, pluginName );

				if ( instance ) {
					instance.options = options;
				} else {
					$.data( this, pluginName, monitor( $el, options ) );
					$el.on( 'remove', $.proxy( function () {

						$.removeData(this, pluginName);
						unmonitor( instance );

					}, this ) );
				}
			});

			return this;
		};


})(jQuery);

var PIXGRIDDER = window.PIXGRIDDER || {};

PIXGRIDDER.rotatingFrames = function(){
	var $window = $(window);
	$('.row[style*="rotate"]').addClass('pixgridder_rotate').each(function(){
		if ( !$('.pix_section_video', this).length ) {
			if ( !$('.rotating-frame', this).length ) {
				var $frame = $(this);
				$frame.append('<div class="rotating-frame"><div class="rotating-inside"></div></div>');
				var rot = $frame.attr('style').match(/rotate\((.+?)deg\)/gi);
				rot = rot[0];
				rot = rot.replace(/rotate\((.+?)deg\)/gi,'$1');
				var negRot = rot*-1,
				bgImg,
				bgRep,
				bgColor,
				ratio;

				$('.rotating-frame', $frame).css({
					webkitTransform: 'rotate('+rot+'deg)',
					mozTransform: 'rotate('+rot+'deg)',
					msTransform: 'rotate('+rot+'deg)',
					oTransform: 'rotate('+rot+'deg)',
					transform: 'rotate('+rot+'deg)'
				});
				$('.rotating-inside', $frame).css({
					webkitTransform: 'rotate('+negRot+'deg)',
					mozTransform: 'rotate('+negRot+'deg)',
					msTransform: 'rotate('+negRot+'deg)',
					oTransform: 'rotate('+negRot+'deg)',
					transform: 'rotate('+negRot+'deg)'
				});

				if ( typeof $frame.attr('style') !== 'undefined' && $frame.attr('style').match(/background-image/) ) {
					bgImg = $frame.css('background-image');
					$frame.css('background-image','');
					$('.rotating-inside', $frame).css('background-image',bgImg);
				}

				if ( typeof $frame.attr('style') !== 'undefined' && $frame.attr('style').match(/background-repeat/) ) {
					bgRep = $frame.css('background-repeat');
					$frame.css('background-repeat','');
					$('.rotating-inside', $frame).css('background-repeat',bgRep);
				}

				if ( typeof $frame.attr('data-pix-ratio') !== 'undefined' ) {
					ratio = $frame.attr('data-pix-ratio');
					$frame.removeAttr('data-pix-ratio');
					$('.rotating-inside', $frame).attr('data-pix-ratio',ratio);
				}

				if ( typeof $frame.attr('style') !== 'undefined' && $frame.attr('style').match(/background-color/) ) {
					bgColor = $frame.css('background-color');
					$frame.css('background-color','');
					$('.rotating-frame', $frame).css('background-color',bgColor);
				}

			}
		} else {
			$(this).css({
				webkitTransform: 'rotate(0)',
				mozTransform: 'rotate(0)',
				msTransform: 'rotate(0)',
				oTransform: 'rotate(0)',
				transform: 'rotate(0)'
			});
		}
		$window.trigger('pix-parallax');
	});

};

PIXGRIDDER.pixgridderParallax = function() {
	var $window = $(window),
		$dataratio = $('[data-pix-ratio]'),
		fromTop;

	$dataratio.each(function(){

		var $div = $(this),
			leng = $('.rotating-inside', $div).length;

		$div = leng ? $('.rotating-inside', $div) : $(this);

		var imgUrlOr = $div.css('background-image'),
			imgSize = (typeof $div.css('background-size') == 'undefined' || parseFloat($div.css('background-size')) == '0') ? '100%' : $div.css('background-size'),
			imgRepeat = (typeof $div.css('background-repeat') == 'undefined') ? 'no-repeat' : $div.css('background-repeat'),
			ratio = $div.attr('data-pix-ratio'),
			imgUrl = /^url\((['"]?)(.*)\1\)$/.exec(imgUrlOr),
			newImg,
			imgW,
			imgH;

		imgUrl = imgUrl ? imgUrl[2] : "";

		var img = $('<img />').one('load',function(){
			if ( !$('img.pix-parallax', $div).length ) {
				newImg = '<img src="'+imgUrl+'" class="pix-parallax">';
				imgW = $(newImg).naturalWidth();
				imgH = $(newImg).naturalHeight();
				newImg = $(newImg)
					.attr('data-orheight',imgH)
					.attr('data-orwidth',imgW)
					.attr('src',pixgridder_blank_gif)
					.css({
						backgroundImage: imgUrlOr,
						backgroundSize: imgSize,
						backgroundRepeat: imgRepeat,
						position: 'absolute'
					});
				$div
					.css({backgroundImage:'', overflow:'hidden'})
					.prepend(newImg);
					$window.trigger('pix-parallax');
			}
		}).attr('src', imgUrl).each(function() {
			if(this.complete) {
				$(this).load();
			}
		});

		var moveParax = function(){
			fromTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
			var $img = $('img.pix-parallax', $div),
				winH = $window.height(),
				elemTop = $div.offset().top,
				elemBottom = elemTop + $div.outerHeight(),
				scrollEl = (elemTop-fromTop)*ratio*-1;

			if ( typeof $img[0] !== 'undefined' ) {
				$img[0].style['-webkit-transform'] = 'translate3d(0,'+scrollEl+'px,0)';
				$img[0].style['-moz-transform'] = 'translate3d(0,'+scrollEl+'px,0)';
				$img[0].style['-ms-transform'] = 'translate3d(0,'+scrollEl+'px,0)';
				$img[0].style['-o-transform'] = 'translate3d(0,'+scrollEl+'px,0)';
				$img[0].style['transform'] = 'translate3d(0,'+scrollEl+'px,0)';
			}

		};

		var stopParax = function(){
			var $img = $('img.pix-parallax', $div);

			if ( typeof $img[0] !== 'undefined' ) {
				$img[0].style['-webkit-transform'] = 'translate3d(0,0,0)';
				$img[0].style['-moz-transform'] = 'translate3d(0,0,0)';
				$img[0].style['-ms-transform'] = 'translate3d(0,0,0)';
				$img[0].style['-o-transform'] = 'translate3d(0,0,0)';
				$img[0].style['transform'] = 'translate3d(0,0,0)';
			}

		};

		$window.on('pix-parallax resize', function(){
			if( !Modernizr.touch && $window.width() > 1024 ){
				$div.pixGridderScrolledIntoView({
					tolerance: 200,
					scrolledin: function () {
						if (window.addEventListener) {
							window.addEventListener('load', moveParax, false);
							window.addEventListener('scroll', moveParax, false);
							window.addEventListener('resize', moveParax, false);
						} else if (window.attachEvent) {
							window.attachEvent('onscroll', moveParax);
							window.attachEvent('onresize', moveParax);
						}
					}, scrolledout: function () {
						if (window.removeEventListener) {
							window.removeEventListener('load', moveParax, false);
							window.removeEventListener('scroll', moveParax, false);
							window.removeEventListener('resize', moveParax, false);
						} else if (window.detachEvent) {
							window.detachEvent('onscroll', moveParax);
							window.detachEvent('onresize', moveParax);
						}
						stopParax();
					}
				});
			}
		});
	});

	$window.on('pix-parallax resize', function(){
		$('img.pix-parallax').each(function(){
			var $img = $(this),
				$div = $img.parents('div[data-pix-ratio]').eq(0),
				ratio = parseFloat($div.attr('data-pix-ratio')),
				position = 'absolute',
				$parent = $img.parents('div').eq(0),
				w = $parent.outerWidth(),
				winH = $window.height(),
				pH = $parent.outerHeight(),
				h,
				imgW = $img.data('orwidth'),
				imgH = $img.data('orheight'),
				css, r, d, d1, d2,
				ratioImg = imgW/imgH,
				ratioSection;

				h = winH > pH ? winH : pH;
				//h = h+(h*ratio);
				ratioSection = w/h;

			if( ratioImg > ratioSection ) {
				r = h / imgH;
				d = d1 = d2 = (w - (imgW*r))*0.5;
				$img.css({
					'height' : h,
					'left': 0,
					'margin-left': d1+'px',
					'margin-right': d2+'px',
					'margin-top': 0,
					'max-width': 'none',
					'position': position,
					'top': 0,
					'width': imgW*r,
					'z-Index': '-1'
				});
			} else {
				r = w / imgW;
				d = (h - (imgH*r))*0.5;
				$img.css({
					'height': imgH*r,
					'left': 0,
					'margin-left': 0,
					'margin-right': 0,
					'margin-top': d+'px',
					'max-width': 'none',
					'position': position,
					'top': 0,
					'width': w,
					'z-Index': '-1'
				});
			}

		});
	});

};

PIXGRIDDER.pixgridderFirstInARow = function() {
	var pixgridder_css_selector = typeof pixgridder_css_selector !== 'undefined' ? pixgridder_css_selector : '.row .column',
		$window = $(window);

	var pixgridderFirstInARowCheck = function(){
		var elW = 0,
			$el = $(pixgridder_css_selector).filter(':notparents(.pix-letmebe)');
		$el.each(function(){
			var $t = $(this),
				pos,
				newPos,
				w = $window.width(),
				tW = $t.outerWidth();
			$t.removeClass('first-child');
			pos = $t.position();
			newPos = parseFloat(pos.left)+10;

			if ( $t.is(':first-child') ) {
				$t.attr('data-child','first');
				elW = 0;
			} else if ( newPos < elW ) {
				$t.addClass('first-child');
				elW = 0;
			}

			elW = elW + tW;
		});
	};
	pixgridderFirstInARowCheck();
	$window.on('resize',function(){
		pixgridderFirstInARowCheck();
	});
};

PIXGRIDDER.initPixElem = function() {
	var top = 0,
		delay = 0,
		start = 100,
		setDelay,
		pixgridder_css_selector = typeof pixgridder_css_selector !== 'undefined' ? pixgridder_css_selector : '.row .column',
		elems = jQuery('.pix-fadeIn, .pix-fadeDown, .pix-fadeUp, .pix-fadeLeft, .pix-fadeRight, .pix-zoomIn, .pix-zoomOut, .pix-rotateIn, .pix-rotateOut, .pix-flipClock, .pix-swing, .pix-turnBackward, .pix-turnForward').add(pixgridder_css_selector);

    $(elems).not(".pix-lazy-load").not(".pix-letmebe").filter(':notparents(.pix-letmebe)').pixGridderScrolledIntoView().on('scrolledin', function () {
		var $elem = $(this),
			opt = $elem.data('delay');
		$elem.addClass('pix-lazy-load');
		var newOff = $elem.offset(),
			newTop = newOff.top;
		if ( !$elem.hasClass('none') && !$elem.hasClass('bx-clone') ) {
			if ( typeof opt != 'undefined' && opt !== '' /*&& isNaN(parseFloat(opt))*/ ) {
				delay = parseFloat(opt);
			} else {
				if ( newTop != top ) {
					top = newTop;
					setDelay = 0;
				} else {
					setDelay = (setDelay+200);
				}
				delay = start+setDelay;
				$elem.attr('data-delay',delay);
			}
		}

		if(!Modernizr.csstransforms3d) {
			$elem.filter('.pix-flipClock').removeClass('pix-flipClock').addClass('pix-fadeDown');
			$elem.filter('.pix-swing').removeClass('pix-swing').addClass('pix-fadeDown');
			$elem.filter('.pix-turnBackward').removeClass('pix-turnBackward').addClass('pix-fadeRight');
			$elem.filter('.pix-turnForward').removeClass('pix-turnForward').addClass('pix-fadeLeft');
		}

		if ( !$elem.is('.none, .available, .pix-fadeIn, .pix-fadeDown, .pix-fadeUp, .pix-fadeLeft, .pix-fadeRight, .pix-zoomIn, .pix-zoomOut, .pix-rotateIn, .pix-rotateOut, .pix-flipClock, .pix-swing, .pix-turnBackward, .pix-turnForward') &&
			typeof pixgridder_fx !== 'undefined' ) {

			$elem.addClass(pixgridder_fx);

		}

		var elemClass = function(){
			$elem.addClass('pix-transended')
			.removeClass('pix-loaded')
			.removeClass('pix-fadeIn')
			.removeClass('pix-fadeDown')
			.removeClass('pix-fadeUp')
			.removeClass('pix-fadeLeft')
			.removeClass('pix-fadeRight')
			.removeClass('pix-zoomIn')
			.removeClass('pix-zoomOut')
			.removeClass('pix-rotateIn')
			.removeClass('pix-rotateOut')
			.removeClass('pix-flipClock')
			.removeClass('pix-swing')
			.removeClass('pix-turnBackward')
			.removeClass('pix-turnForward');
		}

		var addLoaded = function(){
			if(!Modernizr.cssanimations){
				$elem.not('.pix-loaded').addClass('pix-loaded-inanim');
				$('body').removeClass('pix-scroll-load');
			} else {
				$elem.addClass('pix-loaded');
				$elem.not('.pix-loaded').not('.available').not('.none').addClass('pix-loaded');
			}
			$elem.off('transitionend webkitTransitionEnd mozTransitionEnd oTransitionEnd');
			$elem.on('transitionend webkitTransitionEnd mozTransitionEnd oTransitionEnd', function(){
				setTimeout(elemClass, 1000);
			});
		};

		if ( !$elem.hasClass('none') && !$elem.hasClass('bx-clone') ) {
			setTimeout( addLoaded, delay);
		} else {
			elemClass();
		}
    });
};

PIXGRIDDER.init = function(){
	PIXGRIDDER.rotatingFrames();
	PIXGRIDDER.pixgridderParallax();
	PIXGRIDDER.pixgridderFirstInARow();
	PIXGRIDDER.initPixElem();
};

$(function(){
	PIXGRIDDER.init();
	$(window).trigger('resize');
});

$(window).on('pixgridder', function(){
	PIXGRIDDER.init();
	$(window).trigger('resize');
});

})(jQuery);