var mapi = ''; // menu scrollbar
var api = ''; // main content scrollbar
var originalHeight;

$(document).ready(function() {

	originalHeight = $('#menu-body').outerHeight();
	$(".email_form").submit(function(e) {
		e.preventDefault();
		// check for form completion
		$(':input', this).each(function(){
			if($(this).attr('name') == 'femail') {
				var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
				var femail = $(this).val();
				if(femail == '' || !emailReg.test(femail)) {
					// it is a bad email address
					alert('Please enter a valid email adress.');
					return false;
				}
			}
		});
		$.ajax({
			type: 'POST',
			url: '/request',
			data: $(this).serialize(),
			dataType: 'json',
			success: function(data) {
				if (data && data.success) {
					$('.fCancel').click();
					$('.img_overlay_info a').removeClass('sel');
					$('.img_overlay').hide();
					alert('Portfolio request sent.');
				} else {
					if (data && data.message) {
						alert('Could not send portfolio request. Please try again.');
					}
				}
				//window.setTimeout(5000, function() { $('#thankYouMessage, #errorMessage').hide(); });
			}
		});
		return false;
	});

	// navigation toggle
	$('.nav_title, .nav_artist').click(function() {
		var title = $(this),
				_d = title.attr('rel'),
				adjustMargin = function(height, vHeight){
						var newHeight = originalHeight + height - (vHeight ? vHeight : 0),
								menu = $('#menu'),
								menuBody = $('#menu-body'),
								jspContainer = $(".jspContainer",menuBody),
								menuHeight = menu.height();
						originalHeight = newHeight;
						if(newHeight > menuHeight){
							newHeight = menuHeight;
						}
						menuBody.animate({height:newHeight+'px'}, 'fast');
						jspContainer.animate({height: newHeight+'px' }, 'fast', function(){ $(window).trigger('resize'); });
				};
		if ($(this).hasClass('open')) {
			$(this).removeClass('open');
			adjustMargin(-$('#' + _d).outerHeight());
			$('#' + _d).slideUp('fast');
		} else {
			var visibleHeight = $('#menu-body ul:visible').outerHeight();
			resetNav();
			$(this).addClass('open');
			adjustMargin($('#' + _d).outerHeight(),visibleHeight);
			$('#' + _d).slideDown('fast');
		}
		return false;
	});

	$('a.link_share').hover(function() {
		$(this).animate({opacity: 1.0}, 200);
	}, function() {
		$(this).animate({opacity: 0.3}, 200);
	});

	$('a.link_request').hover(function() {
		if ($(this).hasClass('sel')) {
			// do nothing
		} else {
			$(this).animate({opacity: 1.0}, 200);
		}
	}, function() {
		$(this).animate({opacity: 0.3}, 200);
	});

	// share link
	$('a.link_share').bind('click', function() {
		if ($(this).hasClass('sel')) {
			$(this).siblings('.share_options').hide();
			$(this).removeClass('sel');
		} else {
			$(this).siblings('.share_options').show();
			$(this).addClass('sel');
			$(this).animate({opacity: 1.0});
		}
		return false;
	});
	
	// request link click
	$('a[rel^="portfolio_request"]').bind('click', function() {
		if ($(this).hasClass('sel')) {
			$(this).removeClass('sel');
			$(this).parent().siblings('.img_overlay_form').hide();
			$(this).parent().siblings('.img_overlay_con').show();
		} else {
			$(this).addClass('sel');
			$(this).parent().siblings('.img_overlay_con').hide();
			$(this).parent().siblings('.img_overlay_form').show();
		}
		return false;
	});
	
	// form cancel
	$('.fCancel').bind('click', function() {
		$(this).parent().parent().parent().parent().siblings('.img_overlay_con').show();
		$(this).parent().parent().parent().parent().siblings('.img_overlay_options').children('.link_request').removeClass('sel');
		$(this).parent().parent().parent().parent().hide();
		$(this).parent().parent().parent()[0].reset();
		return false;
	});

	$('form').bind('mousedown',function() {
		// do nothing
	});

	// body click for share/info
	$('body').bind('click', function(event) {
		if (event.target.nodeName == 'INPUT' || event.target.nodeName == 'LABEL' || event.target.nodeName == 'TEXTAREA') {
			// do nothing
			//console.log(event.target.nodeName);
		} else {
			$('.img_overlay_info a').removeClass('sel');
			$('.img_overlay').hide();
		}
	});

	$.fn.imagesLoaded = function(callback){
		//Thanks https://gist.github.com/268257
		var elems = this.filter('img'),
				numOfElems = elems.length,
				blank = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
		elems.bind('load.imagesLoaded', function(e){
			$(e.currentTarget).closest('li').css({'display':'block'});
			if (--numOfElems <= 0 && e.target.src !== blank){ callback.call(elems,e.target); elems.unbind('load.imagesLoaded'); }
		}).each(function(index, e){
			// cached images don't fire load sometimes, so we reset src.
			if (e.complete || e.complete === undefined){
				var src = e.src;
				// webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
				// data uri bypasses webkit log warning (thx doug jones)
				e.src = blank;
				e.src = src;
			}
		});
		return this;
	};

	$('#menu .nav_controls a').bind('click', function(e){
		if($('#resize-loading').is(':visible')){
			return false;
		}

		var $this = $(this),
				colors = {'expanded': '#000', 'normal': '#9E8E7E'},
				singleImgs = $('#rightcol .asset_li.single img.img_photo'),
				spreadImgs = $('.asset_li.v-spread > div'),
				srcMatch = new RegExp("(http:\\/\\/.*\\/).*_(.*.jpe?g)"),
				assetList = $('li.asset_li'),
				rightCol = $('#rightcol');

		$('#menu #imgs-loading').show();
		$('#resize-loading').show();
		assetList.css({'display':'none'});
		var resizeSingle = function(size){
			var $i = $(this),
					src = srcMatch.exec($i.attr('src')),
					$img = $i.clone(true);
			$img.css({maxWidth:$i.attr(size+'w')+'px'});
			$img.attr('src', src[1] + size + '_' + src[2]);
			$i.siblings('.img_photo_border').css({maxWidth:(parseInt($i.attr(size+'w'), 10)-2)+'px',maxHeight:$i.attr(size+'h')+'px'});
			$i.parent().css({maxWidth:$i.attr(size+'w')+'px',maxHeight:$i.attr(size+'h')+'px'});
			$i.replaceWith($img);
		}
		var resizeVSpread = function(size){
			var $container = $(this),
					$imgs = $('img.img_photo', $container),
					$i1 = $imgs.first(),
					$i2 = $imgs.last(),
					src1 = srcMatch.exec($i1.attr('src')),
					src2 = srcMatch.exec($i2.attr('src')),
					$img1 = $i1.clone(true),
					$img2 = $i2.clone(true),
					vSpreads = $('.v-spread-img', $container),
					fullWidth = (parseInt($img1.attr(size+'w'),10) + parseInt($img2.attr(size+'w'),10));
			$container.css({maxWidth:fullWidth+'px'});
			vSpreads.first().css({width: (parseInt($img1.attr(size+'w'),10) / fullWidth*100 - 0.5)+'%' });
			vSpreads.last().css({width: (parseInt($img2.attr(size+'w'),10) / fullWidth*100 - 0.5)+'%' });
			$img1.css({maxWidth:$img1.attr(size+'w')+'px'}).attr('src', src1[1] + size + '_' + src1[2]).closest('.v-spread-img');
			$img2.css({maxWidth:$img2.attr(size+'w')+'px'}).attr('src', src2[1] + size + '_' + src2[2]).closest('.v-spread-img');
			$i1.siblings('.img_photo_border').css({maxWidth:(parseInt($img1.attr(size+'w'),10)-2)+'px',maxHeight:$img1.attr(size+'h')+'px'});
			$i2.siblings('.img_photo_border').css({maxWidth:(parseInt($img2.attr(size+'w'),10)-2)+'px',maxHeight:$img2.attr(size+'h')+'px'});
			$i1.parent().css({maxWidth:$img1.attr(size+'w')+'px',maxHeight:$img1.attr(size+'h')+'px'});
			$i2.parent().css({maxWidth:$img2.attr(size+'w')+'px',maxHeight:$img2.attr(size+'h')+'px'});
			$i1.replaceWith($img1);
			$i2.replaceWith($img2);
			$img1.closest('.v-spread-img').css({maxWidth:$img1.attr(size+'w')+'px'});
			$img2.closest('.v-spread-img').css({maxWidth:$img2.attr(size+'w')+'px'});
		}

		//have to rebuild the jspane because you can't have it auto-reinit more than once.
		rightCol.data('jsp').destroy();
		$('#rightcol').jScrollPane({
			showArrows: false,
			verticalDragMinHeight: 24,
			verticalDragMaxHeight: 24,
			verticalDragMinWidth: 24,
			verticalDragMaxWidth: 24,
			autoReinitialise: true,
			autoReinitialiseDelay: 1000
		});
		$('img.img_photo:lt(3)').imagesLoaded(function(){ $('#resize-loading').hide(); });
		$('img.img_photo:gt(2)').imagesLoaded(function(){ $(window).trigger('resize',[true]);$('#menu #imgs-loading').hide(); });
		if($this.hasClass('expanded')){
			//contract
			$this.removeClass('expanded').css({"background-color": colors['normal']});
			if(assetList.first().hasClass('single')){ //depending on first image we need to initiate loading of that type first
				singleImgs.each(function(){ resizeSingle.call(this, 'gl'); }); //that way we can better estimate when to hide resize-loading
				spreadImgs.each(function(){ resizeVSpread.call(this, 'gl'); });
			} else {
				spreadImgs.each(function(){ resizeVSpread.call(this, 'gl'); });
				singleImgs.each(function(){ resizeSingle.call(this, 'gl'); });
			}
		} else {
			//expand
			$this.addClass('expanded').css({"background-color": colors['expanded']});
			if(assetList.first().hasClass('single')){ //depending on first image we need to initiate loading of that type first
				singleImgs.each(function(){ resizeSingle.call(this, 'gf'); }); //that way we can better estimate when to hide resize-loading
				spreadImgs.each(function(){ resizeVSpread.call(this, 'gf'); });
			} else {
				spreadImgs.each(function(){ resizeVSpread.call(this, 'gf'); });
				singleImgs.each(function(){ resizeSingle.call(this, 'gf'); });
			}
		}
		e.preventDefault();
	});
});

function setupScrollbars(autoReinitialize) {
	var menu = $('#menu'),
			menuBody = $('#menu-body');

	// initiate jscrollpane
	$('#rightcol, #bio').jScrollPane({
		showArrows: false,
		verticalDragMinHeight: 24,
		verticalDragMaxHeight: 24,
		verticalDragMinWidth: 24,
		verticalDragMaxWidth: 24,
		autoReinitialise: (autoReinitialize ? true : false),
		autoReinitialiseDelay: 1000
	});
	var api = $('#rightcol').data('jsp'),
			bapi = $('#bio').data('jsp');
	var throttleTimeout;

	menuBody.jScrollPane({
		showArrows: false,
		verticalDragMinHeight: 24,
		verticalDragMaxHeight: 24,
		verticalDragMinWidth: 24,
		verticalDragMaxWidth: 24
	});
	var mapi = menuBody.data('jsp');
	var throttleTimeout = false;

	var mheight = menu.height();
	if( mheight <= menuBody.height() ){
		menuBody.height(mheight);
	}

	// resize the portfolio width for resizing the imgs.
	$('#portfolio').width($(window).width() - 364);//safari was being a bit funny about image sizes, so this is here.
	if( $(window).data('events')['resize'] ){ return false; } //lets try not to bind this heavy logic twice.
	$(window).bind('resize', function(e, bypassTimeout) {
		if(bypassTimeout){
			var rightCol = $('#rightcol');
			//make sure this is the updated jspane, since we rebuild it on expand and contract
			api = $('#rightcol').data('jsp');
			if(api){
				$('img.img_photo').unbind('load.imagesLoaded');
				$('li.asset_li').css({'display':'block'});
				if( parseInt(rightCol.css('paddingBottom'),10) == 0 ){
					rightCol.css({paddingBottom:'1px'});
				} else {
					rightCol.css({paddingBottom:'0px'});
				}
				//we are auto reiniting while the images are loading.. needs to be removed when site is laoded.
				api.reinitialise({autoReinitialise: false});
			}
			if(bapi){
				bapi.reinitialise();
			}
			mapi.reinitialise();
		} else {
			if(throttleTimeout) { clearTimeout(throttleTimeout); }
			throttleTimeout = setTimeout(function(){
				if(api){
					api.reinitialise();
				}
				if(bapi){
					bapi.reinitialise();
				}
				mapi.reinitialise();
				var winWidth = $(window).width() - 330 - ((bapi && bapi.getIsScrollableV()) || (api && api.getIsScrollableV()) ? 30 : 0);//the sidemenu is 330 and the scrollbar
				$('#portfolio, #rightcol .jspPane').width(winWidth - 4);//for borders
				$('#bio .inner').width(winWidth);
			}, 225);
		}
		//hide resize loading
		$('#resize-loading').hide();
		// resize the portfolio width for resizing the imgs.
		var winWidth = $(window).width() - 330 - ((bapi && bapi.getIsScrollableV()) || (api && api.getIsScrollableV()) ? 30 : 0);//the sidemenu is 330 and the scrollbar
		$('#portfolio, #rightcol .jspPane').width(winWidth - 4);//for borders, //since resizing is throttled we still want the container to resize instantly.
		$('#bio .inner').width(winWidth);
		$('#blog').width(winWidth - 50);

		//resize menu
		mheight = menu.height();
		if(mheight <= menuBody.height()){
			menuBody.height(mheight);
			$('.jspContainer',menuBody).height(mheight);
			$('.jspContainer .jspTrack',menuBody).height(mheight);
		} else {
			menuBody.height(Math.min(originalHeight,mheight));
			$('.jspContainer',menuBody).height('100%');
			$('.jspContainer .jspTrack',menuBody).height('100%');
		}

		resizeCaption();
		resizeVideoCaption();
		resizeBlog();
	});
}

$(window).load(function() {
	$(window).trigger('resize',[true]);
});

function resetNav() {
	$('.nav_title').removeClass('open');
	$('.nav_category').slideUp('fast');
	$('.nav_artist').removeClass('open');
	$('.nav_albums').slideUp('fast');
}

function hideCaption() {
	$('.img_overlay').animate({opacity:0}, 0).hide();
	$('.link_overlay').removeClass('sel');
}

function resizeCaption() {
	$('.img_overlay:visible').each(function(){
		var that = $(this),
				parent = that.parent(),
				form = $('.img_overlay_form', parent),
				img = $('img.img_photo', parent),
				_width = img.width(),
				_height = img.height();
		that.css({'width':_width+'px','height':_height+'px'});
		form.width(_width - 30);
	});
}

function resizeBlog() {
	//watchout this function gets called in more places than the blog.
	var bwidth = $('#blog').width();
	if (bwidth < 800) {
		var _width = bwidth;
		$('#blog ul').width(bwidth);
	} else {
		var _width = 800;
		$('#blog ul').width(_width);
	}
	$('#blog .img_photo.video').each(function(e){
		var $this = $(this),
				$li = $this.closest('li'),
				_height = 533;
		$($li).width(_width).height(_height+21);
		var ovWidth = 800, ovHeight = 533;
		_height = (_width*ovHeight/ovWidth);
		$("> div", $this).css({width:_width+"px", height:_height+"px"});
		$li.css({width:_width+"px", height:(_height+21)+"px"});
		$('.img_overlay, .img_photo', $li).width(_width).height(_height);
		$('.img_photo_border', $li).width(_width - 2).height(_height - 2);
		$('.img_overlay_info', $li).width(_width);
		$('.img_overlay_form', $li).width(_width - 30);
	});
	$('img.image_photo').each(function(e) {
		var $this = $(this);
		/*
		if ($(this).height() < 500) {
			var _height = $this.height();
		} else {
			var _height = 500;
		}
		*/
		var _height = 500;
		var $li = $this.parent().parent().parent().parent().parent().parent().parent();
		$($li).width(_width).height(_height+21);
		$('.blogslides, .img_overlay, .img_photo, .blogslides table, .blogslides table td', $li).width(_width).height(_height);
		$('.img_photo_border', $li).width(_width - 2).height(_height - 2);
		$('.img_overlay_info', $li).width(_width);
		$('.img_overlay_form', $li).width(_width - 30);
	});
}

function resizeVideoCaption() {
	if (typeof video != 'undefined' && video == true) {
		$('.img_overlay').each(function(e) {
			var video_elem = $(this).siblings('.img_photo').children('div[id^="video"]');
			var _width = Math.round(video_elem.width());
			var _height = Math.round(video_elem.height());
			$(this).css({'width':_width+'px','height':_height+'px'});
			$(this).siblings('.img_photo').children('.img_photo_border').width(_width - 2).height(_height - 2);
		});
	}
}

function showOverlay() {
	var that = $(this),
			container = $(this).parent().parent(),
			img,
			overlay,
			overlayform,
			_width,
			_height;

	if ($(this).hasClass('sel')) {
		$(this).removeClass('sel');
		$(this).parent().siblings('.img_overlay').animate({opacity:0}, 0, function() {
			that.parent().siblings('.img_overlay').hide();
		});
	} else {
		img = $('img.img_photo', container);
		overlay = $('.img_overlay', container);
		overlayform = $('.img_overlay_form', container);
		_width = img.width();
		_height = img.height();

		overlay.css({'width':_width+'px','height':_height+'px'});
		overlayform.width(_width - 30);

		hideCaption();
		resizeCaption();
		resizeVideoCaption();
		$(this).addClass('sel');
		$(this).parent().siblings('.img_overlay').show();
		$(this).parent().siblings('.img_overlay').animate({opacity:1.0}, 0);
	}
	return false;
}

function resizeHomeSlideshow (runNow) {
	var onResize = function() {
		var $home = $('#home'),
			winWidth = $home.width();
			winHeight = $home.height();
		$('.slideshow, .slideshow ul, .slideshow ul li, .slideshow ul li table, .slideshow ul li table tbody, .slideshow ul li table td').width(winWidth).height(winHeight);
		$('.slideshow ul li table tbody td img').css({'max-width': winWidth, 'max-height': winHeight});
	};

	$(window).resize(onResize);
	if (runNow) {
		onResize();
	}
}

// home page functions
function home() {
	setupScrollbars();

	resizeHomeSlideshow(true);

	$('.slideshow ul').cycle({
		fx: 'fade',
		delay: 1000,
		speed: 1000,
		nowrap: 0,
		fit: 0,
		cycle: true,
		timeout: 2000,
		containerResize: 0,
		slideResize: 0,
		height: '100%',
		width: '100%'
	});
}

// portfolio page functions
function portfolio() {
	$('.nav_artist').addClass('open');

	//maybe this to help out slower connections
	//make scrollbars auto init when loading the images, then when initial loading is done, we can revert back to the regular scrollbar method
	$('img.img_photo:lt(3)').imagesLoaded(function(){ $('#resize-loading').hide(); });
	$('img.img_photo:gt(2)').imagesLoaded(function(){ $(window).trigger('resize',[true]); });
	setupScrollbars(true);

	// show img overlay (share/info)
	$('.link_overlay').bind('click', showOverlay);

	$(window).load(function() {
		resizeCaption();
		resizeVideoCaption();
	});
}

// about page functions
function about() {
	if(mapi){
		mapi.destroy();
	}
	setupScrollbars();
}

function bio() {
	$('.nav_artist').addClass('open');
	setupScrollbars();
}

// contact page functions
function contact() {
	//offsite links open in a new page auto-magically.
	$("a").filter(function() {
		return this.hostname && this.hostname !== location.hostname;
	}).attr('target', '_blank');

	if(mapi){
		mapi.destroy();
	}
	setupScrollbars();
}

// blog page functions
function blog() {
	$('#leftcol').addClass('blog');
	$('#n_news').prev().addClass('open');

	// show img overlay (share/info)
	$('.link_overlay').bind('click', showOverlay);

	resizeBlog();
	$(window).load(function() {
		resizeBlog();
		setupScrollbars();
	});
	setupScrollbars();
}

