(function ($) {

	function openPoPup(clickHandle, contentHandle) {

	    $.fancybox($(contentHandle).html(), {
	        // width: 1154,
	        // minWidth: width, // not valid in v1.3.x but 2.x
	        // minHeight: height, // not valid in v1.3.x but 2.x
	        maxWidth: 1154,
	        maxHeight: 810,
	        autoScale: true,
	        transitionIn: 'none',
	        transitionOut: 'none',
	        hideOnContentClick: false,
	        'closeBtn' : false 
	    });
	}

    $(document).ready(function () {
    		$(document).on('click','.read-more-members', function () {
    			var contentPopup = $(this).closest('.holder');
    			var bgImg = contentPopup.css('backgroundImage');

    			openPoPup('#btnEditSummary', contentPopup);
    		});

        $(".wpcf7-file").attr('data-jcf', '{"buttonText": "ATTACH COVER LETTER & CV", "placeholderText": ""}');

        $(".filter select").change(function () {
            var fday = $("#select-day").val();
            var fclass = $("#select-class").val();
            var ffloor = $("#select-floor").val();
            if (fday == "") {
                $(".day-table").show();
            } else {
                $(".day-table").hide();
                $(".day-table." + fday).show();
            }
            if(fclass!=="" && ffloor==""){
                $(".day-table-row").hide();
                $(".day-table-row."+fclass).show();
            }
            if(fclass=="" && ffloor!==""){
                $(".day-table-row").hide();
                $(".day-table-row."+ffloor).show();
            }
            if(fclass=="" && ffloor==""){
                $(".day-table-row").show();
            }
            if(fclass!=="" && ffloor!==""){
                $(".day-table-row").hide();
                $(".day-table-row."+fclass+"."+ffloor).show();
            }
        });


        $("#menu li").each(function () {
            if ($(this).find('ul').length) {
                $(this).find('>a').append('<span class="drops"></span>');
            }
        });

        $("#menu").on('click', '.drops', function () {
            if ($(this).hasClass("actives")) {
                $(this).removeClass("actives").parent().next().slideUp();
            } else {
                $(this).addClass("actives").parent().next().slideDown();
            }
            return false;
        });
		$( ".members .holder" ).each(function(){
			$(this).append('<span class="opener"></span>');
		});

		$(window).on('scroll load',function() {
		    var scrollSite = $(document).scrollTop(),
		        elemToScroll = $('#header').next().offset().top;

		    if( elemToScroll < scrollSite ) {
		        $('#header').addClass('fixed-header');
		    } else {
		        $('#header').removeClass('fixed-header');
		    }

		});



		$(".team").on('click', '.opener', function () {
			if ($(this).hasClass("actives")) {
				$(this).removeClass("actives").parent().removeClass("actives");
			} else {
				$('.members .holder').removeClass("actives");
				$('.members .opener').removeClass("actives");
				$(this).addClass("actives").parent().addClass("actives");
			}
			return false;
		});
        $(".popup_link").fancybox({
            maxWidth: 1700,
            maxHeight: 940,
            fitToView: false,
            width: '80%',
            height: '99.5%',
            autoSize: false,
            closeClick: false,
            closeBtn: false,
            openEffect: 'elastic',
            closeEffect: 'elastic'
        });

        jcf.replaceAll();

        $('.text-slider ul').bxSlider({
            auto: true,
            controls: false,
            pager: false
        });

        $('.day-table table').each(function (index) {
            $(this).wrapAll('<div class="table-container-outer"><div class="table-container"></div></div>');
            $(this).parent().before('<div class="table-container-fade"></div>');
        });

        var isMobile = {
            hasTouch: function () {
                return 'ontouchstart' in document.documentElement;
            },
            Android: function () {
                return navigator.userAgent.match(/Android/i);
            },
            BlackBerry: function () {
                return navigator.userAgent.match(/BlackBerry/i);
            },
            iOS: function () {
                return navigator.userAgent.match(/iPhone|iPad|iPod/i);
            },
            Opera: function () {
                return navigator.userAgent.match(/Opera Mini/i);
            },
            Windows: function () {
                return navigator.userAgent.match(/IEMobile/i);
            },
            any: function () {
                return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
            },
            ismobi: function () {
                return navigator.userAgent.match(/Mobi/i);
            }
        };

        if ($('#map').length > 0) {
            function initialize() {
                var myLatlng = new google.maps.LatLng(amData.map.lat, amData.map.lng);
                var mapOptions = {
                    zoom: 17,
                    center: myLatlng,
                    scrollwheel: false,
                    draggable: isMobile.hasTouch(),
                    disableDoubleClickZoom: false
                }
                var map = new google.maps.Map(document.getElementById('map'), mapOptions);

                var marker = new google.maps.Marker({
                    position: myLatlng,
                    map: map,
                    title: amData.map.address
                });
            }
            google.maps.event.addDomListener(window, 'load', initialize);
        }

    });

    $(document).on('click', ".menu_trigger", function (e) {
        e.preventDefault()
        window.setTimeout(function () {
            if ($('.nav-bar').hasClass('clicked')) {
                $('.nav-bar').stop(true, true).animate({height: 'hide'}, 100);
                $('.nav-bar').removeClass('clicked');
                $('.menu_trigger').removeClass('clicked');
            } else {
                $('.nav-bar').stop(true, true).animate({height: 'show'}, 400);
                $('.nav-bar').addClass('clicked');
                $('.menu_trigger').addClass('clicked');
            }
        }, 400);
        return false;
    });

	$( window ).scroll(function() {
		if($('.nav-bar').hasClass('clicked')){
			$('.nav-bar').stop(true,true).animate({height:'hide'},100);
			$('.nav-bar').removeClass('clicked');
			$('.menu_trigger').removeClass('clicked');
		}
	});	

    $(window).load(function () {
        var contentWidth = $(window).innerWidth();
        $('.page-template-timetable #content').css('max-width', contentWidth - 30);
        $('.text-slider').css('max-width', contentWidth);
    });

    $(window).resize(function () {
        if ($(document).width() > 800) {
            $("#menu ul").attr('style', '');
            $(".nav-bar").attr('style', '');
            $(".nav-bar").removeClass("clicked");
            $('.menu_trigger').removeClass('clicked');
        }
        else {
            $(".nav-bar").removeClass("active");
            $('.menu_trigger').removeClass('clicked');
        }
        var contentWidth = $(window).innerWidth();
        $('.page-template-timetable #content').css('max-width', contentWidth - 30);
        $('.text-slider').css('max-width', contentWidth);
    });
//////////////////
	var hash;

	//scrollto when click to link
	$(".anchor-nav>a").click(function() {
	  var url = $(this).attr('href');
	  hash = url.substring(url.indexOf('#'));
	  return scrollto_with_hash(hash);
	});

	//scrollto when click to other link with hash
	hash = window.location.hash.replace('#', '');

	if (hash != '') {
	  hash = '#' + hash;
	  scrollto_with_hash(hash);
	  //return scrollto_with_hash(hash);
	}

	// vidth browser
	function viewport() {
		var e = window, 
				a = 'inner';

		if (!('innerWidth' in window )) {
			a = 'client';
			e = document.documentElement || document.body;
		}
		return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
	}
	// ----------vidth browser

	function scrollto_with_hash(hash) {

		if ($(hash).length) {

			if( !$('#header').hasClass('fixed-header') && viewport().width > 1024 ) {

				$('html, body').animate({
					scrollTop: $(hash).offset().top - 294
				}, 600);
				return false;

			} else if( !$('#header').hasClass('fixed-header') && viewport().width < 1025 && viewport().width > 558 ) {

				$('html, body').animate({
					scrollTop: $(hash).offset().top - 240
				}, 600);
				return false;

			} else if( !$('#header').hasClass('fixed-header') && viewport().width < 559 ) {

				$('html, body').animate({
					scrollTop: $(hash).offset().top - 235
				}, 600);
				return false;

			} else {

				$('html, body').animate({
					scrollTop: $(hash).offset().top - 120
				}, 600);
				return false;

			}
		}
	}

//////////////////
	// smooth anchor links
	function initAnchors() {
	  /* global SmoothScroll */

	  new SmoothScroll({
		extraOffset: 0,
		anchorLinks: '.anchor-nav a',
		activeClasses: 'link',
		wheelBehavior: 'ignore',
		animDuration: 800
	  });

	}

	/*!
	 * SmoothScroll module
	 */
	;
	(function($, exports) {
	  // private variables
	  var page,
		win = $(window),
		activeBlock, activeWheelHandler,
		wheelEvents = ('onwheel' in document || document.documentMode >= 9 ? 'wheel' : 'mousewheel DOMMouseScroll');

	  // animation handlers
	  function scrollTo(offset, options, callback) {
		// initialize variables
		var scrollBlock;
		if (document.body) {
		  if (typeof options === 'number') {
			options = {
			  duration: options
			};
		  } else {
			options = options || {};
		  }
		  page = page || $('html, body');
		  scrollBlock = options.container || page;
		} else {
		  return;
		}

		// treat single number as scrollTop
		if (typeof offset === 'number') {
		  offset = {
			top: offset
		  };
		}

		// handle mousewheel/trackpad while animation is active
		if (activeBlock && activeWheelHandler) {
		  activeBlock.off(wheelEvents, activeWheelHandler);
		}
		if (options.wheelBehavior && options.wheelBehavior !== 'none') {
		  activeWheelHandler = function(e) {
			if (options.wheelBehavior === 'stop') {
			  scrollBlock.off(wheelEvents, activeWheelHandler);
			  scrollBlock.stop();
			} else if (options.wheelBehavior === 'ignore') {
			  e.preventDefault();
			}
		  };
		  activeBlock = scrollBlock.on(wheelEvents, activeWheelHandler);
		}

		// start scrolling animation
		scrollBlock.stop().animate({
		  scrollLeft: offset.left,
		  scrollTop: offset.top
		}, options.duration, function() {
		  if (activeWheelHandler) {
			scrollBlock.off(wheelEvents, activeWheelHandler);
		  }
		  if ($.isFunction(callback)) {
			callback();
		  }
		});
	  }

	  // smooth scroll contstructor
	  function SmoothScroll(options) {
		this.options = $.extend({
		  anchorLinks: 'a[href^="#"]', // selector or jQuery object
		  container: null, // specify container for scrolling (default - whole page)
		  extraOffset: null, // function or fixed number
		  activeClasses: null, // null, "link", "parent"
		  easing: 'swing', // easing of scrolling
		  animMode: 'duration', // or "speed" mode
		  animDuration: 800, // total duration for scroll (any distance)
		  animSpeed: 1500, // pixels per second
		  anchorActiveClass: 'anchor-active',
		  sectionActiveClass: 'section-active',
		  wheelBehavior: 'stop', // "stop", "ignore" or "none"
		  useNativeAnchorScrolling: false // do not handle click in devices with native smooth scrolling
		}, options);
		this.init();
	  }
	  SmoothScroll.prototype = {
		init: function() {
		  this.initStructure();
		  this.attachEvents();
		},
		initStructure: function() {
		  var self = this;

		  this.container = this.options.container ? $(this.options.container) : $('html,body');
		  this.scrollContainer = this.options.container ? this.container : win;
		  this.anchorLinks = jQuery(this.options.anchorLinks).filter(function() {
			return document.getElementById(this.getAttribute('href').slice(1));
		  });
		},
		getAnchorTarget: function(link) {
		  // get target block from link href
		  var targetId = $(link).attr('href');
		  return $(targetId.length > 1 ? targetId : 'html');
		},
		getTargetOffset: function(block) {
		  // get target offset
		  var blockOffset = block.offset().top;
		  if (this.options.container) {
			blockOffset -= this.container.offset().top - this.container.prop('scrollTop');
		  }

		  // handle extra offset
		  if (typeof this.options.extraOffset === 'number') {
			blockOffset -= this.options.extraOffset;
		  } else if (typeof this.options.extraOffset === 'function') {
			blockOffset -= this.options.extraOffset(block);
		  }
		  return {
			top: blockOffset
		  };
		},
		attachEvents: function() {
		  var self = this;

		  // handle active classes
		  if (this.options.activeClasses && this.anchorLinks.length) {
			// cache structure
			this.anchorData = [];

			for (var i = 0; i < this.anchorLinks.length; i++) {
			  var link = jQuery(this.anchorLinks[i]),
				targetBlock = self.getAnchorTarget(link),
				anchorDataItem;

			  $.each(self.anchorData, function(index, item) {
				if (item.block[0] === targetBlock[0]) {
				  anchorDataItem = item;
				}
			  });

			  if (anchorDataItem) {
				anchorDataItem.link = anchorDataItem.link.add(link);
			  } else {
				self.anchorData.push({
				  link: link,
				  block: targetBlock
				});
			  }
			};

			// add additional event handlers
			this.resizeHandler = function() {
			  self.recalculateOffsets();
			};
			this.scrollHandler = function() {
			  self.refreshActiveClass();
			};

			this.recalculateOffsets();
			this.scrollContainer.on('scroll', this.scrollHandler);
			win.on('resize', this.resizeHandler);
		  }

		  // handle click event
		  this.clickHandler = function(e) {
			self.onClick(e);
		  };
		  if (!this.options.useNativeAnchorScrolling) {
			this.anchorLinks.on('click', this.clickHandler);
		  }
		},
		recalculateOffsets: function() {
		  var self = this;
		  $.each(this.anchorData, function(index, data) {
			data.offset = self.getTargetOffset(data.block);
			data.height = data.block.outerHeight();
		  });
		  this.refreshActiveClass();
		},
		refreshActiveClass: function() {
		  var self = this,
			foundFlag = false,
			containerHeight = this.container.prop('scrollHeight'),
			viewPortHeight = this.scrollContainer.height(),
			scrollTop = this.options.container ? this.container.prop('scrollTop') : win.scrollTop();

		  // user function instead of default handler
		  if (this.options.customScrollHandler) {
			this.options.customScrollHandler.call(this, scrollTop, this.anchorData);
			return;
		  }

		  // sort anchor data by offsets
		  this.anchorData.sort(function(a, b) {
			return a.offset.top - b.offset.top;
		  });

		  function toggleActiveClass(anchor, block, state) {
			anchor.toggleClass(self.options.anchorActiveClass, state);
			block.toggleClass(self.options.sectionActiveClass, state);
		  }

		  // default active class handler
		  $.each(this.anchorData, function(index) {
			var reverseIndex = self.anchorData.length - index - 1,
			  data = self.anchorData[reverseIndex],
			  anchorElement = (self.options.activeClasses === 'parent' ? data.link.parent() : data.link);

			if (scrollTop >= containerHeight - viewPortHeight) {
			  // handle last section
			  if (reverseIndex === self.anchorData.length - 1) {
				toggleActiveClass(anchorElement, data.block, true);
			  } else {
				toggleActiveClass(anchorElement, data.block, false);
			  }
			} else {
			  // handle other sections
			  if (!foundFlag && (scrollTop >= data.offset.top - 1 || reverseIndex === 0)) {
				foundFlag = true;
				toggleActiveClass(anchorElement, data.block, true);
			  } else {
				toggleActiveClass(anchorElement, data.block, false);
			  }
			}
		  });
		},
		calculateScrollDuration: function(offset) {
		  var distance;
		  if (this.options.animMode === 'speed') {
			distance = Math.abs(this.scrollContainer.scrollTop() - offset.top);
			return (distance / this.options.animSpeed) * 1000;
		  } else {
			return this.options.animDuration;
		  }
		},
		onClick: function(e) {
		  var targetBlock = this.getAnchorTarget(e.currentTarget),
			targetOffset = this.getTargetOffset(targetBlock);

		  e.preventDefault();
		  scrollTo(targetOffset, {
			container: this.container,
			wheelBehavior: this.options.wheelBehavior,
			duration: this.calculateScrollDuration(targetOffset)
		  });
		},
		destroy: function() {
		  if (this.options.activeClasses) {
			win.off('resize', this.resizeHandler);
			this.scrollContainer.off('scroll', this.scrollHandler);
		  }
		  this.anchorLinks.off('click', this.clickHandler);
		}
	  };

	  // public API
	  $.extend(SmoothScroll, {
		scrollTo: function(blockOrOffset, durationOrOptions, callback) {
		  scrollTo(blockOrOffset, durationOrOptions, callback);
		}
	  });

	  // export module
	  exports.SmoothScroll = SmoothScroll;
	}(jQuery, this));
//////////////////
})(jQuery);