$(document).ready(function() {
	// --------------------------------------------------------------------------------
	// GLOBAL VARS
	// --------------------------------------------------------------------------------
	var $mainNavLinks = $('#branding nav li a[target!="_blank"]'),
	$worklink = $('.worklink'),
	$mediabox,
	$mediaboxBg,
	$mediaboxContent,
	$featuredVideoIframe = $('#featuredVideoIframe'),
	$featureVideoNavPrev = $('#featureVideoNavPrev'),
	$featureVideoNavNext = $('#featureVideoNavNext'),
	url,
	parent,
	windowHeight = $(window).height(),
	$content = $('#content'),
   	$navigation = $('.navigation-below'),
	position = 0,
	$external = $('a.external');
	
	$('body.blog').prepend('<div id="loader"></div>'); // Insert the loader div for works
	$('body').prepend('<div id="pageLoader"><img src="/wp-content/themes/mediabolaget/images/ajax-loader-small.gif"></div>'); // Insert the menu nav loader div
	
	// --------------------------------------------------------------------------------
	// MAIN NAVIGATION
	// --------------------------------------------------------------------------------
	// $mainNavLinks.click(function() {
	// 	$('#pageLoader').show();
	// 	var link = $(this).attr('href');
	// 	
	// 	setTimeout(linkAction,100);	
	// 	
	// 	function linkAction() {
	// 		window.location = link;
	// 	}
	// 	return false;
	// });
	// 
	$external.live('click', function( e ){
		e.preventDefault();
		window.open($(this).attr("href"),"newWindow");
	});
	

	// --------------------------------------------------------------------------------
	// MEDIABOX & WORKLINK
	// --------------------------------------------------------------------------------
	function mediabox() {
		// Checks to see if the mediabox exists, if it does: show it. If it doesn't, create it.
		if (!$('#mediabox').length) {
			// Append our mediabox divs to the DOM
			$('body').prepend('<div id="mediaboxBg"></div><div id="mediabox"><a href="#" id="mediaboxClose" title="Close this overlay box">Close</a><div id="mediaboxContent"></div</div>');
			$mediabox = $('#mediabox');
			$mediaboxBg = $('#mediaboxBg');
			$mediaboxContent = $('#mediaboxContent');
		} 
		
		// Launch the mediabox
		$('body').prepend('<div id="loader"></div>'); // Insert the loader div
		$('#loader').css('display','block').animate({
			// Show the loader to the user
			marginTop: '-50px',
			opacity : '1.0'
		}, 500, function() {
			
		});
		$mediaboxBg.fadeIn(700); 
		$mediabox.css('visibility','hidden').show(); // Display: block the mediabox so it begins loading the video, but keep it hidden from the user while showing the loader

		
		// Clicking the close button, or anywhere outside the box triggers the close function
		$('#mediaboxClose, #mediaboxBg').click(function(e) {
			e.preventDefault();
			mediaboxClose();
		});
		
		// Function for closing the box
		function mediaboxClose() {
			$mediabox.hide();
			$mediaboxBg.fadeOut();
			$mediaboxContent.empty();
			$('#loader').hide();
			
		}
	}

	// Worklink events live binded
	$worklink.live({
	  click: function(e) {
	    // do something on click
		e.preventDefault();
		mediabox();
		$mediaboxContent.empty();
		var url = $(this).attr('href'),
		parent = $(this).closest('.entry-content'),
		thumbnailImage = $(this).find('img');
		
		var thescrollTop = $(window).scrollTop();
		// Set variable to count pixels to the top, in order to position the mediabox correctly
		// if ( $.browser.msie && $.browser.version < 9 ) {
		// 			var thescrollTop = $('html').scrollTop();
		// 		} else {
		// 			var thescrollTop = $('body').scrollTop();
		// 		}
		$mediaboxContent.load(url+' #videobox', function() {
			// Content is loaded
			$('#loader').remove();
			$mediabox.css('visibility','visible').css('marginTop',thescrollTop + 'px');
			// If the video should be centered, figure out the heigh and add a margin
			// var mediaboxHeight = $('#mediaboxContent').height();
			// 	$mediabox.css('marginTop', '-'+mediaboxHeight / 2+'px');
		});
	  }
	});
	
	if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {
	   // You're on iOS, so we're not using the overlay
		$worklink.die();
		
		// Hide the address bar
		window.addEventListener('load', function(){
		setTimeout(scrollTo, 0, 0, 1);
		}, false);
	}
	
	// --------------------------------------------------------------------------------
	// INFINITE SCROLL
	// --------------------------------------------------------------------------------
	// $navigation.css('visibility','hidden');
	$content.infinitescroll({
			loading: {
				img : '/wp-content/themes/mediabolaget/images/ajax-loader-small.gif',
				msgText: ''
			},
	        navSelector  : 'nav.navigation-below',  // selector for the paged navigation 
	        nextSelector : 'span.nav-next a',  // selector for the NEXT link (to page 2)
	        itemSelector : '.post',     // selector for all items you'll retrieve
			animate : false,
			bufferPx: 100,
	        debug: false,
	        errorCallback: function() { 
				//$('#footer').removeClass('onFirst');
	          // fade out the error message after 2 seconds
	          $('#infscr-loading').css({'display':'none'});
			
	        }
	      },
	        function( newElements ) { 
				//$(this).masonry({ appendedContent: $(newElements) });
				//$(newElements).find('img').attr({'title':'','alt':''}); 
				
				// Update document height with tne new value
			}
			
		);
	
	// If there are no scrollbars, initiate a scroll to load more content
	$content.infinitescroll('scroll');
	
	
	// --------------------------------------------------------------------------------
	// RESIZE VIDEO & VIMEO
	// --------------------------------------------------------------------------------
	// By Chris Coyier & tweaked by Mathias Bynens
	
	if ( $.browser.msie && $.browser.version < 8 ) {
		// IE 7 or lower
		// alert('IE 7');
	
	} else {
		// Everybody else..
		
		$(function() {

				var vimeoPlayers = document.querySelectorAll('iframe'),
	                player;

	            for (var i = 0, length = vimeoPlayers.length; i < length; i++) {
	                player = vimeoPlayers[i];
	                $f(player).addEvent('ready', ready);
	            }

		        // Find all Vimeo videos
		        var $allVideos = $("iframe[src^='http://player.vimeo.com']"),

		            // The element that is fluid width
		            $fluidEl = $("body");

		        // Figure out and save aspect ratio for each video
		        $allVideos.each(function() {

		                $(this).data('aspectRatio', this.height / this.width)

		                        // and remove the hard coded width/height
		                        .removeAttr('height')
		                        .removeAttr('width');
		        });


				function addEvent(element, eventName, callback) {
	                if (element.addEventListener) {
	                    element.addEventListener(eventName, callback, false);
	                }
	                else {
	                    element.attachEvent(eventName, callback, false);
	                }
	            }


				function ready(player_id) {
					var player_id = 'featuredVideoIframe';
					// Keep a reference to Froogaloop for this player
	                var container = document.getElementById(player_id).parentNode.parentNode,
	                    froogaloop = $f(player_id);

	                /**
	                 * Adds listeners for the events that are checked. Adding an event
	                 * through Froogaloop requires the event name and the callback method
	                 * that is called once the event fires.
	                 */
						froogaloop.addEvent('finish', function(data) {

							if(featureVideoPosition < featureVideoArray.length-1){ // Iterate 1
								featureVideoPosition++;
							} else { // restarting
								featureVideoPosition = 0;
							}
							$($featuredVideoIframe).attr('src',featureVideoArray[featureVideoPosition]+'&api=1&player_id=featuredVideoIframe&autoplay=1');		
	                    });


	            }


		        // When the window is resized
		        // (debounced)

		        $(window).smartresize(function() {
					// console.log('resized');
		                var newWidth = $fluidEl.width();

		                // Resize all videos according to their own aspect ratio
		                $allVideos.each(function() {

		                        var $el = $(this);
		                        $el
		                                .width(newWidth)
		                                .height(newWidth * $el.data('aspectRatio'));

		                });

		        // Kick off one resize to fix all videos on page load
		        }).resize();


				

		});
		
		
		
	}
	

	
	// --------------------------------------------------------------------------------
	// DEBOUNCE WINDOW RESIZE
	// --------------------------------------------------------------------------------
	(function($,sr){

	  // debouncing function from John Hann
	  // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
	  var debounce = function (func, threshold, execAsap) {
	      var timeout;

	      return function debounced () {
	          var obj = this, args = arguments;
	          function delayed () {
	              if (!execAsap)
	                  func.apply(obj, args);
	              timeout = null; 
	          };

	          if (timeout)
	              clearTimeout(timeout);
	          else if (execAsap)
	              func.apply(obj, args);

	          timeout = setTimeout(delayed, threshold || 100); 
	      };
	  }
		// smartresize 
		jQuery.fn[sr] = function(fn){  return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };

	})(jQuery,'smartresize');
	
	
	// --------------------------------------------------------------------------------
	// FEATURED VIDEOS NAVIGATION
	// --------------------------------------------------------------------------------
	
	$($featureVideoNavNext).click(function(e) {
		e.preventDefault();
		var player_id = 'featuredVideoIframe';
		// Keep a reference to Froogaloop for this player
        var container = document.getElementById(player_id).parentNode.parentNode,
            froogaloop = $f(player_id);

		if(featureVideoPosition < featureVideoArray.length-1){ // Iterate 1
			featureVideoPosition++;
		} else { // restarting
			featureVideoPosition = 0;
		}
		$($featuredVideoIframe).attr('src',featureVideoArray[featureVideoPosition]+'&api=1&player_id=featuredVideoIframe&autoplay=1');

	});

	$($featureVideoNavPrev).click(function(e) {
		e.preventDefault();
		var player_id = 'featuredVideoIframe';
		// Keep a reference to Froogaloop for this player
        var container = document.getElementById(player_id).parentNode.parentNode,
            froogaloop = $f(player_id);

		if(featureVideoPosition > 0){ 
			featureVideoPosition--;
		} else { // go to the last one
			featureVideoPosition = featureVideoArray.length-1;
		}
		$($featuredVideoIframe).attr('src',featureVideoArray[featureVideoPosition]+'&api=1&player_id=featuredVideoIframe&autoplay=1');

	});
	
	

	// --------------------------------------------------------------------------------
	// MISC.
	// --------------------------------------------------------------------------------
	$i = 0;
	$('#content article section').each(function(i) {
		$i++;
		if ($i == 3) {
			$(this).addClass('last');  // For IE
			$i = 0;
		}
	});
	
	
	
	
	
});



