/* ---------------------------------------------------------- 

Murray Fredericks Photography - main javascript document
Ben Watson + Brad Thomas, Deepend Sydney, 2010-2011

------------------------------------------------------------ */

///////////////////////////////////////////// VERTICALLY ALIGN MASTER CONTAINER FUNCTION
(function ($) {
	$.fn.vAlign = function(message) {
		return this.each(function(i){
		var ah = $(this).height();
		var ph = $(this).parent().height();
		//var ph = $(window).height();
		var mh = (ph - ah) / 2;
		$(this).css('margin-top', mh);
		});
	};
})($);
//
$(window).ready(function() {
	$('#master-container').vAlign();
});

//BROWSER DETECT, MINIFIED, SRC: http://www.tvidesign.co.uk/blog/CSS-Browser-detection-using-jQuery-instead-of-hacks.aspx
$(document).ready(function(){var a=navigator.userAgent.toLowerCase();$.browser.chrome=/chrome/.test(navigator.userAgent.toLowerCase());if($.browser.msie){$('body').addClass('browserIE');$('body').addClass('browserIE'+$.browser.version.substring(0,1))}if($.browser.chrome){$('body').addClass('browserChrome');a=a.substring(a.indexOf('chrome/')+7);a=a.substring(0,1);$('body').addClass('browserChrome'+a);$.browser.safari=false}if($.browser.safari){$('body').addClass('browserSafari');a=a.substring(a.indexOf('version/')+8);a=a.substring(0,1);$('body').addClass('browserSafari'+a)}if($.browser.mozilla){if(navigator.userAgent.toLowerCase().indexOf('firefox')!=-1){$('body').addClass('browserFirefox');a=a.substring(a.indexOf('firefox/')+8);a=a.substring(0,1);$('body').addClass('browserFirefox'+a)}else{$('body').addClass('browserMozilla')}}if($.browser.opera){$('body').addClass('browserOpera')}});



// BEGIN JQUERY DOCUMENT.READY
$(document).ready(function() {

	$('#master-container').vAlign();


////////////////////////////////////////////// MAIN NAV FUNCTIONS

//Fade in and out nav active states - NOTE: This function applies to main nav, sub nav and project specific sub nav
$('.main-nav a, .sub-nav a, .project-subnav a, .credit-link').not(".current").hover(
	function () {
		$(this).find('span').stop(true, true).animate({ 
	  	 opacity: 1
    }, 500 );
	},
	function () {
		$(this).find('span').stop(true, true).animate({ 
	  	 opacity: 0
    }, 500 );
	}
);

////////////////////////////////////////////// SUB NAV FUNCTIONS

//Adding active class to subnav container - this is used for rollout functions
$('#sub-nav-container').hover(
	function () {
		$(this).addClass('active');
	}, 
	function () {
		$(this).removeClass('active');
	}
);


//Trigger sub-nav on rollover
	$(".main-nav li.trigger").hover(function() {
		
		//alert('roll over');
		$('#sub-nav-container').addClass('active');
		
		
		setTimeout(function(){
      // do something
		if($('#sub-nav-container').hasClass('active')) {
				//code to be executed if condition is true
			$("#sub-nav-bg").animate ({
				top: 57
			}, 800, 'easeOutQuart'  );	
		
  		$("#sub-nav-container").animate ({
				top: 57
			}, 1000, 'easeOutQuart', function() {
				// Animation complete.
				subNavHide();
			});
		}
		else {
				//code to be executed if condition is false
				//alert('not active');
			}
			
		},400);
		
		
		
		
	}, 

	function () {
    $('#sub-nav-container').removeClass('active');
  }
		
	);
	
	
//Detecs if user still on subnav - if not, hides, if so loops function with delay
	function subNavHide(){
		setTimeout( function(){
		if ($("#sub-nav-container").hasClass('active')){
				//alert('still over');
				subNavHide();
		}
		else {
				//alert(' not over!');
					$("#sub-nav-bg").animate ({
						top: -15
						}, 1200, 'easeInQuart' );
					
					$("#sub-nav-container").animate ({
						top: -15
						}, 1000, 'easeInQuart', function() {
					// Animation complete.
					});
				};
		}, 250);
	};
	
	
////////////////////////////////////////////// PAUSE FLASH VIDEOS


function pauseVideo(videoID) {
		document.getElementById(videoID).pauseVideo();
		//alert(videoID);
}


$('.browserIE ul.project-subnav a').click(function() {

	if ($('ul.project-subnav a.documentary').hasClass('videoActive')){
		//code to be executed if condition is true
		pauseVideo("video1");
		$('ul.project-subnav a.documentary').removeClass('videoActive');
		
	} else if($('ul.project-subnav a.time-lapse').hasClass('videoActive')){
		pauseVideo("video2");
		$('ul.project-subnav a.time-lapse').removeClass('videoActive');
	
	} else {
		//code to be executed if condition is not true
//		$('ul.project-subnav a.documentary').removeClass('videoActive');
//		$('ul.project-subnav a.time-lapse').removeClass('videoActive');
		return true;
	}	

});

$('.browserIE a.documentary').click(function() {
		$(this).addClass('videoActive');
});	

$('.browserIE a.time-lapse').click(function() {
		$(this).addClass('videoActive');
});	
	

////////////////////////////////////////////// INIT PROJECT CONTENT PANELS


$(function() {
		if ( $('#main-content-container').hasClass('project') ){
			
				$("ul.project-subnav").tabs(".content-panels > div", {
					effect: 'fade',
					fadeOutSpeed: 1000,
					fadeInSpeed: 1000,
					onBeforeClick: function() {
							
						// Check for video elements, if true, pausing video elements
						// Two caveats:
						// - Does not resume after switching back.
						// - Does not work in anything that's using the Flash fallback, ie. IE
						var videos = ["One", "Two", "Three", "Four"];
						for (var idx in videos) {
							var video = $("#video"+videos[idx]);
							if (video.length > 0 && video[0].player != undefined
								&& video[0].player != undefined
								&& video[0].player.video != undefined
								&& video[0].player.video.pause != undefined)
							{
								video[0].player.pause();
							}
						}
						
						//If thumbs are active when user switches between content panels, they will remain active.
						//Thus, we hide them when the user navigates away from the photograpy tab 
						
						if ( $('a.photography').hasClass('current') ) {
							//If user is already on photography page, do nothing
						}
						
						else {
							
							//Resetting thumbnails display
							$('.thumbnail-container').css({'opacity' : '0'});								
							$('.thumbnail-container').removeClass('active');
							$('.thumbnails-link').removeClass('active');
							$('.scroller').css({'opacity' : '1'});	
							
						}
					}
			});
		}
	
		else {
			//Do nothing
		}
})




////////////////////////////////////////////// PROJECT THUMBS ROLLOVERS
$('.project-thumbnails a').hover (
	function () {
		$(this).stop(true, true)
			.animate({
				opacity: 1
			}, 500 );

		$('.project-thumbnails a').not(this).stop(true, true)
			.animate({
				opacity: 0.25
			}, 500 );
		},
	
	function () {
		$('.project-thumbnails a').stop(true, true).delay(50)
			.animate({
				opacity: 1
			}, 500 );		
		}
);


////////////////////////////////////////////// HIDE AND SHOW PROJECT THUMBS AND HIDE / SHOW SHARE LINKS- CALLED FROM a.thumbnails-link

function showThumbs(){
		$('.thumbnail-container').addClass('active');
		$('.thumbnail-container').css("z-index" , "100");
		$('.scroller').stop(true, true).animate({
				opacity: 0
				}, 1000, function() {
					$('.scroller').css("display" , "none");
				}); 
					
					$('.thumbnail-container').css("display" , "block");
					$('.thumbnail-container').stop(true, true).animate({
						opacity: 1
						}, 1000, function() {
							//Complete
				});
					
		//If user is on the media or new page, we need to show the number of articles
		if( $("#main-content-container").hasClass("media")) {
			showPagination();
		}
		else {
			//do nothing
		}
}

function hideThumbs(){
	
		$('.thumbnail-container').removeClass('active');				
		$('.scroller').css("display" , "block");
		$('.scroller').stop(true, true).animate({
				opacity: 1
				}, 1000, function() {
					//Complete
				}); 
																									
					$('.thumbnail-container').stop(true, true).animate({
						opacity: 0
						}, 1000, function() {
							$('.thumbnail-container').css("display" , "none");
							$('.thumbnail-container').css("z-index" , "1");
				}); 

		//If user is on the media or new page, we need to HIDE the number of articles
		if( $("#main-content-container").hasClass("media")) {
			hidePagination();
		}
		else {
			//do nothing
		}					
}


function hideShareLinks(){
	$('.share-container').fadeOut(1000);
}

function showShareLinks(){
	$('.share-container').fadeIn(1000);
}

function activateThumbs(){
	if ( $('.thumbnail-container').hasClass('active') ) {
		hideThumbs();
		showShareLinks();
	}
	else {
		showThumbs();
		hideShareLinks();
	}
}

//Binding hide thumbs to project title
$('h2.project-title').click(function(){
	if ( $('.thumbnail-container').hasClass('active') ) {
		hideThumbs();
		showShareLinks();
	}
	else {
		//showThumbs();
		//hideShareLinks();
		return false;
	}	
});



//Binding thumbnail functionality to thumbnails link - adding class when toggled
$('.thumbnails-link').click(function() {
	activateThumbs();
	if ( $(this).hasClass('active') ) {
		$(this).removeClass('active');
	}
	else {
		$(this).addClass('active');
	}
});

//When user clicks thumbnail image to select that thumb, hide the thumbs, show main image
$('.project-thumbnails a').click(function() {
	activateThumbs();
	$(".thumbnails-link").removeClass('active');
});



////////////////////////////////////////////// MEDIA PAGINATION FUNCTIONS

//Define page variables and force current page to display
var firstPage = 1;
var currentPage = 1;
var maxPages = $('#thumbs').children().size();
var pagination = currentPage + '  /  ' + maxPages;
var hash = window.location.hash;

//Default view, thumbnails visible;
$("#thumbs .current").css("opacity",1);
$('.article-indicator').html(pagination);
$('#media .scroller-indicator').hide();


//Show the pagination on the page (ie; 1/2)
function showPagination(){	
	//alert("showing");
	$('.article-indicator').show();
	$('.scroller-indicator').hide();
}

//Show the pagination on the page (ie; 1/2)
function hidePagination(){	
	//alert("showing");
	$('.article-indicator').hide();
	$('.scroller-indicator').show();	
}


//Hide currently visible page
function hideCurrentPage(){
	var currentPageElement = $("#thumbs .current");
	var nextPage = $("#thumbs .current").next(".page");

	currentPageElement.stop(true, true).animate({
				opacity: 0
				}, 1000, function() {
					currentPageElement.removeClass("current")
					currentPageElement.css("z-index", "1");
				});
  }

//Show next page
function showNextPage(){
	var nextPage = $("#thumbs .current").next(".page");
	hideCurrentPage();
	$('.article-indicator').html(pagination);
	nextPage.stop(true, true).animate({
				opacity: 1
				}, 1000, function() {
				nextPage.addClass("current")
				nextPage.css("z-index", "100");
  		});	
	}

//Show previous page
function showPrevPage(){
	var prevPage = $("#thumbs .current").prev(".page");
	hideCurrentPage();
	$('.article-indicator').html(pagination);
	prevPage.stop(true, true).animate({
				opacity: 1
				}, 1000, function() {
				prevPage.addClass("current")
				prevPage.css("z-index", "100");
  		});	
	}

//Jump forward 
function pageForward(){
	if(currentPage < maxPages) {
		currentPage++;
		showNextPage();
		$('.article-indicator').html(currentPage + '  /  ' + maxPages);
	}
	else {
		//alert("At page limit");
	}
}

//Jump backward 
function pageBackward(){
	if(currentPage > firstPage) {
		currentPage--;
		showPrevPage();
		$('.article-indicator').html(currentPage + '  /  ' + maxPages);
	}
	else {
		//alert("Already First page");
	}
}	
	

//Run pagination on page clicks
$('.media a.page-forward').click(function() {
	pageForward();
});

$('.media a.page-backward').click(function() {
	pageBackward();
});



////////////////////////////////////////////// SHARING FUNCTIONALITY

$(".share-container").hover(
  function () {
		$(this).stop(true, true).animate({
			width: 190
			}, 500)
  }, 
  function () {
		$(this).animate({
			width: 35
			}, 500)
  }
);



////////////////////////////////////////////// FACEBOOK AND TWITTER SHARING - BRAD THOMAS
function parse_url (str, component) {
    // Parse a URL and return its components
    //
    // version: 1009.2513
    // discuss at: http://phpjs.org/functions/parse_url    // +      original by: Steven Levithan (http://blog.stevenlevithan.com)
    // + reimplemented by: Brett Zamir (http://brett-zamir.me)
    // %          note: Based on http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
    // %          note: blog post at http://blog.stevenlevithan.com/archives/parseuri
    // %          note: demo at http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js    // %          note: Does not replace invaild characters with '_' as in PHP, nor does it return false with
    // %          note: a seriously malformed URL.
    // %          note: Besides function name, is the same as parseUri besides the commented out portion
    // %          note: and the additional section following, as well as our allowing an extra slash after
    // %          note: the scheme/protocol (to allow file:/// as in PHP)    // *     example 1: parse_url('http://username:password@hostname/path?arg=value#anchor');
    // *     returns 1: {scheme: 'http', host: 'hostname', user: 'username', pass: 'password', path: '/path', query: 'arg=value', fragment: 'anchor'}
    var  o   = {
        strictMode: false,
        key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],        q:   {
            name:   "queryKey",
            parser: /(?:^|&)([^&=]*)=?([^&]*)/g
        },
        parser: {            strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
            loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/\/?)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // Added one optional slash to post-protocol to catch file:/// (should restrict this)
        }
    };
        var m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
    uri = {},
    i   = 14;
    while (i--) {uri[o.key[i]] = m[i] || "";}
    // Uncomment the following to use the original more detailed (non-PHP) script
    /*
        uri[o.q.name] = {};
        uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
        if ($1) uri[o.q.name][$1] = $2;
        });        return uri;
    */

    switch (component) {
        case 'PHP_URL_SCHEME':            return uri.protocol;
        case 'PHP_URL_HOST':
            return uri.host;
        case 'PHP_URL_PORT':
            return uri.port;        case 'PHP_URL_USER':
            return uri.user;
        case 'PHP_URL_PASS':
            return uri.password;
        case 'PHP_URL_PATH':            return uri.path;
        case 'PHP_URL_QUERY':
            return uri.query;
        case 'PHP_URL_FRAGMENT':
            return uri.anchor;        default:
            var retArr = {};
            if (uri.protocol !== '') {retArr.scheme=uri.protocol;}
            if (uri.host !== '') {retArr.host=uri.host;}
            if (uri.port !== '') {retArr.port=uri.port;}            if (uri.user !== '') {retArr.user=uri.user;}
            if (uri.password !== '') {retArr.pass=uri.password;}
            if (uri.path !== '') {retArr.path=uri.path;}
            if (uri.query !== '') {retArr.query=uri.query;}
            if (uri.anchor !== '') {retArr.fragment=uri.anchor;}            return retArr;
    }
}
var oURLParts = parse_url( window.location );

function openTwitterShareWindow( sURL, sWindowName ) {
  window.open( 'http://twitter.com/share?url=' + encodeURIComponent( sURL ), sWindowName );
  return false;
}

function buildTwitterShareImageURL() {
  openTwitterShareWindow( window.location, 'twitterShare' );
  return false;
}

function buildTwitterShareVideoURL() {
  var sURL = oURLParts.scheme + '://' + oURLParts.host + oURLParts.path + '#documentary';
  openTwitterShareWindow( sURL, 'twitterVideoShare' );
  return false;
}

function buildFacebookShareImageURL() {
  var sCurrentURL = window.location;
  var sURL = '';
  var sImg = jQuery( '.scroller .images img:visible' );
  var sTitle = sImg.attr( 'alt' );
  var sImgSrc = sImg.attr( 'src' );
  sImgSrc = sImgSrc.replace( 'mainImages', 'thumbs' );

  // do we have explode in JS? ah yes, split!
  var sProt       = oURLParts.scheme;
  var sHost       = oURLParts.host;
  var aPathParts  = oURLParts.path.split( '/' );
  aPathParts.pop();

  // let's build the URL!
  sURL  = 'http://www.facebook.com/';
  sURL += 'sharer.php?s= 100';
  sURL += '&p[title]=Murray%20Fredericks,%20' + encodeURIComponent( sTitle );
  sURL += '&p[url]=' + encodeURIComponent( sCurrentURL );
  sURL += '&p[images][0]=' + sProt + '://' + sHost + aPathParts.join('/') + '/' + sImgSrc;
  sURL += '&p[summary]=' + encodeURIComponent( sTitle );

  window.open( sURL, 'facebookShare' );
  return false;
}

function buildFacebookShareVideoURL() {
  var sCurrentURL = '';
  var sVideo      = jQuery( '.video-js' );
  var sImg        = sVideo.attr( 'poster' );
  //var sTitle      = jQuery( '.video-js #video-img' ).attr( 'title' );
  var sTitle      = '';

  var sProt       = oURLParts.scheme;
  var sHost       = oURLParts.host;
  var aPathParts  = oURLParts.path.split( '/' );

  sCurrentURL     = oURLParts.scheme + '://' + oURLParts.host + oURLParts.path + '#documentary';
  aPathParts.pop();

  // is the poster image relative to our website?
  if( sImg.indexOf( 'http://' ) == -1 ) {
    sImg = sProt + '://' + sHost + aPathParts.join( '/' ) + '/' + sImg;
  }

  // let's build the URL
  sURL  = 'http://www.facebook.com/';
  sURL += 'sharer.php?s= 100';
  sURL += '&p[title]=Murray%20Fredericks';
  sURL += (sTitle.length > 0) ? ',%20' + encodeURIComponent( sTitle ) : '';
  sURL += '&p[url]=' + encodeURIComponent( sCurrentURL );
  sURL += '&p[images][0]=' + encodeURIComponent( sImg );
  sURL += '&p[summary]=' + encodeURIComponent( sTitle );

  window.open( sURL, 'facebookVideoShare' );
  return false;
}

jQuery( '#shareFacebookImage' ).click(function() {
  buildFacebookShareImageURL();
});
jQuery( '#shareTwitterImage' ).click(function() {
  buildTwitterShareImageURL();
});
jQuery( '#shareTwitterVideo' ).click(function() {
  buildTwitterShareVideoURL();
});
jQuery( '#shareFacebookVideo' ).click(function() {
  buildFacebookShareVideoURL();
});



////////////////////////////////////////////// HIDE SHOW VIDEO CONTROLS ON VIDEO ROLLOVER


$('.video-js-box').hover(
  function () {
    //on mouseOver
		$('.vjs-controls').animate({
	    	//top: '-35'
				opacity: 1
			}, 500, function() {
    // Animation complete.
	  });
		//alert('mouseover .video-js-box');
  }, 
  function () {
		$('.vjs-controls').animate({
	    	//top: '0'
				opacity: 0
			}, 500, function() {
    // Animation complete.
	  });
		
		//alert('mouseout .video-js-box');
  }
);


////////////////////////////////////////////// GALLERY THUMBNAIL PAGINATION

var thumbPageContainer = $('.thumbnail-container');
var thumbMaxPages = $('.thumbnail-container .project-thumbnails > .page').size();
var thumbCurPage = 1;

//alert('test pages');

if(thumbMaxPages <= 1 ){
		$('.thumbnail-container .thumb-backward, .thumbnail-container .thumb-forward,').css('display','none');
	} else {	
		//Do nothing
}




function hideThumbsCurrentPage(){
	$(thumbPageContainer).find('.current').animate({
		opacity: 0
	}, 500, function() {
		// Animation complete.
		$(thumbPageContainer).find('.current').removeClass('current');
		$(thumbPageContainer).find('.current').css('display','none');		
	});
};

function showThumbsNextPage(){
	var nextPage = 	$(thumbPageContainer).find('.current').next('.page');
	thumbCurPage ++;
	$(nextPage).css('display','block');		
	$(nextPage).animate({
		opacity: 1
	}, 500, function() {
		// Animation complete.
		$(nextPage).addClass('current');
		//alert(thumbCurPage);
	});
};

function showThumbsPrevPage(){
	thumbCurPage --;
	var prevPage = 	$(thumbPageContainer).find('.current').prev('.page');
	$(prevPage).animate({
		opacity: 1
	}, 500, function() {
		// Animation complete.
		$(prevPage).addClass('current');
		//alert(thumbCurPage);
	});
};


$('.thumbnail-container .thumb-backward').click(function() {
	if(thumbCurPage > 1 ){
		hideThumbsCurrentPage();
		showThumbsPrevPage();	
	}else{	
		return false;
	}
});

$('.thumbnail-container .thumb-forward').click(function() {
	if(thumbCurPage < thumbMaxPages ){
		hideThumbsCurrentPage();
		showThumbsNextPage();	
	}else{	
		return false;
	}	
});





}); // END JQUERY DOCUMENT.READY

////////////////////////////////////////////// IPAD SPECIFIC FUNCTIONS
function BlockMove(event) {
  // Tell Safari not to move the window.
event.preventDefault() ;
}




////////////////////////////////////////////// VERTICAL AND HORIZ. ALIGN ALL NEWS ITEM IMAGES AND COPY
$( window ).ready( function() {
  //var iCount = 0;
  $( '.vert-center-only' ).each(function() {
    //iCount++;
    $( this ).css( 'position', 'absolute' );

		// horizontal centering
    var h = $( this ).height(); 
    var div_h = $( this ).parent().height();
    $( this ).css( 'marginTop', Math.round((div_h - h) / 2) + 'px' );
	  
		// vertical centering
		if (!$(this).hasClass('.horiz-center-only')) {
				var w = $( this ).width();
				var div_w = $( this ).parent().width();
				$( this ).css( 'marginLeft', Math.round((div_w - w)/2) + 'px' );
			}
  });
})


////////////////////////////////////////////// RUN VERTICAL ALIGN FUNCTION ON RESIZE - WILL ALSO CENTER CONTENT
$(window).resize(function() {
	$('#master-container').vAlign();
});
	
	



