var baseUrl = "http://mdff.ca/index.php/v1/";
var loadingHtml = "<h2>Loading</h2>";
var pageDominancePercent = 50;

/*
 * pageArray = an associative array mapping div ids to the page that should be loaded
 */
var pageArray = {
	'#home': 'home',
	'#updates': 'updates',
	'#filmography': 'filmography', 
	'#screenings' : 'screenings',
	'#about' : 'about',
	'#press' : 'press',
};

/*
 * divLoaded  is an array of which pages/sections have been loaded
 */
var divLoaded = {
	'#home' : false,
	'#updates' : false,
	'#filmography' : false,
	'#screenings' : false,
	'#about' : false,
	'#press' : false
}

/*
 * divLoading  is an array of which pages/sections are being loaded
 */
var divLoading = {
	'#home' : false,
	'#updates' : true,
	'#filmography' : false,
	'#screenings' : false,
	'#about' : false,
	'#press' : false
}

/*
 * sectionTitles - an array linking the div which is in a dominant position
 * on the page (60 percent of the page from the bottom up) to the title that
 * should be displayed in the h1 on the right.
 */
var sectionTitles = {
	'#home' : '#title-mdff',
	'#updates' : '#title-mdff',
	'#filmography' : '#title-filmography',
	'#screenings' : '#title-screenings',
	'#about' : '#title-about',
	'#press' : '#title-press',
	'#contact' : '#title-contact'
}



//===================================================================
// 
//===================================================================

var currentdiv;
var prevScroll = 0;
var scrollToOnStart = '';
var scrolledSinceJump = true;
var tempData = true;
var recentJumpTo = '';
var interrupted = false;


/*
 * Load handlers
 */
$(document).ready(function(){
	
	$('img.title').hide();
	$('#title-mdff').show();
	
	
	if ($('body').attr('id') !== 'archive') {
		window.currentdiv = '#updates';
		
		$(window).scroll(function(){
			checkScroll();
			checkDominantDiv();
			if (!window.scrolledSinceJump) {
				window.scrolledSinceJump = true;
			}
		});
		
		
		$.get(baseUrl + 'updates', function(data){
			$('#updates').html(data);
			divLoaded['#updates'] = true;
			divLoading['#updates'] = false;
			
			var hash = window.location.hash;
			
			setTimeout(function(){
				$('#menu ul li a[href=' + hash + ']').click();
			}, 500);
		});
		
		
		$('#menu ul li a').click(function(){
			var position = $($(this).attr('href')).position();
			window.recentJumpTo = $(this).attr('href');
			
			$(window).bind('mousewheel', function(event, delta){
				interruptAnimation(event, delta)
			});
			window.interruped = false;
			$('html, body').animate({
				scrollTop: position.top - 36
			}, 1000, function(){
				$(window).unbind('mousewheel');
				$('img.title').hide();
				$(window.sectionTitles[window.recentJumpTo]).show();
				moveTitle();
				window.currentdiv = window.recentJumpTo;
				
				setTimeout(function(){
					window.scrolledSinceJump = false;
					window.currentdiv = window.recentJumpTo;
					$('#title h1').text(window.sectionTitles[window.recentJumpTo]);
					moveTitle();
				}, 250);
			});
			
			$('#title h1 a').text(window.sectionTitles[$(this).attr('href')]);
			
			return false;
		});
		
	}
	
	
	$(window).resize(function(){
		moveTitle();
	});
	
	moveTitle();
	
	
	/*
	 * Activate sharing buttons
	 */
	$('a.shareUpdate').live('click', function(){
		var entryid = $(this).attr('rel');
		$(this).parent().append(
		'<span class="shareBox">'+
		'	<span><a href="http://twitter.com/home?status=http://mdff.ca/index.php/v1/entry/'+entryid+'">Twitter</a></span>'+
		'&nbsp;&nbsp;<span><a href="http://www.facebook.com/share.php?u=http://mdff.ca/index.php/v1/entry/'+entryid+'" target="_blank">Facebook</a></span>'+
		'&nbsp;&nbsp;<span><a class="closeShare" href="#">&times;</a></span>'+
		'</span>'
		);
		$(this).hide();
		$(this).parent().find('a.closeShare').click(function(){
			var parentElement = $(this).parent().parent().parent().parent();
			$(parentElement).find('a.shareUpdate').show();
			$(parentElement).find('span.shareBox').remove();
			return false;
		});
		return false;
	});
	
	$('a.shareFilm').live('click', function(){
		var entryid = $(this).attr('rel');
		$(this).parent().append(
		'<span class="shareBox">'+
		'	<span><a href="http://twitter.com/home?status=http://mdff.ca/index.php/v1/film/'+entryid+'">Twitter</a></span>'+
		'&nbsp;&nbsp;<span><a href="http://www.facebook.com/share.php?u=http://mdff.ca/index.php/v1/film/'+entryid+'" target="_blank">Facebook</a></span>'+
		'&nbsp;&nbsp;<span><a class="closeShare" href="#">&times;</a></span>'+
		'</span>'
		);
		$(this).hide();
		$(this).parent().find('a.closeShare').click(function(){
			var parentElement = $(this).parent().parent().parent().parent();
			$(parentElement).find('a.shareFilm').show();
			$(parentElement).find('span.shareBox').remove();
			return false;
		});
		return false;
	});
	
	$(window).keypress(function(e){
		if(e.which == 115){
			alert(window.scrolledSinceJump);
		}
	});
	
	$('#filmography a.play').live('click', function(){
		var embed1 = '<iframe src="http://player.vimeo.com/video/';
		var embed2 = '?autoplay=1&title=0&amp;byline=0&amp;portrait=0&amp;color=fff200" width="630" height="354" frameborder="0"></iframe>';
		$(this).parent().find('div.vimeoPlayer').html(embed1 + $(this).parent().find('span.vimeoVidId').html() + embed2).show();
		return false;
	});
	
});


$(window).load(function(){
	/*
	 * Adjust positioning of /entry and /film templates
	 */
	if($('#entry').length){
		if($(window).height() > $('#entry').height()){					//window bigger than entry content - reposition to center
			var newTop = Math.round(($(window).height()/2) - ($('#entry').height()/2)) + "px";
			$('#entry').css({
				'marginTop' : '0',
				'top' : newTop
			});
		}
		else{															// content bigger than window.  move to top +36px;
			$('#entry').css({
				'marginTop' : '0',
				'top' : '36px'
			});
		}
	}
});



function interruptAnimation(event, delta){
	$('html, body').stop(true, false);
	window.interruped = true;
	return false;
}


/*
 * Check if a new div has taken the dominant position on the page
 * Updated on scroll event
 */
function checkDominantDiv(){
	
	var distanceFromTopToBeDominant = ((100 - pageDominancePercent) / 100) * $(window).height();
	for (divid in window.pageArray) {
		if ($(divid).length) {
			var position = $(divid).position();
			
			/*
			 * Check that div top is above the 60% marker && bottom is still on screen (60% of the way down)
			 * Uses var pageDominancePercent to determine percentage
			 */
			if (calcDivDistance(divid) <= Math.round(distanceFromTopToBeDominant) 
				&& (position.top + $(divid).height()) > ($(document).scrollTop()+$(window).height()-distanceFromTopToBeDominant)) {		
				
				
				if(window.prevScroll < $(document).scrollTop()){								// Scrolling down
					if (calcDivDistance(divid) > calcDivDistance(window.currentdiv)) {
						$('img.title').hide();
						$(window.sectionTitles[divid]).show();
						moveTitle();
						window.currentdiv = divid;
					}
				}
				else if(window.prevScroll > $(document).scrollTop()){							// Scrolling up
					if (calcDivDistance(divid) < calcDivDistance(window.currentdiv)) {		
						$('img.title').hide();
						$(window.sectionTitles[divid]).show();
						moveTitle();
						window.currentdiv = divid;
					}
				}
				
			}
		}
	}
	window.prevScroll = $(document).scrollTop();
}


function calcDivDistance(div){
	var position = $(div).position();
	var topFromFrame = (position.top - $(document).scrollTop());
	return topFromFrame;
}


/*
 * checkScroll - updated on every scroll event to see if any new content should be loaded.
 * This happens when the div reaches the bottom of the window or higher
 */
function checkScroll(){
	for(divid in window.pageArray){
		if ($(divid).length) {
			var position = $(divid).position();
			
			/*
			 * Section about to enter frame; make an ajax request for the content
			 */
			var distanceFromScreenBottom = 150;			// The bigger the number, the further it can be from the bottom of the screen before loading
			if((position.top - ($(document).scrollTop()) - $(window).height()) < 200 && !divLoaded[divid] && !divLoading[divid]){
				divLoading[divid] = true;
				getRequest(window.baseUrl + window.pageArray[divid], divid);
				$(divid).html(window.loadingHtml);
			}
		}
	}
}


/*
 * getRequest(URL, params) - wrapper function to pass extra data
 * to the success handler
 */
function getRequest(myUrl, extradata) {
		$.ajax( {
	        type: "GET",
	        url:  myUrl,
	        success: function (data, textStatus, oHTTP){
				$(extradata).html(data);
				window.tempData = window.scrolledSinceJump;
				$(extradata).find('.moduleContainer').hide().fadeIn(400, function(){
					window.scrolledSinceJump = window.tempData;
					notifyLoaded();
					checkDominantDiv();
				});
				
				window.divLoading[extradata] = false;
				window.divLoaded[extradata] = true;
				
				notifyLoaded();
				checkDominantDiv();
			}  

         });
 }
 
 //messenger to inform a recent automated scroll it's now in the wrong spot.
 function notifyLoaded(){
 	setTimeout(function(){
	 	if(!window.interruped){
			position = $(window.recentJumpTo).position();
			
			$(window).bind('mousewheel', function(event, delta){ interruptAnimation(event, delta) });
			$('html, body').animate({
	        	scrollTop: position.top-36
			}, 400, function(){
				$(window).unbind('mousewheel');
				$('img.title').hide();
				$(window.sectionTitles[window.recentJumpTo]).show();
				moveTitle();
				window.currentdiv = window.recentJumpTo;
						
				setTimeout(function(){
					window.scrolledSinceJump = false;
					checkDominantDiv();
				},50);
			});
		}
		else{
			$('html, body').stop(true, false);
			window.interruped = true;	
		}
	},400);
 }
 
 
 function moveTitle(){
	var newTop = ($(window).height()/2) - 175;
 	$('img.title').css('top', newTop + 'px');
 }

 

