/*
 * Piper Scripts File
*/

/*
 * Get Viewport Dimensions
 * returns object with viewport dimensions to match css in width and height properties
 * ( source: http://andylangton.co.uk/blog/development/get-viewport-size-width-and-height-javascript )
*/
function updateViewportDimensions() {
	var w=window,d=document,e=d.documentElement,g=d.getElementsByTagName('body')[0],x=w.innerWidth||e.clientWidth||g.clientWidth,y=w.innerHeight||e.clientHeight||g.clientHeight;
	return { width:x,height:y }
}
// setting the viewport width
var viewport = updateViewportDimensions();
/*
 * Throttle Resize-triggered Events
 * Wrap your actions in this function to throttle the frequency of firing them off, for better performance, esp. on mobile.
 * ( source: http://stackoverflow.com/questions/2854407/javascript-jquery-window-resize-how-to-fire-after-the-resize-is-completed )
*/
var waitForFinalEvent = (function () {
	var timers = {};
	return function (callback, ms, uniqueId) {
		if (!uniqueId) { uniqueId = "Don't call this twice without a uniqueId"; }
		if (timers[uniqueId]) { clearTimeout (timers[uniqueId]); }
		timers[uniqueId] = setTimeout(callback, ms);
	};
})();

// how long to wait before deciding the resize has stopped, in ms. Around 50-100 should work ok.
var timeToWaitForLast = 100;

function loadGravatars() {
  // set the viewport using the function above
  viewport = updateViewportDimensions();
  // if the viewport is tablet or larger, we load in the gravatars
  if (viewport.width >= 768) {
  jQuery('.comment img[data-gravatar]').each(function(){
    jQuery(this).attr('src',jQuery(this).attr('data-gravatar'));
  });
	}
} // end function

/*
 * Put all your regular jQuery in here.
*/
jQuery(document).ready(function($) {

//some mobile detection we can use later
	var isMobile = {
		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()); }
	};

	/* usage:
		if( isMobile.iOS() ) alert('iOS');
		if( isMobile.any() ) alert('Mobile');
	*/

	  /*
	   * Let's fire off the gravatar function
	   * You can remove this if you don't need it
	  */

	//loadGravatars();


	if( !$("html").hasClass("lt-ie9") ) {
		// STICKY HEADER
			/*
			var sticky = new Waypoint.Sticky({
				   element: $('.header')[0],
				   offset: '-0.1%' //just enough to turn it off
				})
			*/
			/*if(sticky){
				$("#content").addClass('sticky');
			}*/

		$('select.nice_select').niceSelect();

		$(window).bind("load resize",function() { //note, next time get to work with updateViewportDimensions()
				var wi = $(window).width(); 
				if (wi < 1024){
					$("#content.sticky").css({'margin-top' : '0'})
					$('.ocs-trigger.is-active').trigger('click');
				}
				if (wi >= 1024){
					var oheight = $('.header').outerHeight();
					$("#content.sticky").css({'margin-top' : oheight})
				}
				if (wi >= 768){
					//$('.tabs').height($('.content').outerHeight()+100);//as the positioned tabs don't affect the height of container
					$('.tabs .content').css({'display' : 'block', 'opacity' : '0'});
					$('.tabs .content.activeContent').css({'opacity' : '1'});
				}
				if (wi < 768){
					$('.tabs .content').css({'opacity' : '1', 'display' : 'none'});
					$('.tabs .listhead').removeClass('expanded').addClass('collapsed');
					$('.tabs').css({'height' : 'auto'});
					$('.tabs .content').css({'height' : 'auto'});

					// Sticky Header adjust for alert bar
					//var adj = $('.header').outerHeight();
					//$('#container.drop #banner').css( {"margin-top" : adj -1} );
				}

			});


			
		//- TABS
			$('.tabs .content').css({'display' : 'block'});
			/* Tab Switcher */
			var SwitchTabs = function(container, tabs, activeclass, tab) {   
			    var tabContainers = $(container + ' > div');
			    var index = 0;
			    var tabnum = (tab) ? parseInt(tab, 0) - 1 : 0;
			    tabContainers.filter(':eq(' + tabnum + ')').css({'display' : 'block','opacity' : '1'});

			    $(container + ' > ' + tabs).find('span').click(function() {
			        index = $(this).parent().index();
			        tabContainers.css({'opacity' : '0','z-index' :'-1'}).removeClass('activeContent').filter(':eq(' + index + ')').css({'opacity' : '1' , 'z-index' : '1','display' : 'block'}).addClass('activeContent');
			        $(container + ' ' + tabs + ' ' + ' span').removeClass(activeclass);
			        $(this).addClass(activeclass);
			        $('.tabs').height($('.activeContent').outerHeight()*1.1);
			    }).filter(':eq(' + tabnum + ')').click();
			};

			$(function() {
			    SwitchTabs('div.tabs', 'dl.tabnav', 'active', 1);
			});


		//- ACCORDIONS
			
			$('.accordions .content').hide();
			//$("#specs_tab").slideDown('slow'); //uncomment to show first block

			$('.tabs, .accordions').find('.listhead').click(function(){
		      //Expand or collapse this panel
		      $(this).next().slideToggle('slow').toggleClass('expanded');
		      $(this).toggleClass('expanded collapsed');

		      //Hide the other panels
		      $('.accordions .content, .tabs .content').not($(this).next()).slideUp('slow').toggleClass('expanded');
		      $('.accordions .listhead, .tabs .listhead').not($(this)).removeClass('expanded').addClass('collapsed');
		    });

			//add support for sidebar widgets in blog
			/*$('.widget_recent_entries ul, .widget_categories ul, .widget_archive ul').hide().addClass('content');
			$('.widget_recent_entries .widgettitle, .widget_categories .widgettitle, .widget_archive .widgettitle').addClass('listhead collapsed');
		    $('.widget').find('.listhead').click(function(){
		      $(this).next().slideToggle('slow').toggleClass('expanded');
		      $(this).toggleClass('expanded collapsed');
		      $('.widget .content').not($(this).next()).slideUp('slow').toggleClass('expanded');
		      $('.widget .listhead').not($(this)).removeClass('expanded').addClass('collapsed');
		    });*/

		    //Back to the regular accordions
		    $('.crushAll').click(function(){
		    	$('.accordions .listhead').removeClass('expanded').addClass('collapsed');
		    	$('.accordions .content').slideUp('slow').removeClass('expanded').addClass('collapsed');
		    });
		    $('.openAll').click(function(){
		    	$('.accordions .listhead').removeClass('collapsed').addClass('expanded');
		    	$('.accordions .content').slideDown('slow').removeClass('collapsed').addClass('expanded');
		    });


		//preload images
		$.preloadImages = function() {
		  for (var i = 0; i < arguments.length; i++) {$("<img />").attr("src", arguments[i]);}
		}
		//$.preloadImages("/wp-content/themes/themename/library/images/submenuBG.png");


		var $hamburger = $(".panelToggle");
		  $hamburger.on("click", function(e) {
		    $hamburger.toggleClass("is-active");
		    // Do something else, like open/close menu
		  });
		
		
		
		//set heights for photospace gallery
		//$( window ) .on("load resize", function() {		
			//thumbsHeight = $('ul.thumbs').outerHeight();
			//$(".photospace_res").css("padding-bottom", thumbsHeight+20)
		//});


		// Add wrapper for responsive iframes
		$('iframe').wrap( '<div class="embed-object"></div>' );

	}

	// set cookie example (js-cookies.js): 
	// Cookies.set('stickyClosed', 'setvisitor24', { expires: 1 });
	// php conditional: <?php if (!isset($_COOKIE["stickyClosed"])){#dosomething}?>


		// Basic responsive tables
		//$('table').basictable({breakpoint: 768,});


		/*var hasScrolled = false;
		//document.addEventListener("scroll", function(){ hasScrolled = true; });
		$( ".mmenu" ).scroll(function() {
  		hasScrolled = true;
  		console.log('Scrolled detected');
			});

			function flippendo(){
				$('mm-panel_opened').on('scroll', function(){ 
			        console.log('scroll happened');
			    	});
			}
			setTimeout(flippendo, 2000);
		 

		setTimeout(triggerScroll,2000);

		function triggerScroll(){
			if (hasScrolled) {
				console.log('user has already scrolled');
		  	$('.scroll_prompt a').fadeOut('slow');
		    return;
		  } else {
		  	
		  }
		}*/
		$('.scroll_prompt a').hide('fast');
		$(document).on('click', '.menuToggle', function(){
				$('.scroll_prompt a').show('fast');
				console.log('Click detected');
				function flippendo(){
						$('.scroll_prompt a').hide('fast');
					}
					setTimeout(flippendo, 10000);
		}); 
		
}); /* end of as page load scripts */


