require( [ 'jquery', 'uri' ], function() {
require( '/includes/TouchEvents.js', function() {});

	bod = $('body');

	// Masthead Script
	$.widget( "cms.masthead", {

		options: {
			overlap: false,
			speed: 200,
			scrollCount: 1,
		},

		_create: function () {
			var path = new URI(window.location.href),
			anchor = path.Hash && path.Hash.split( '#' ).pop(),
			link = $('a[name="' + anchor + '"]'),
			grid = this;
			this.transitionEvent = this._whichTransitionEvent();
			this.scrollCount = ( this.options.scrollCount * 100 ) - 1;
			this.lastScroll = 0;

			// If overlap is false, pad the body tag to prevent the masthead from obscuring other elements
            if (!this.options.overlap) {
                this._setBuffer();
                setTimeout($.proxy(function() {
                    this._setBuffer();
                    // if we have an anchor link, animate to it
                    if ( anchor && link && link.length ) {
                        setTimeout( this._checkAnchor.apply( this, [link] ), 100 );
                    }
                }, this), 500);

                // reset the padding on a delayed resize
                $(window).onidle('resize', $.proxy(this._setBuffer, this), 250);
            }


			$( window ).on( 'scroll', $.proxy( this._checkScroll, this ) );

			// When clicking on a link that has an anchor
	        $( 'a[href*="#"]' ).on( 'click', function ( e ) {
	            var evt = $(e.target).is('a') ? e.target : e.currentTarget,
	            	target = new URI( evt.href ),
	                anchor = target.Hash,
	                link = $('a[name="' + anchor + '"]');
	            // Prevent the default events
	            e.preventDefault();
	            if ( path.Path == target.Path && link.length ) {
	                grid._checkAnchor.apply( grid, [link] );
	            } else {
	                window.location = evt.href;
	            }
	        } );
		},

		_setBuffer: function() {
            this.buffer = this.element.innerHeight();
            var mobBuffer = $('[data-mob-buffer]'),
                regBuffer = $('[data-banner]'),
                mobileMenu = $('.dd-mobile, .dd-panel.search'),
                main = $('main');

			main.css('padding-top', this.buffer);

		},

		_checkScroll: function () {
			var scrollTop = $( window ).scrollTop();
			if ( !$( 'html' ).hasClass( 'anchors' ) ) {
				if ( scrollTop > this.scrollCount ) {
					$('body').addClass( 'fixed' );
				} else {
					$('body').removeClass( 'fixed' );
				}
			}

			// Check to see whether we last scrolled up or down
			if ( this.lastScroll < scrollTop ) {
				$('html').addClass('down-scroll').removeClass('up-scroll');
			} else if ( this.lastScroll > scrollTop ) {
				$('html').removeClass('down-scroll').addClass('up-scroll');
			}
			// Set last scroll variable to current scroll for next time
			this.lastScroll = scrollTop;
		},

		_checkAnchor: function ( link ) {
			var offset = link.offset().top;
			if ( this.options.overlap ) {
				offset -= this.element.innerHeight();
			} else {
				offset -= (this.element.innerHeight() - this.buffer);
			}
				this._runScroll.apply( this, [offset] );
		},

		_runScroll: function ( offset ) {
			if ( offset < 500 ) {
				this.options.speed = 100;
			}
			$( 'html, body' ).animate( {
				scrollTop: offset
			}, this.options.speed , function () {
				$( 'html' ).removeClass( 'anchors' );
			} );
		},

		_whichTransitionEvent: function () {
			var t,
			el = document.createElement( "fakeelement" );
			var transitions = {
				"transition": "transitionend",
				"OTransition": "oTransitionEnd",
				"MozTransition": "transitionend",
				"WebkitTransition": "webkitTransitionEnd"
			};
			for ( t in transitions ) {
				if ( el.style[t] !== undefined ) {
					return transitions[t];
				}
			}
		}
	} );


	// Animate a simple counter, increasing a value from one number to another.
   $.fn.counter = function ( to, dur, fmt ) {
      var opt, from;

      // Validate inputs.
      if ( !this.length ) {
         return this;
      }

      // Kill any existing animations.
     // killDraw.apply( this, arguments );

      // Normalize the inputs.
      to = Make.Float( to );
      from = Make.Float( this.text() );
      dur = Make.Float( dur );
      fmt = fmt && $.isFunction( fmt ) ? fmt : Math.round;

      // If there's nothing to animate, set the end result immediately.
      if ( from === to || dur <= 0 ) {
         this[0].innerHTML = fmt( to );
         return this;
      }

      // Set the options.
      opt = {
         duration: dur,
         from: from,
         to: to,
         range: to - from,
         format: fmt,
         timing: $.draw.CubicBezier.get( 'ease' ),
         element: this[0]
      };

      // Start the animation.
      opt.interval = setInterval( function () {
         var         diff, percent, step, val,
                        drawTime = performance.now();

         if ( !opt.startTime ) {
                        // The first call is the start of the animation.
                        opt.startTime = drawTime;
                        return;
         }

         // Difference since start of animation.
         diff = Math.min( opt.duration, drawTime - opt.startTime );
         // Get the percent complete.
         percent = diff / opt.duration;
         // Using the timing function, get the current step as a percentage.
         step = opt.timing.get( percent );
         // Get the current value.
         val = opt.from + ( opt.range * step );

         // Update the displayed value in the counter.
         opt.element.innerHTML = opt.format( val );

         // If we're finished.
         //if ( percent === 1 ) {
                        // Clean up the draw function.
          //              killDraw.apply( $( opt.element ), [] );
        // }

      }, 1000 / 60 );

      // Save the animation data.
      this.eq( 0 ).data( 'ui.draw.opt', opt );

      return this;
   };

	// Basic show / hide to add and remove open/closed classes from the btn and the container.
	function simpleShowHide(btn, className, classSpot, classSpot2) {
		if ( !classSpot ) {
			classSpot = btn;
		}
		if ( !className ) {
			className = 'open';
		}

		classSpot.toggleClass(className);
		if ( classSpot2 ) {
			classSpot2.toggleClass(className);
		}
	}

	function mobileNav() {

		var menuBtn = $( '.menu-btn' );
		menuBtn.on( 'click', function(e) {
			e.preventDefault();
			simpleShowHide( $(this), 'mm-open', bod );

		} );


		// Call open / close function for the drop downs
		var panelBtn = $('.panel-btn');
		panelBtn.click(function(e) {
			e.preventDefault();
			var item = $(this);

			if ( item.is('.open') ) {
				panelBtn.removeClass('open');
			} else {
				panelBtn.removeClass('open');
				item.addClass('open');
			}
		});

		bod.addClass('mobile-ready');

	}


	// CHECKS TO SEE IF AN ITEM IS VISIBLE IN YOUR SCREEN
	function checkZones(zones) {
		// Grab our window top and bottom positions
		var wTop = $(window).scrollTop(),
			wBottom = wTop + $(window).height();

		// Run each zone through our function 1 by 1
		for (i = 0; i < zones.length; i++) {
			// Make sure we haven't already animated in
			if ( !zones.eq(i).is('.show') ) {

				// Get the current zone's top and bottom position.
				var height = zones.eq(i).outerHeight(),
				top = zones.eq(i).offset().top,
				bottom = top + zones.eq(i).height();

				// Check to see if our zone is in view
				// Increase the decimal to make it so less of the zone has to be in view before you add the class.
				if ( (bottom - (height * 0.3) <= wBottom) && (top + (height * 0.3) >= wTop) ) {

					// Add the show class to animate in
					zones.eq(i).addClass('show');

					// Check to see if we have any counters to call
					var counts = zones.eq(i).find( '.counter' );
					if ( counts.length ) {

						for (i = 0; i < counts.length; i++) {
							var item = counts.eq(i),
								duration = item.data('duration') || 750;
							item.counter( item.data('to'), duration, function(val){ return $.toInt(val)+item.data('sign') } );
						}

					}
				}
			}
		}
	}


	// Function to handles scrolling lists
    $.widget("cms.scrollingList", {

        options: {
            direction: 'vertical',
            count: 1,
            scroll: 'panel',
            breakpoints: {
                tabletLandscape: {
                    width: 1185,
                    count: 3
                },
                tabletPortrait: {
                    width: 785,
                    count: 2
                },
                mobile: {
                    width: 585,
                    count: 1
                }
            },
            infinite: true,
            nav: false,
            video: false,
            setHeights: false,
            autoAdvance: false
        },

        _create: function() {

            // get the total number of elements to be scrolled
            this.total = this.element.find("[data-role='item']").length;

            // Get the number of visible items based on the current window size
            this.groups = {
                count: this._detectViewport(this.options.breakpoints, this.options.count, this.total)
            };

            // If we don't have enough items to scroll, do nothing
            if (!this.groups.count) {
                return false;
            } else {
                // Record the total number of groups
                this.groups.total = Math.ceil(this.total / this.groups.count);
            }
            // Start sizing the elements
            setTimeout($.proxy(this._setup, this), 250);

            // Handle clicks on navigation elements
            this.element.on('click', $.proxy(this._handleMouse, this));

            // Handle Swipe Events
            this.element.on('swipeleft swiperight', $.proxy(this._handleSwipe, this));


            // Set up any additional thumbnail nav
            if (this.options.nav) {
                $.proxy(this._thumbNav(), this);
            }

            // Run auto advance, if needed
            if (this.options.autoAdvance) {
                $.proxy(this._autoAdvance, this);
            }
        },

        _setup: function() {
            var styleMode, styleFallback, styleProp;
            this.container = this.element.find("[data-role='container']");
            this.list = this.container.find("[data-role='list']");
            this.items = this.container.find("[data-role='item']");


            $.proxy(this._setSizing(), this);


            // Sets up the ability to cycle thought options infinitely
            if (this.options.infinite) {
                // Clone the existing list
                this.list.clone().insertAfter(this.list);
            }
            this.element.addClass('active start');

            this._index = 0;

            switch (this.options.scroll) {
                case 'panel':
                    this.scroll = this.groups.count;
                case 'single':
                default:
                    this.scroll = 1;
                    break;
            }
        },

        // Handle Swipe Events
        _handleSwipe: function(e) {
            if ( e.type === 'swipeleft' ) {
				this._next();
            } else if ( e.type === 'swiperight' ) {
				this._prev();
            }
        },

        // Handle Mouse Events
        _handleMouse: function(e) {
            var target = $(e.originalEvent.target),
                index;
            if ( target.parents( '.minus' ).length ) {
				var target = target.parents( '.minus' );
            }

            if (target.data('role') == 'nav' ) {
                switch (target.data('direction')) {
                    case 'next':
                        this._next();
                        break;
                    case 'prev':
                        this._prev();
                        break;
                }

                if (target.data('index') !== undefined) {
                    if ( target.is( '.minus' ) ) {
						index = target.data('index') - 1;
                    } else {
						index = target.data('index');
                    }
                }

                if (index !== undefined) {
                    this._moveTo.apply(this, [index]);
                }
            }
        },

        _next: function() {
            index = this._index + this.scroll;
            this._moveTo.apply(this, [index]);
        },

        _prev: function() {
            index = this._index - this.scroll;
            this._moveTo.apply(this, [index]);

        },

        _moveTo: function(index) {
            var distance;

            // Make sure our index is within the amount of items we have
            if (index + this.groups.count >= this.total) {
                index = this.total - this.groups.count;
                this.element.addClass('end').removeClass('start');
            } else if (index <= 0) {
                index = 0;
                this.element.addClass('start').removeClass('end');
            } else {
                this.element.removeClass('start end');
            }

            // Calculate the distance to move
            if (this.options.scroll == 'panel') {
                distance = (this.groups.size * index) * -1;
            } else {
                distance = (this.items.size * index) * -1;
            }

            // If the browser supports transforms, take advantage of it
            if (Modernizr && Modernizr.csstransforms) {
                // Set the translate to the percentage * the index of how many we are moved
                this.list.css('transform', this.styles.move + '(' + distance + '%)');
            }
            // Otherwise, use the appropriate fallback
            else {
                // Set the margin-left to the percentage * the index of how many we are moved
                this.list.css(this.styles.fallback, distance + '%');
            }

            if ( this.list.parent( '.timeline-nav' ) ) {
				this.list.find('.minus').removeClass('active').filter("[data-index='" + (index + 1) + "']").addClass('active');
            }

            if (this.options.nav) {
                this.nav.find('span').removeClass('active').filter("[data-index='" + index + "']").addClass('active');
            }

            this._index = index;
        },

        _thumbNav: function() {
            this.nav = this.element.find("nav[data-role='thumbs']");
            for (var i = 0; i < this.groups.total; i++) {
                this.nav.append('<span data-role="nav" data-index="' + (i * this.groups.count) + '">');
            }
            this.nav.find('span').first().addClass('active');
        },

        // Set sizing
        _setSizing: function() {
            switch (this.options.direction) {
                case 'vertical':
                    // Get the height of the largest item or group of items in the list
                    if (this.options.scroll == 'panel') {
                        this.container.size = this._maxHeight(this.items, this.groups.count);
                    }

                    this.styles = {
                        prop: 'height',
                        move: 'translateY',
                        fallback: 'margin-top'
                    }

                    break;
                case 'horizontal':
                default:
                    this.container.size = this.container.innerWidth();

                    this.styles = {
                        prop: 'width',
                        move: 'translateX',
                        fallback: 'margin-left'
                    }
                    break;
            }

            this.list.size = (((this.container.size / this.groups.count) * this.total - this.container.size) / this.container.size + 1) * 100;
            this.items.size = ((this.list.size / this.total) / this.list.size) * 100;
            this.groups.size = this.items.size * this.groups.count;


            // If we are scrolling vertically, we need to do a little extra work
            if (this.options.direction == 'vertical') {
                // Set the height so that the overflow will work
                this.container.height(this.container.size);
            }

            // Set size of the list as a percentage of the container
            this.list.css(this.styles.prop, this.list.size + '%');

            // Set size of the items as a percentage of the list
            this.items.css(this.styles.prop, this.items.size + '%');
        },

        // Find out how many items we will be showing at once and see if we have enough items to active a scroller
        _detectViewport: function(breakpoints, desktop, count) {
            var win = $(window).width();

        	 // If we are above tabletLandscape width,
            if (win >= breakpoints.tabletLandscape.width &&
                // and there are enough items to fill more than one group
                count > desktop) {
                // Set up desktop version
                return desktop;
            }

            // If we are above tablet portrait width
            else if (win >= breakpoints.tabletPortrait.width &&
                // and below tablet landscape width
                win <= breakpoints.tabletLandscape.width &&
                // and there are enough items to fill more than one group
                count > breakpoints.tabletLandscape.count) {
                // set up the tabletLandscape version
                return breakpoints.tabletLandscape.count;
            }

            // If we are above mobile width
            else if (win >= breakpoints.mobile.width &&
                // and below table width
                win <= breakpoints.tabletPortrait.width &&
                // and there are enough items to fill more than one group
                count > breakpoints.tabletPortrait.count) {
                // set up the tabletPortrait version
                return breakpoints.tabletPortrait.count;
            }

            // If we are below mobile width
            else if (win <= breakpoints.mobile.width &&
                // and there are enough items to fill more than one group
                count > breakpoints.mobile.count) {
                // set up mobile
                return breakpoints.mobile.count;
            }
            // we don't need to start, return false and quit
            else {
                return false;
            }
        },

        // Find max height of scrollable elements
        _maxHeight: function(items, group) {
            var heights = [];

            // Iterate through the slides and get the heights
            for (var i = 0; i < items.length; i++) {
                heights.push(items.eq(i).outerHeight());
            }

            // Get the tallest height
            return Math.max.apply(Math, heights);
        }
    });


	// One .ready to rule them all!!!
    $(document).ready(function() {

		// Call the masthead script
		$( '#HeaderZone' ).masthead();


		// Add ready class for load animation.
		bod.addClass('ready');


		// Call Simple Show/Hide on the services dropdown.
		var servBtn = $( '.service-btn' );
		servBtn.on( 'click', function() {

			simpleShowHide( servBtn, 'menu-open' );

		} );

		// Call Simple Show/Hide on the Sticky Zip Search.
		var searchBtn = $( '.search-btn' );
		searchBtn.on( 'click', function() {

			simpleShowHide( $(this), 'search-open', $(this).closest( '.sticky-zip-finder' ) );

		} );


		// Setup for pull out nav if we are in range
		if ( document.documentElement.clientWidth <= 985 ) {
			//mobileNav();
		}


		var test = $('.testimonial-area');
        if ( test.find('.container').length ) {

			test.scrollingList({
				direction: 'horizontal',
				count: 1,
				scroll: 'single',
				breakpoints: {
					tabletLandscape: {
						width: 1185,
						count: 1
					},
					tabletPortrait: {
						width: 785,
						count: 1
					},
					mobile: {
						width: 585,
						count: 1
					}
				},
				nav: true,
				autoAdvance: false,
				infinite: false
			});

        } else {
			test.remove();
        }

		var instagram = $('.instagram-area');
        if ( instagram.find('.container ul').length ) {
			instagram.scrollingList({
				direction: 'horizontal',
				count: 3,
				scroll: 'single',
				breakpoints: {
					tabletLandscape: {
						width: 1185,
						count: 3
					},
					tabletPortrait: {
						width: 785,
						count: 2
					},
					mobile: {
						width: 585,
						count: 1
					}
				},
				nav: true,
				autoAdvance: false,
				infinite: false
			});
        } else {
			instagram.remove();
        }

        //Phone Number Formatting for the forms
        (function( factory ) {
			if ( typeof rrequire === "function") {
				rrequire( ["j/jquery"], factory);
			} else {
				factory( jQuery, window );
			}
		} (function( $, scope ) {
			var phoneInput = $( '.phone-mask' );
			phoneInput.on( 'input', function() {
				if ( this.value && this.value.match(/\d+/g) ) {
					this.value = this.value
						.match(/\d*/g).join('')
						.replace(/(\d{0,3})(\d{0,3})(\d{0,4})/, '($1) $2-$3')
						.replace(/-*$/g, '')
						.substring(0, 14);

					if ( this.value.length <= 6 ) {
						var cursorIndex = this.value.indexOf( ')');
						this.setSelectionRange( cursorIndex, cursorIndex );
					}
				} else {
					this.value = "";
				}
			});

			phoneInput.trigger( 'input' );
		}));




		// Manage Footer & Blog menu opening / closing for mobile
		if ( document.documentElement.clientWidth <= 635 ) {


			var colNav = $( '.footer-nav, .sys-nav.side-nav' ),
				list = colNav.find( 'ul' ),
				btn = colNav.find( '.more-btn' );

			list.slideUp();

			btn.on( 'click', function() {
				console.log('Click');

				// $(this).toggleClass( 'open' );
				// $(this).closest( 'nav' ).find( 'ul' ).slideToggle( 500 );

			} );

		}


        // Call Simple Show/Hide on the disclaimer.
		var disBtn = $( '.dis-btn' );
		disBtn.on( 'click', function() {

			simpleShowHide( disBtn, 'show', disBtn.closest( '.disclaimer' ) );

		} );


		// Call Simple Show/Hide on the testimonial system items.
		var testBtn = $( '.testimonial-system .testimonial-list' ).find( '.more-btn' );
		testBtn.on( 'click', function() {

			simpleShowHide( $(this), 'test-expand', $(this).closest( 'li' ), bod );

		});

		// Show/Hide the custom play button for the video
        var vid = $('.content-video .video');
        if (vid.length !== 0) {

            $('.content-video').on('click', function() {
                $(this).find('.video-play').hide();
            });
        }


		if ( !$( 'body' ).is( '.cms-admin' ) ) {

			// Remove Icon List if it's empty
			var iconList = $( '.content-icon-list' );
			if ( !iconList.find( 'li' ).children().length ) {
				iconList.remove();
			}


			// Remove Accolade list if it's empty
			var accoladeList = $( '.accolade-list' );
			if ( !accoladeList.find( 'li' ).children().length ) {
				accoladeList.remove();
			}
		}


		// Check video players to see if they have a source.
		var players = $( '.content-video .video' );

		for ( i = 0; i < players.length; i++ ) {

			if ( players.eq(i).attr('style').indexOf( 'display: none' ) < 0 ) {
				players.eq(i).addClass( 'no-video' );
			}

		}


		// Check Services for a selected page and group
		var path = window.location.pathname,
			sideNav = $( '.services-nav, .side-nav' );
		if ( sideNav.length ) {
			sideNav.find( "a[href='" + path + "']" )
				.parentsUntil( 'nav' )
				.filter( 'li' )
					.addClass( 'selected' );
		}


		// Get any .magic zones and make set our breakpoint
		var magic = {
			zones: $('.magic'),
			bP: 785
		};

		if ( magic.zones.length ) {
			// Initial check to see if anything is currently in view
			checkZones(magic.zones);
			// Delayed check in case the page moves around while things load.
			setTimeout( checkZones(magic.zones), 2000 );
		}


		// Resize Functions run through here
		$(window).onidle( 'resize', function() {
			// Setup for pull out nav if we are in range
			if ( document.documentElement.clientWidth < 985 && !bod.is( '.mobile-ready' ) ) {
				//mobileNav();
			}
		},150);


		// Scroll Functions... I AM YOUR FATHER!!!
        $(window).onidle('scroll', function(){

			// Run the visibility checking script on all magic zones
			if ( magic.zones.length > 0 ) {
				checkZones(magic.zones);
			}

		},300);


	} );
	 var videoScroller = $('.vid-area, .video-testi-scroller .box .video-testi-video');
        if ( videoScroller.find('.video-container').length ) {
            videoScroller.scrollingList({
                direction: 'horizontal',
                count: 1,
                scroll: 'single',
                breakpoints: {
					tabletLandscape: {
						width: 1185,
						count: 1
					},
					tabletPortrait: {
						width: 785,
						count: 1
					},
					mobile: {
						width: 585,
						count: 1
					}
				},
                nav: true,
                autoAdvance: false,
                infinite: false
            });
        } else {
			videoScroller.hide();
        }

        // Home Page Video
        $( '.video-container .vid-area-list li' ).on( 'click', function() {
				$( this ).addClass( 'playing' );
				$( this ).find('video').attr( 'controls', 'true' );
				$( this ).find('video').get(0).play();
        });
        $( '.vid-area .scroll-thumbs span' ).on( 'click', function() {
				$('.video-container .vid-area-list li' ).removeClass('playing');
				$('.video-container .vid-area-list li video' ).each(function(){
					$(this).get(0).pause();
				});
        });



        // Testimonial Button Move at 800 breakpoint
		var testBtn = $('.testimonial-area .btn');

		// Move the Testimonial Button if needed on ready
		$(document).ready(function() {
			var win = $(window).width();

			// Check for moving the regular button
			if ( (win <= 800) ) {
				testBtn.insertAfter('.testimonial-area .container');
				testBtn.addClass('moved');
			}

		});




} );
