var prev_id;
var curr_id;
var next_id;
var prev_url;
var curr_url;
var next_url;
var homepage_cnt = 0;
var homepage_speed = 4000;
var homepage_timer;
var url_paths = new Array();
var slideshow_images = new Array();
var current_hash = window.location.hash;
var folioTip = '<span class="navtip"><span class="navmsg">The still image portfolio of Jonathan Chapman Photography.<span>-></span></span></span>';
var motionTip = '<span class="navtip"><span class="navmsg">A rotating gallery of still + video based projects. Exploring an eclectic array of people and places. Take a moment to interact.<span>-></span></span></span>';
var archiveTip = '<span class="navtip"><span class="navmsg">An ever growing gallery of images; content derived from the things that inspire us. Explore these sets and check back often.<span>-></span></span></span>';
var blogTip = '<span class="navtip"><span class="navmsg"><i>Here & There, Yesterday & Today.</i>  The blog of Jonathan Chapman Photography.<span>-></span></span></span>';




$(document).ready(function() {
	init();	
});


function init() {	
	// get current url to determine section location
	url_paths = window.location.pathname.split( '/' ).clean("");
	var last = url_paths[url_paths.length-1];
	var second_last = url_paths[url_paths.length-2];
	var archive_detail = url_paths[url_paths.length-3];
	if (last == undefined){
		last = "";
	}
	
	if (last == 'portfolio'){
		setupPortfolio();
	}
	if (last == '' || last == "homepage_promo"){
		setupHomepage();
	}
	if (last == 'archive' || second_last == 'archive'){
		setupArchive();
	}
	if (last == 'motion'){
		setupMotion();
	}
	if (archive_detail == "archive"){
		setupArchiveDetail();
	}
	if (last == 'guestbook' || last == 'contact' || last == 'client-login'){
		setupPageTransitions(last);
	}
	
	
	// visit blog rollover
	$('#visitblog').hover(function(){
		$(this).css({'cursor' : 'pointer'});
		$(this).stop(true,true).animate({
			'top' : 0
			}, 300, 'easeOutQuad')
		}, function(){
			$(this).animate({
				'top' : -10
			}, 300, 'easeOutQuad')
	})
	$('#visitblog').click(function(e){
		e.preventDefault();
		var txturl = $(this).find('a').attr('href');
			//window.location = txturl;
			window.open(txturl, '_blank');
	});
	
	
	
	
	
	$(folioTip).appendTo('#navitem-portfolio');
	$(motionTip).appendTo('#navitem-motion');
	$(archiveTip).appendTo('#navitem-archive');
	$(blogTip).appendTo('#navitem-blog');
	
	var isiPad = navigator.userAgent.match(/iPad/i) != null;
	var isiPhone = navigator.userAgent.match(/iPhone/i) != null;
	if (isiPad==false && isiPhone==false){
		
		$('#navitem-motion, #navitem-archive, #navitem-portfolio, #navitem-blog').bind({
			mouseenter: function() {
				if(!$(this).hasClass('curr')) {
					var tip = $(this).find('.navtip');
					tip.stop(true,true).fadeIn("fast");
				}
			},
			mouseleave: function() {
				if(!$(this).hasClass('curr')) {
		 			var tip = $(this).find('.navtip');
					tip.fadeOut("fast");
				}
			}
		});
	}
		
	// ---------------------------------------
	//		contact page rollovers
	// ---------------------------------------
	
	if(document.getElementById('chapman-more')){
	
		var moreLinks = $('#chapman-more .col');
		
		moreLinks.hover(function(){
			$(this).css({'cursor' : 'pointer'});
			$(this).find('img').fadeTo(150,0.5);
			$(this).find('a').addClass('hoverme');
		}, function(){
			$(this).find('img').fadeTo(150,1.0);
			$(this).find('a').removeClass('hoverme');
		})
		moreLinks.click(function(e){
			e.preventDefault();
			e.stopPropagation();
			
			var linkItem = $(this).find('a');
			var linkURL = linkItem.attr('href');
			
			if(linkItem.hasClass('extlink')){
           	window.open(linkURL, '_blank');
			} else {
				window.location = linkURL;
			}
		});
	}
	
}

function setupMotion(){
	setupGridRollovers();
	setupArchiveLandingTransition();
}

function setupGridRollovers(){
	$('#thumbGrid .grid-col').bind({
		click: function() {
			var imgurl = $(this).find('.img').attr('href');
			window.location = imgurl;
			return false;
		},
		mouseenter: function() {
			var par = $(this);
			if (($(this).hasClass('grid-col'))) {
				var start_xPos = '90px';
				par.css({'cursor' : 'pointer'});
				par.find('div.overlay').stop(true, false).fadeTo(300, 1.0, function() { // callback
					if(par.hasClass('featureVid')) {
						start_xPos = '260px';
					}
					par.find('.overlay-link').animate({
						left : start_xPos
					}, 300, "easeOutQuad")
				});	
			}
		},
		mouseleave: function() {
			var par = $(this);		
			var pid = par.attr('id');
			var end_xPos = '170px';	
			par.find('.overlay').stop(true,false).fadeTo(300, 0.0, function(){
				if(par.hasClass('featureVid')) {
					end_xPos = '350px';
				}
				par.find('.overlay-link').animate({
					left : end_xPos
				}, 300, "easeOutQuad")
			});	
		}
	});
}

function setupArchive(){
	
	$('#setGrid .grid-col').bind({
		click: function() {
			var imgurl = $(this).find('.img').attr('href');
			window.location = imgurl;
			return false;
		},
		mouseenter: function() {
			$(this).find('img').fadeTo(300,0.5);		
		},
		mouseleave: function() {
			$(this).find('img').fadeTo(300,1.0);	
		}
	});
	
	// queue all
	$('#setGrid img').css({'opacity':0.0});
	//$('.grid-col').addClass('loadanim');
	
	var delay = 500;
	$('#setGrid img').each(function (index) {
		$(this).delay(delay).fadeTo(200, 1.0, function(){
			//$(this).closest('div').removeClass('loadanim');
		});
		delay += 30;
		
	});
	setupArchiveLandingTransition();
	setupGridRollovers();
}

function setupPortfolio(){

	// find current hash and fade out the portfolio thumb	
	$("#thumb-grid a.img").live('click', function(e){
		window.location.hash = "/" + $(this).find('img').attr('rel');
		return false;
	});
	
	// thumb grid
	var gridH = $('#thumb-grid').outerHeight();
	$('#thumb-grid').hide();
	$('.navdivide').hide();
	$('#sitenav').delay(500).animate({
		marginTop : '-=170px'
	}, 800, function(){
		$('#thumbContainer').animate({
			'height' : gridH + 'px'
		}, 800, 'easeOutQuad', function(){
			$('.navdivide').show();
			$('#thumb-grid').fadeIn();
		});
	}) // end thumb grid
	
	// prev/next nav
	$("#prevbtn").live('click', function(e){
		window.location.hash = "/" + $(this).attr('href');
		return false;
	});
	$("#nextbtn").live('click', function(e){
		window.location.hash = "/" + $(this).attr('href');
		return false;
	});
	$("#prevbtn").hide();
	$("#nextbtn").hide();
	// end prev/next nav
	

	$("#maincontent div.imgwrapper").prepend('<div id="topnotch"></div><div id="btmnotch"></div>');

	$("#maincontent div.imgwrapper").css({'padding':'0'});
	$("#maincontent div.imgwrapper img").hide();
	
	// listen for hash changes
	$(window).bind( "hashchange", function(e){
		var img = "";
		var url = window.location.hash.split('/');
		var result = $.map(url, function(n) {
        	return /(\#)/.test(n) ? null : n;
        });
		
		if (result.clean("").length > 0){ // there is a history
			current_hash = result[0];
			img = $("#thumb-grid a.img img[rel="+result[0]+"]").parent().attr('rel');
		} else { // no history - blank hash
			img = $("#thumb-grid a.img:first").attr('rel');
			current_hash = $("#thumb-grid a.img:first img").attr('rel');
		}
		// fade back current image
		$("#thumb-grid img").parent().fadeTo(300, 1.0);
		$("#thumb-grid img[rel="+current_hash+"]").parent().stop(true,true).fadeTo(300, 0.5);
		$('a#prevbtn, a#nextbtn').hide();
		
		try {
			$('a#prevbtn').unbind('mouseenter mouseleave');
			$('a#nextbtn').unbind('mouseenter mouseleave');
		} catch(err){}
		
		loadPortfolioImage(img);
	});
	
	$(window).trigger( "hashchange" );
  	// end history
  	//determinePreviousAndNext();
}

function setupTaglineRotation(){
	$("#home_tagline p").hide();
	$("#home_tagline").show();
	$("#home_tagline p:eq(0)").fadeIn().delay(2000).fadeOut();
	$("#home_tagline p:eq(1)").delay(3000).fadeIn().delay(2000).fadeOut();
	$("#home_tagline p:eq(2)").delay(6000).fadeIn(500, function(){
		$(this).delay(4000).fadeOut(500, function(){
			setupTaglineRotation();
		});
	});
}

function setupHomepage(){
	$("#maincontent div.imgwrapper").prepend('<div id="topnotch"></div><div id="btmnotch"></div>');
	// hide the content is js is enabled so there's no jumpy fade
	$("#maincontent div.imgwrapper").css({'padding':'0'});
	$("#maincontent div.imgwrapper img").hide();
	
	setupTaglineRotation();
	
	window.addEventListener('focus', function() {
	    // focused browser tab
	    clearInterval(homepage_timer); // setup autofade timer
		//homepage_timer = setInterval("loadImage()", homepage_speed);
	},false);
	
	window.addEventListener('blur', function() {
	    // unfocused browser tab
	    clearInterval(homepage_timer); // setup autofade timer
	},false);
	
	// push all of the extra images into an array
	slideshow_images = $("li.home_slideshow a").map(function() { return $(this).attr('href'); }).get();
	loadImage(); // load first image from array of homepage images
	clearInterval(homepage_timer); // setup autofade timer
	homepage_timer = setInterval("loadImage()", homepage_speed);
}

function loadImage(){
	loadPortfolioImage(slideshow_images[homepage_cnt]);
	homepage_cnt++;
	if(homepage_cnt >= slideshow_images.length){
		homepage_cnt = 0;
	}
}


function setupArchiveDetail(){
	$("#maincontent div.imgwrapper").prepend('<div id="topnotch"></div><div id="btmnotch"></div>');
	var container = $("#maincontent div.imgwrapper");
	var image = $("#maincontent div.imgwrapper img");
	var height = image.height();
	var width = image.width();
	image.hide();
	container.height(0);
	container.width(0);	
	container.animate({
		height : height,
		width : width
	}, 800, "easeOutQuad", function(){
		image.fadeIn(300, "easeOutQuad");
	});
	
	// setup ajax slideshow
	homepage_cnt = $("span#current").text()-1;
		
	slideshow_images = $("li.archive_slideshow a").map(function() { return $(this).attr('href'); }).get();
	$("#prevlink").hide();
	$("#nextlink").hide();
	
	$("#prevlink").live('click', function(){
		handlePrevEvent();
		return false;
	});
	$("#nextlink").live('click', function(){
		handleNextEvent();
		return false;
	});
	
	$("#btmnotch").css({ 'top' : height - 0 });
	$('#topnotch, #btmnotch').show();
	
	setupArchivePrevNext();	
}

function handlePrevEvent(){
	clearInterval(homepage_timer);
	homepage_cnt--;
	if (homepage_cnt < 0) homepage_cnt = 0;
	$("span#current").text(homepage_cnt+1);
	setupArchiveShowHide();
	loadPortfolioImage(slideshow_images[homepage_cnt]);
}

function handleNextEvent(){
	clearInterval(homepage_timer);
	homepage_cnt++;
	if (homepage_cnt > slideshow_images.length) homepage_cnt = slideshow_images.length;
	$("span#current").text(homepage_cnt+1);
	setupArchiveShowHide();
	loadPortfolioImage(slideshow_images[homepage_cnt]);
}

function setupArchiveShowHide(){
	$('a#prevbtn, a#nextbtn').hide();
	$('a#prevlink, a#nextlink').hide();
	
	try {
		$('a#prevbtn').unbind('mouseenter mouseleave');
		$('a#nextbtn').unbind('mouseenter mouseleave');
	} catch(err){}
	
	if (homepage_cnt > 0){
		$("a#prevlink").show();
		$("#prevbtn").show();
		$("#prevbtn").css({ opacity: 0.0 });
		$('#prevbtn').hover(
			function(){
				 window.clearTimeout(timeout);
				$(this).stop(true,false).fadeTo(350,1.0);
			},
			function(){
				$(this).fadeTo(350,0);
			}
		)
	}
	if (homepage_cnt < slideshow_images.length-1){
		$("a#nextlink").show();
		$("#nextbtn").show();
		$("#nextbtn").css({ opacity: 0.0 });
		$('#nextbtn').hover(
			function(){
				 window.clearTimeout(timeout);
				$(this).stop(true,false).fadeTo(350,1.0);
			},
			function(){
				$(this).fadeTo(350,0);
			}
		)
	}
	
}

function setupArchivePrevNext(){
	var imgFrame = $('.imgwrapper img');
	var height = imgFrame.height();
	var width = imgFrame.width();
	
	var yPos = (height/2)-25;
	var xPos = (width/2)+11;
	var oPos = 10;
	
	try {
		$('a#prevbtn').unbind('mouseenter mouseleave');
		$('a#nextbtn').unbind('mouseenter mouseleave');
	} catch(err){}
	try {
		$('a#prevbtn').die('click');
		$('a#nextbtn').die('click');
	} catch(err){}
	
	$("a#prevbtn").live('click', function(e){
		e.preventDefault();
		handlePrevEvent();
	});
	$("a#nextbtn").live('click', function(e){
		e.preventDefault();
		handleNextEvent();
	});	
	
	
	$('a#nextbtn').css({
		'background-position' : 'right ' + yPos + 'px',
		'top' : 10,
		'left' : xPos,
		'height' : height,
		'width' :  width/2
	});
	$('a#prevbtn').css({
		'background-position' : '0 ' + yPos + 'px',
		'top' : 10,
		'left' : oPos,
		'height' : height,
		'width' : width/2
	});
	
	setupArchiveShowHide();
}





function loadPortfolioImage(image_path){
	$('a#prevbtn, a#nextbtn').hide();
	// create new img element to push ajax loaded image into
	var imgLoad = $("<img />");
	imgLoad.attr("src", image_path);
	imgLoad.unbind("load");
		
	imgLoad.bind("load", function () {
		prepImageForResize(this, this.width, this.height);
	});
}

function prepImageForResize(image, width, height){
	var container = $("#maincontent div.imgwrapper");
	var old_image = $("#maincontent div.imgwrapper img");
	
	$("#maincontent div.imgwrapper").css({'padding':'10px 10px 50px'});
	old_image.fadeOut(300, "easeOutQuad", function(){
		container.animate({
			height : height,
			width : width
			}, 600, "easeOutQuad", function(){
				container.find('img').remove();
				container.prepend(image);
				$("#maincontent div.imgwrapper img").hide();
				
				$("#btmnotch").css({ 'top' : height - 1 });
				$('#topnotch, #btmnotch').show();
				$("#maincontent div.imgwrapper img").fadeIn(300, "easeOutQuad", determinePreviousAndNext);
			});
	});
}

function determinePreviousAndNext(){
	var img = $("#thumb-grid a.img img[rel="+current_hash+"]").parent().parent();
	
	curr_id = img.find('img').attr('rel');
	prev_id = img.prev().find('img').attr('rel');
	next_id = img.next().find('img').attr('rel');
	
	curr_url = img.find('a').attr('rel');
	prev_url = img.prev().find('a').attr('rel');
	next_url = img.next().find('a').attr('rel');
	
	var imgFrame = $('.imgwrapper');
	var height = imgFrame.height();
	var width = imgFrame.width();
	
	var yPos = (height/2)-25;
	var xPos = (width/2)+11;
	var oPos = 10;
	
	
	// tickmarks
	
	//container.prepend('<div id="topnotch"></div><div id="btmnotch"></div>');
	
	// position the prev arrow
	if (img.length != 0){ // if anywhere but the archive
		if (prev_id != undefined){
			var prevBtn = $('a#prevbtn').attr('href', prev_id);
			prevBtn = $('a#prevbtn').attr('rel', prev_url);
			$('a#prevbtn').css({
				'background-position' : '0 ' + yPos + 'px',
				'top' : 10,
				'left' : oPos,
				'height' : height,
				'width' : width/2
				});
			prevBtn.show();
			prevBtn.css({ opacity: 0.0 });
			prevBtn.hover(
				function(){
					 window.clearTimeout(timeout);
					$(this).stop(true,true).fadeTo(350,1.0);
				},
				function(){
					$(this).fadeTo(350,0);
				}
			)
		}
		
		// position the next arrow
		if (next_id != undefined){
			var nexBtn = $('a#nextbtn').attr('href', next_id);
			nexBtn = $('a#nextbtn').attr('rel', next_url);
			$('a#nextbtn').css({
				'background-position' : 'right ' + yPos + 'px',
				'top' : 10,
				'left' : xPos,
				'height' : height,
				'width' :  width/2
				});
			nexBtn.show();
			nexBtn.css({ opacity: 0.0 });
			nexBtn.hover(
				function(){
					 window.clearTimeout(timeout);
					$(this).stop(true,true).fadeTo(350,1.0);
				},
				function(){
					$(this).fadeTo(350,0);
				}
			)
		}
	} else { // you're in the archive detail
		//setupArchivePrevNext();
		setupArchivePrevNext();
	}
}

var timeout = window.setTimeout(function(){
    $('a#prevbtn,a#nextbtn').trigger('mouseout')
},100);


function setupPageTransitions(section){
	var outer = $("#maincontent .pgcontent");
	var elem_height = outer.height();
	
	var child_elements = outer.children().map(function() { return this; });
	child_elements.css({'display':'none'});
	
	outer.css({'height':'0'});
	outer.animate({
		height: elem_height
	}, 1000);
	
	var delay = 50;
	outer.children().each(function(index) {
		$(this).delay(delay).fadeIn(800);
		delay += 300;
	});
}

function setupArchiveLandingTransition(){
	var outer = $("#thumbGrid");
	
	var child_elements = outer.children('div.grid-col').map(function() { return this; });
	child_elements.css({'opacity':0.0});
		
	var delay = 200;
	child_elements.each(function(index){
		if (index > 30){
			$(this).css({'opacity':1.0});
		} else {
			$(this).delay(delay).fadeTo(400, 1.0);
			delay += 30;	
		}
		
		
	});
}



Array.prototype.clean = function(deleteValue) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == deleteValue) {         
      this.splice(i, 1);
      i--;
    }
  }
  return this;
};

