var galleries = null;
var arrMonths = ['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November',
	'December'];
var ajaxRequest = null;
var currentGallery = null;
var ids = {
	GALLERY_CONTAINER: '#gallery-container',
	GALLERY_INFO: '#gallery-info',
	RECENT_GALLERIES: '#recent-galleries'
};

// ==================

function startPartyAnimals() {
	// get gallery data
	$.ajax({
		url: 'galleries.xml',
		type: 'GET',
		dataType: 'xml',
		cache: false,
		success: function(data, txtStatus) {
			galleries = $(data).find('gallery');
			ui();
			openInitialGallery();
		},
		error: function(xhr, txtStatus, errThrown) {
			showStatusImg('error');
		}
	});
}

function updateSearchResults(term) {
	var galleriesFound = 0;
	var resultsHTML = '';
	$(galleries).each(function(i) {
		var matches = false;
		if($(this).attr('title').toUpperCase().indexOf(term.toUpperCase()) != -1) matches = true;
		if($(this).attr('desc').toUpperCase().indexOf(term.toUpperCase()) != -1) matches = true;
		if($(this).attr('caption').toUpperCase().indexOf(term.toUpperCase()) != -1) matches = true;
		if(matches) {
			resultsHTML += '<div class="search-result" id="result_' + $(this).attr('loc') + '"><p><span class="info-heading">'
				+ $(this).attr('title') + ': ' + formatDate($(this).attr('date')) + '</span> ' + $(this).attr('desc') + '</p></div>';
			galleriesFound++;
		}
	});
	if(galleriesFound == 0) resultsHTML = '<p>No results found.</p>';
	$('#search-results').empty().append(resultsHTML);
	
	$('#search-results .search-result').bind("mouseenter", function() { $(this).addClass('search-result-hover'); });
	$('#search-results .search-result').bind("mouseleave", function() { $(this).removeClass('search-result-hover'); });
	$('#search-results .search-result').click(function() {
		var galleryId = $(this).attr('id').split('_')[1];
		$('#search-results').fadeOut('fast');
		$('#gallery-list').fadeOut('fast');
		loadGallery(galleryId);
	});
}

function ui() {
	// add recent galleries to list
	$(galleries).filter(':lt(9)').each(function(i) {
		$(ids.RECENT_GALLERIES).append('<img src="images/galleries/' + $(this).attr('loc') + '/' + $(this).attr('image')
			+ '" width="75" height="75" id="recent_' + $(this).attr('loc') + '" alt="' + $(this).attr('desc') + '" />');
		$('#recent-galleries-heading').after('<p id="info_' + $(this).attr('loc') + '" class="recent-gallery-info">'
			+ $(this).attr('title') + ': ' + formatDate($(this).attr('date')) + '</p>');
	});
	// add mouse events to recent galleries
	$(ids.RECENT_GALLERIES + ' img').each(function(i) {
		var thisGallery = $(this).attr('id').split('_')[1];
		$(this).click(function() { loadGallery(thisGallery); });
		$(this).bind('mouseenter', function() {
			var galleryId = $(this).attr('id').split('_')[1];
			$(this).addClass('highlight');
			$('#info_' + galleryId).show();
		});
		$(this).bind('mouseleave', function() {
			var galleryId = $(this).attr('id').split('_')[1];
			$(this).removeClass('highlight');
			$('#info_' + galleryId).hide();
		});
	});
	// search box
	$('#input-search').val('');
	$('#input-search').keyup(function() {
		var searchTerm = $('#input-search').val();
		if(searchTerm.length > 2) {
			$('#search-results').fadeIn('fast');
			$('#gallery-list').fadeOut('fast');
			updateSearchResults(searchTerm);
		} else {
			$('#search-results').fadeOut('fast');
		}
	});
	$('#input-search').focus(function() {
		if($('#input-search').val().length > 2) {
			$('#search-results').fadeIn('fast');
			$('#gallery-list').fadeOut('fast');
		}
	});
	$('#input-search').click(function(event) { event.stopPropagation(); });
	$('#search-results').click(function(event) { event.stopPropagation(); });
	$('body').click(function() { $('#search-results').fadeOut('fast'); });
	
	// gallery buttons
	$('#previous').click(function() { changeSlide(-1); });
	$('#previous').bind('mouseenter', function() { if(currentGallery) $('#previous').addClass('gallery-button-hover'); });
	$('#previous').bind('mouseleave', function() { if(currentGallery) $('#previous').removeClass('gallery-button-hover'); });
	$('#next').click(function() { changeSlide(1); });
	$('#next').bind('mouseenter', function() { if(currentGallery) $('#next').addClass('gallery-button-hover'); });
	$('#next').bind('mouseleave', function() { if(currentGallery) $('#next').removeClass('gallery-button-hover'); });
	
	// image click
	$('#gallery-container').click(function() { changeSlide(1); });
	
	// photo actions tabs
	$('#tab-buy').click(function() {
		$('.sheet-selected').removeClass('sheet-selected').hide();
		$('.tab-selected').removeClass('tab-selected');
		$('#sheet-buy').addClass('sheet-selected').show();
		$('#tab-buy').addClass('tab-selected');
	});
	$('#tab-share').click(function() {
		$('.sheet-selected').removeClass('sheet-selected').hide();
		$('.tab-selected').removeClass('tab-selected');
		$('#sheet-share').addClass('sheet-selected').show();
		$('#tab-share').addClass('tab-selected');
	});
	$('#tab-send').click(function() {
		$('.sheet-selected').removeClass('sheet-selected').hide();
		$('.tab-selected').removeClass('tab-selected');
		$('#sheet-send').addClass('sheet-selected').show();
		$('#tab-send').addClass('tab-selected');
	});
	
	// fade in buy sheet
	$('#sheet-buy').fadeIn('fast');
	
	// view galleries button
	$('#dyn-total-galleries').empty().append('(' + $(galleries).length + ')');
	$('#gallery-view-all').bind("mouseenter", function() { $(this).css('background-color', '#553333'); });
	$('#gallery-view-all').bind("mouseleave", function() { $(this).css('background-color', '#000000'); });
	$('#gallery-view-all').click(function() { ($('#gallery-list').css('display') == 'none') ? $('#gallery-list').fadeIn('fast')
		: $('#gallery-list').fadeOut('fast') ; });
	
	// gallery list
	$(galleries).each(function(i) {
		$('#dyn-gallery-list').append('<p id="all_' + $(this).attr('loc') + '"><span class="info-heading">'
			+ $(this).attr('title') + '</span> ' + formatDate($(this).attr('date')) + ': ' + $(this).attr('desc') + '</p>');
	});
	$('#dyn-gallery-list p:not(.close)').each(function(i) {
		$(this).click(function() {
			var galleryId = $(this).attr('id').split('_')[1];
			loadGallery(galleryId);
			$('#gallery-list').fadeOut('fast');
		});
		$(this).bind('mouseenter', function() { $(this).addClass('highlight'); });
		$(this).bind('mouseleave', function() { $(this).removeClass('highlight'); });
	});
}

function showBuyTab() {
	$('#tab-buy').show();
	$('.sheet-selected').removeClass('sheet-selected').hide();
	$('.tab-selected').removeClass('tab-selected');
	$('#sheet-buy').addClass('sheet-selected').show();
	$('#tab-buy').addClass('tab-selected');
}

function hideBuyTab() {
	$('#tab-buy').hide();
	$('.sheet-selected').removeClass('sheet-selected').hide();
	$('.tab-selected').removeClass('tab-selected');
	$('#sheet-share').addClass('sheet-selected').show();
	$('#tab-share').addClass('tab-selected');
}

function formatDate(dateStr) {
	return dateStr.substr(6, 2) + " " + arrMonths[parseInt(dateStr.substr(4, 2), 10)] + " " + dateStr.substr(0, 4);
}

function openInitialGallery() {
	var initialGallery = $(galleries).filter(':lt(1)').attr('loc');
	// check qs - if there is one change initialGallery
	var wlh = window.location.href;
	if( (wlh.toUpperCase().indexOf("?GALLERY=") != -1) && (wlh.indexOf('>') == -1) && (wlh.indexOf('>') == -1)
		&& (wlh.indexOf('%3C') == -1) && (wlh.indexOf('%3E') == -1) && (wlh.indexOf('%3c') == -1) && (wlh.indexOf('%3e') == -1) ) {
		initialGallery = wlh.split('?')[1].split('=')[1];
		if(initialGallery.indexOf('#') != -1) initialGallery = initialGallery.split('#')[0];
	}
	loadGallery(initialGallery);
}

function loadGallery(id) {
	var gallery = $(galleries).filter('[loc=' + id + ']:lt(1)');
	if($(gallery).length > 0) {
		unloadGallery();
		showStatusImg('loading');
		if(ajaxRequest) ajaxRequest.abort();
		ajaxRequest = $.ajax({
			url: '/images/galleries/' + $(gallery).attr("loc") + '/imageset.xml',
			type: 'GET',
			dataType: 'xml',
			cache: false,
			success: function(data, txtStatus) {
				var images = $(data).find('image');
				var shareURL = 'http://www.partyanimalsphotos.co.uk/?gallery=' + $(gallery).attr('loc');
				// gallery info
				currentGallery = { date: gallery.attr('date'), title: gallery.attr('title'), loc: gallery.attr('loc'),
					site: gallery.attr('site'), href: gallery.attr('href'), hreftext: gallery.attr('hreftext'),
					desc: gallery.attr('desc'), caption: gallery.attr('caption') };
				currentGallery.images = [];
				$(images).each(function(i) {
					var thisCaption = $(this).attr('caption') ? $(this).attr('caption') : currentGallery.caption;
					currentGallery.images.push({ name: $(this).attr('name'), caption: thisCaption });
				});
				currentGallery.slideshow = {};
				currentGallery.slideshow.slides = currentGallery.images.length;
				currentGallery.slideshow.slide = 0;
				currentGallery.slideshow.inTrans = false;
				// gallery images
				for(var i = 0; i < currentGallery.images.length; i++) {
					$(ids.GALLERY_CONTAINER).append('<img class="slide" id="slide-' + i + '" alt="' + currentGallery.images[i].caption
						+ '" />');
				}
				// only download first image
				$('#slide-0').attr('src', 'images/galleries/' + currentGallery.loc + '/' + currentGallery.images[0].name);
				// ui
				$(ids.GALLERY_INFO).append('<h2>' + currentGallery.title + '</h2>');
				$(ids.GALLERY_INFO).append('<p>' + formatDate(currentGallery.date) + '</p>');
				$(ids.GALLERY_INFO).append('<p><span class="info-heading">Event</span> ' + currentGallery.desc + '</p>');
				$(ids.GALLERY_INFO).append('<p id="picture-reference"></p>');
				// show first image in gallery
				$('.slide').hide();
				showStatusImg('');
				changeSlide(0);
				// update gallery actions
				$('#gallery-actions').show();
				if(currentGallery.href) {
					showBuyTab();
					$('#dyn-photo-sales-link').attr('href', currentGallery.href);
				} else {
					hideBuyTab();
				}
				$('#dyn-share-tweet').empty().append('<a href="http://twitter.com/share" class="twitter-share-button" data-url="'
					+ shareURL + '" data-text="Party Animals Photos: ' + currentGallery.title
					+ '" data-count="horizontal">Tweet</a>'
					+ '<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>');
				$('#dyn-share-facebook').attr('href', 'http://www.facebook.com/sharer.php?u=' + shareURL);
				$('#dyn-share-stumbleupon').attr('href', 'http://www.stumbleupon.com/submit?url=' + shareURL);
				$('#dyn-share-digg').attr('href', 'http://digg.com/submit?url=' + shareURL);
				$('#dyn-input-share').val(shareURL);
				// track load
				_gaq.push(['_trackEvent', 'Galleries', 'Load', currentGallery.loc]);
			},
			error: function(xhr, txtStatus, errThrown) {
				showStatusImg('error');
			}
		});
	} else {
		showStatusImg('error');
	}
}

function unloadGallery() {
	$(ids.GALLERY_CONTAINER + ' .slide').remove();
	$(ids.GALLERY_INFO).empty();
	$('#gallery-actions').hide();
	currentGallery = null;
}

function changeSlide(change) {
	if(currentGallery) {
		if(!currentGallery.slideshow.inTrans) {
			currentGallery.slideshow.inTrans = true;
			var newSlide = currentGallery.slideshow.slide + change;
			if(newSlide < 0) newSlide = currentGallery.slideshow.slides - 1;
			if(newSlide > currentGallery.slideshow.slides - 1) newSlide = 0;
			currentSlideId = 'slide-' + currentGallery.slideshow.slide;
			newSlideId = 'slide-' + newSlide;
			currentGallery.slideshow.slide = newSlide;
			var pos = newSlide + 1;
			$('#' + currentSlideId).fadeOut('fast', function() {
				$('#' + newSlideId).fadeIn('fast', function() { currentGallery.slideshow.inTrans = false; });
			});
			$('#picture-reference').empty().append('<span id="slideshow-position">' + pos + '/' + currentGallery.slideshow.slides
				+ '</span>' + currentGallery.images[newSlide].caption + ' (' + currentGallery.images[newSlide].name + ')');
			$('#dyn-picture-ref').empty().append(currentGallery.images[newSlide].name);
			// download previous and next images
			var previousSlideNo = ((newSlide - 1) < 0) ? currentGallery.slideshow.slides - 1 : newSlide - 1;
			var nextSlideNo = (newSlide + 1 > (currentGallery.slideshow.slides - 1)) ? 0 : newSlide + 1;
			if(!$('#slide-' + previousSlideNo).attr('src')) $('#slide-' + previousSlideNo).attr('src', 'images/galleries/'
				+ currentGallery.loc + '/' + currentGallery.images[previousSlideNo].name);
			if(!$('#slide-' + nextSlideNo).attr('src')) $('#slide-' + nextSlideNo).attr('src', 'images/galleries/'
				+ currentGallery.loc + '/' + currentGallery.images[nextSlideNo].name);
		}
	}
}

function showStatusImg(img) {
	var id = '';
	if(img == 'error') id = '#img-error';
	if(img == 'loading') id = '#img-loading';
	$(ids.GALLERY_CONTAINER + ' img').hide();
	if(id != '') {
		$(id).fadeIn('fast');
	} else {
		$(ids.GALLERY_CONTAINER + ' img:not(.slide)').fadeOut('fast');
	}
}

// ==================

$(document).ready(function() {
	startPartyAnimals();
});

