$.fn.slideFade = function(display, speed, easing, callback) {
	return $(this).animate({opacity: display, height: display}, speed, easing, callback);
}

$.fn.loadGallery = function(galleryid) {
	var container = this;
	$(container).html('');

	function imgLoad(img, completeCallback, errorCallback){
		if(img!=null && completeCallback!=null){
			var loadWatch = setInterval(function() {
				if(img.complete) {
					clearInterval(loadWatch);
					completeCallback(img);
				}}, 100);
		}else{
			if(typeof errorCallback=="function") errorCallback();
		}
	}

	function displayGallery() {
		$('> .loading-message', container).fadeOut('normal', function() {
			$('> #galleryWrapper',container).fadeIn('normal', function() {
				$('#'+galleryid, container).gallerySlideshow(5000,2000,5); // Start gallery slideshow
			});
		});
	}

	$.ajax({
		type: "GET",
		url: '/interface/components/gallery.php',
		data: 'gallery='+galleryid,
		beforeSend: function() {
			$(container).html('<div class="loading-message">Loading images&hellip;</div><div id="galleryWrapper"></div>');
			$('> #galleryWrapper', container).hide();
		},
		success: function(data) {
			$('> #galleryWrapper',container).html(data); // Insert gallery content into container element
		},
		complete: function() {
			var imgcount = 1;
			var imgtotal = $('.content-gallery-display img', container).length;
			$('> .loading-message', container).html('Loading image <span class="loading-message-current">'+imgcount+'</span>'+' of '+'<span class="loading-message-total">'+imgtotal+'</span>&hellip;')
			$('.content-gallery-display img', container).each(function(index) {
				imgLoad($(this)[0], function(img){
					$('.loading-message-current').html(imgcount);
					imgcount++;
					if(imgcount == imgtotal) {
						displayGallery();
					}
				});
			});
		}
	});
};

$.fn.gallerySlideshowNav = function(myid,timeout,speed) {
	// Paging function
	function gotoPage(page) {
		var dir = page < currentPage ? -1 : 1,
			n = Math.abs(currentPage - page),
			left = singleWidth * dir * visible * n;
	
		$('li.item'+highlight).animate({opacity:0.3},speed/8);
		$wrapper.filter(':not(:animated)').animate({
			scrollLeft : '+=' + left
		}, 500, function () {
		if (page == 0) {
			$wrapper.scrollLeft(singleWidth * visible * pages);
			page = pages;
		} else if (page > pages) {
			$wrapper.scrollLeft(singleWidth * visible);
			page = 1;
			$('li.item0', $slider).animate({opacity:0.3},speed/8);
		} 
		
		currentPage = page;
		if(page == pages) {
			highlight = 0;
		} else {
			highlight = page;
		}
		$('li.item'+highlight).animate({opacity:1},speed/8)
	
		init = false;
	  });                
	  
	  return false;
	}

	var $wrapper = $('> .content-gallery-nav', this),
		$slider = $wrapper.find('> ul'),
		$items = $slider.find('> li'),
		$single = $items.filter(':first'),
		// outerWidth: width + padding (adding margin value afterward)
		singleWidth = $single.outerWidth() + 4, 
		// note: doesn't include padding or border
		visible = 1; //Math.ceil($wrapper.innerWidth() / singleWidth), 
		currentPage = 0,
		highlight = 0,
		init = true,
		pages = Math.ceil($items.length / visible);
	
	// Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
	$items.filter(':first').before($items.slice(-2).clone().addClass('cloned'));
	$items.filter(':last').after($items.slice(0, 4).clone().addClass('cloned'));
	$items = $slider.find('> li'); // reselect
	$items.slice(-visible);

	// Fade back all items, highlight first item, remove active item class
	$('li:not(.item0)', $slider).animate({opacity:0.3},0);
	$('li.item0', $slider).removeClass('content-gallery-active-item');
	
	// Add navigation buttons, fade back initially
	$wrapper.after('<a id="'+myid+'Prev" class="content-gallery-nav-arrow content-gallery-nav-back">&lt;</a><a id="'+myid+'Next" class="content-gallery-nav-arrow content-gallery-nav-forward">&gt;</a><a id="'+myid+'Pause" class="content-gallery-nav-pause">Pause&nbsp;Slideshow</a>');
	$('a.content-gallery-nav-arrow').animate({opacity:0.2},100);
	
	// Bind to the item links
	$('> a', $items).click(function() {
		return false;
	});
	
	// Bind to the forward and back buttons
	$('a.content-gallery-nav-arrow', this).hover(function () {
		$(this).animate({opacity:1},100);}, function () {
		$(this).animate({opacity:0.3},100);
	});
	
	$('a.content-gallery-nav-back', this).hover(
		function () {
			$(this).animate({opacity:1},100);
		},
		function () {
			$(this).animate({opacity:0.3},100);
		}).click(function () {
		return gotoPage(currentPage - 1);                
	});
	
	$('a.content-gallery-nav-forward', this).click(function () {
		return gotoPage(currentPage + 1);
	});
	
	// create a public interface to move to a specific page
	$(this).bind('goto', function (event, page) {
		gotoPage(page);
	});
	
	// create an event for automatic scrolling
	$(this).bind('next', function () {
		if(init == true) {
			gotoPage(currentPage);
		} else {
			gotoPage(currentPage + 1);
		}
	});
};



var masterpause = false; // variable to flag slideshow pause state
function pauseSlideshow(setmaster) {
	$('.content-gallery-display').cycle('pause');
	$('.content-gallery-nav-pause').html('Resume Slideshow').addClass('content-gallery-nav-pause-pressed');
	if(setmaster == true) {	
		masterpause = true;
	}
};

function resumeSlideshow(setmaster) {
	$('.content-gallery-display').cycle('resume');
	$('.content-gallery-nav-pause').html('Pause Slideshow').removeClass('content-gallery-nav-pause-pressed');
	if(setmaster == true) {	
		masterpause = false;
	}
};

$.fn.gallerySlideshow = function(timeout,speed,displaycount) {
	var myid = $(this).attr('id');
	var myitems = $('#'+myid+' .content-gallery-nav li').size();

	$(this).gallerySlideshowNav(myid,timeout,speed);
	
	$('#'+myid+ ' .content-gallery-display').cycle({
		timeout:			timeout,  // milliseconds between slide transitions (0 to disable auto advance) 
		speed:				speed,  // speed of the transition (any valid fx speed value) 
		prev:				'#'+myid+'Prev',  // selector for element to use as previous control 
		next:				'#'+myid+'Next',  // selector for element to use as next control 
		startingSlide:		0,
		delay:				0,
		before:				function(curr, next, opts, fwd) {
								var index = opts.currSlide;
								var indexn = opts.nextSlide;
								var indexp = opts.lastSlide;
								$('#'+myid).trigger('next');
							},

		after:				function(curr, next, opts) {
							},
		
		pagerAnchorBuilder: function(idx, slide) { 
								return '#item' + idx + ' a'; // return selector string for existing anchor 
							},
		
		pagerClick:	function(idx, slide) {  // callback fn for pager clicks:    function(zeroBasedSlideIndex, slideElement)
								return '#item' + (idx) + ' a'; // return sel string for existing anchor
							} // end pagerClick callback
	});
	
	$('.content-gallery-nav, .content-gallery-nav-arrow').hover(
		function() {
			if(masterpause == false) {
				$('.content-gallery-display').cycle('pause');
			}
		},
		function() {
			if(masterpause == false) {
				$('.content-gallery-display').cycle('resume');
			}
	});
	
	$('#'+myid+'Pause').toggle(
		function() {
			pauseSlideshow(true);
		},
		function() {
			resumeSlideshow(true);
		}
	);
};

$.fn.vaultDisplayImg = function() {
	$(this).click(function() {
		if($('#vaultContent #defaultContent:visible').length) {
			$('#vaultContent #defaultContent, #vaultPanel').fadeOut('slow',function() {
				$('#vaultPanel').removeClass('content-thumbs').addClass('sidebar-panel').fadeIn('slow');
			});
		}
		var my_li = $(this).parent();
		var imgid = $(my_li).attr('id');
		$('#vaultContent').css('background-image','url(/interface/gallery_display/vault/large/'+imgid+'.jpg)');
		$(my_li).addClass('vault-nav-active');
		$(my_li).siblings('.vault-nav-active').removeClass('vault-nav-active');
		return false;
	});
}
function resetVault() {
	$('#vaultContent').css('background-image','none');
	$('#vaultNav li').removeClass('vault-nav-active');
	$('#vaultPanel').addClass('content-thumbs').removeClass('sidebar-panel');
	$('#vaultContent #defaultContent, #vaultPanel').show();
}

$(document).ready(function() {
	// fade back GFDM branding
	$('#GFDMbrand a').animate({opacity:0.25}, 4000, function() {
		$('#GFDMbrand a').hover(
			function() {
				$(this).animate({opacity:1},300);
			},
			function() {
				$(this).animate({opacity:0.25},300);
			}
		);
	});
	
	// Modify navigation link behavior
	$('#navBar a').click(function() {
		var clicked = $(this);
		var rel_id = $(clicked).attr('rel');
		var rel_cl = $(clicked).attr('class');

		pauseSlideshow(true);
		resetVault();

		// Provide visual cue for navigation change
		$('#navBar li').switchClass('normal','selected','slow');
		$(clicked).parent().switchClass('selected','normal','slow');

		// Change visible content
		if(rel_cl == 'content-link') {
			var visiblepanel = $('.content-panel[id!='+rel_id+']:visible');
			if($(visiblepanel).length) {
				$(visiblepanel).slideFade('hide','slow','swing', function() {
					$('.content-gallery').fadeTo('slow','0.2');
					$(this).removeClass('content-panel-visible');
					$('#'+rel_id).slideFade('show','slow','swing', function() {
						$('#'+rel_id).addClass('content-panel-visible');
						$('#'+rel_id+' .sidebar-panel').fadeIn('slow');
					});
				});
			}
			else if($('#'+rel_id+':hidden').length) {
				$('.content-gallery').fadeTo('slow','0.2');
				$('#'+rel_id).slideFade('show','slow','swing', function() {
					$('#'+rel_id).addClass('content-panel-visible');
					$('#'+rel_id+' .sidebar-panel').fadeIn('slow');
				});
			}
			else {
				$('#'+rel_id).slideFade('hide','slow','swing', function() {
					$('#'+rel_id).removeClass('content-panel-visible');
				});
				$(clicked).parent().switchClass('normal','selected','slow');
				var activeGallery = $('.content-gallery').attr('id');
				$('#navBar a[rel='+activeGallery+']').parent().switchClass('selected','normal','slow');
				$('.content-gallery').fadeTo('slow','1');
				if(masterpause != true) {
					resumeSlideshow(false);
				}
			}
		} else {
			$('.content-panel-visible').slideFade('hide','slow','swing', function() {
				$(this).removeClass('content-panel-visible');
				var activeGallery = $('.content-gallery').attr('id');
				$('#navBar a[rel='+activeGallery+']').parent().switchClass('selected','normal','slow');
				$('.content-gallery').fadeTo('slow','1');
				if(masterpause != true) {
					resumeSlideshow(false);
				}
			});
		}
		
		return false;
	});
	
	// Contact form submission
	function submitContactForm() {
		var submitbutton = $(this);
		var options = {
			target: '#contactFormContainer',
			beforeSubmit: function() {
				$(submitbutton).val('Sending...').attr('disabled',true);
			},
			success: function() { 
				$(submitbutton).val('Send E-mail').attr('disabled',false);
				if($('#statusMessage').attr('class') == 'success') {
					$('#statusMessage div').append('<div><button id="cfReset">Reset Contact Form</button></div>');
					$('#cfReset').click(function() {
						$('#contactFormContainer').load('/interface/components/contact-form.php');
						$('#send_email').click(submitContactForm);
						return false;
					});
				} else {
					$('#send_email').click(submitContactForm);
				}

			}
	    };
		$('#contactForm').ajaxSubmit(options);

		return false;
	}
	
	// Bind to submit button
	$('#send_email').click(submitContactForm);
	
	// Bind to Vault Nav thumbnails
	$('#vaultNav a').vaultDisplayImg();
	
	// Display initial content for requested page
	var bodyid = $('body').attr('id');
	if(bodyid == 'contact') {
		$('#contactContent').show().addClass('content-panel-visible');
	}
	else if(bodyid == 'about_the_artist') {
		$('#aboutContent').show().addClass('content-panel-visible');
	}
	else if(bodyid == 'the_vault') {
		// Load vault in default state
		$('#vaultContent').show().addClass('content-panel-visible');
		$('#vaultSidebar').show().addClass('sidebar-panel-visible');
	}
	else if(bodyid == 'custom_jewelry') {
		// Load custom gallery
		$('#contentA').loadGallery('customContent');
	}
	else {
		// Load default gallery
		$('#contentA').loadGallery('showcaseContent');
	}

});

