document.documentElement.className += " js";

window.setTimeout(function() {
	var _matches = document.location.href.match(/(\/album\/[0-9]{4}\/[-_a-z0-9]+)\/([-_a-z0-9]+)#?$/i);
	if (_matches) {
		document.location.replace(_matches[1] + '#' + _matches[2]);
	}
}, 0);

$(document).ready(function() {
	var isLoggedIn  = $('div#admin').length > 0;
	if (isLoggedIn) {
		$('a').click(function() { history.back(); return false; } );
	} else {
		LinkEnhancer.initialize();
		
		if ($('body.photo-page').length) {
			$('body').append('<div id="progress-bar"></div>');
			$('div.content').empty();

			KeyboardController.initialize();
			StateManager.initialize();
			Crossfader.initialize();

			if (document.location.hash.match(/^#?.+$/)) {
				var url = document.location.href.replace(/#/, '/');
			} else {
				var url = Crossfader.getAlbumUrl();
			}
			Crossfader.load(url);
		}
		
		if ($('body.index-page').length) {
			$('dd a')
				.filter(function() {
					return this.href.match(/album\/20/);
				})
				.click(function() {
					var href = this.href.replace(/\/([-_a-z0-9]+)$/, '#$1');
					document.location.href = href;
					return false;
				})
			;
		}
		
	}
});

/***********************
 * LINK ENHANCER       *
 ***********************/

var LinkEnhancer = (function() {
	
	return new function() {

		var replaceFunction = function(uri) {
			return uri.replace(/\s*\(at\)\s*/, "@").replace(/\s*\(punkt\)\s*/, ".");
		}
		
		this.initialize = function() {
			this.replaceMailAddress();
			this.initExternalLinks();
		}

		this.replaceMailAddress = function() {
			$('span.mail').each(function() {
				var url = replaceFunction($(this).html());
				$(this).html('<a href="mailto:' + url +'">' + url + '</a>');
			});
		}

		this.initExternalLinks = function(listOfLinks) {
			$('a').live('click', function() {
				if (this.hostname && this.hostname.replace(/:.+$/, '') !== location.hostname) {
					window.open(this.href);
					return false;
				}
			});
		}
	
	}
	
})();

/***********************
 * KEYBOARD CONTROLLER *
 ***********************/

var KeyboardController = (function() {
	
	return new function() {

		var TARGETS = {35: 'last', 36: 'first', 37: 'previous', 38: 'previous', 39: 'next', 40: 'next'}

		this.initialize = function() {
			$(document).keyup(function(e) {
				if (e.keyCode in TARGETS) {
					var a = $('ol#nav li.' + TARGETS[e.keyCode] + ' a:first');
					if (a.length) {
						a.click();
					}
				}
			});
		}
		
	}
	
})();

/***********************
 * CROSSFADER          *
 ***********************/

var Crossfader = (function() {

	return new function() {

		var progressbarTimer = null;

		var crossfade = function(data) {
			var wrapper    = $('#content-wrapper');
			var oldContent = wrapper.find('div.content');
			var newContent = $('<div class="content">' + data + '</div>');
			newContent.hide();
			wrapper.append(newContent);
			
			onImagesComplete(newContent.find('#images img'), function() {
				oldContent.fadeOut(400, function() {
					oldContent.remove();
				});
				newContent.fadeIn(400);
			});
		}
		
		var onImagesComplete = function(selector, callback) {
			var incomplete = $(selector).length;
			$(selector).each(function() {
				if (this.complete) {
					incomplete--;
				}
			});
			if (incomplete) {
				window.setTimeout(function() {
					onImagesComplete(selector, callback);
				}, 100);
			} else {
				if (progressbarTimer) {
					window.clearTimeout(progressbarTimer);
				}
				$("#progress-bar").hide();
				callback.call();
			}
		}
		
		if (window.opera) { // due to problems with image.complete in Opera. TODO: find better workaround
			var onImagesComplete = function(selector, callback) {
				if (progressbarTimer) {
					window.clearTimeout(progressbarTimer);
				}
				$("#progress-bar").hide();
				callback.call();
			};
		}
		
		this.initialize = function() {
			if ($('body.photo-page').length == 0) {
				return;
			}
			
			// register events
			
			$('div.content a[href*="/album/"]').live('click', function(e) {
				if (e.button != 2) {
					var _matches = this.href.match(/\/([^\/]+)$/);
					StateManager.setState(_matches ? _matches[1] : StateManager.defaultStateID);
					Crossfader.load(this.href);
					return false;
				}
			});
			
		}

		this.getAlbumUrl = function() {
			return $('link[rel=first]').attr('href');
		}

		this.load = function(href) {
			var separator = (href.indexOf('?') == -1) ? '?' : '&';
			if (progressbarTimer) {
				window.clearTimeout(progressbarTimer);
			}
			progressbarTimer = window.setTimeout(function() {
				$("#progress-bar").show();
			}, 1000);
			$.ajax({
				url: href + separator + 'ajax',
				success: function(data, textStatus) { crossfade(data) },
				error: function(event, textStatus, errorCode) {
					// ignore errors (v 1.0)
					document.location.href = document.location.href.replace(/#.*$/, '');
				}
			});
		}
		
	}

})();

/***********************
 * STATE MANAGER       *
 ***********************/

var StateManager = EXANIMO.managers.StateManager;

StateManager.onstaterevisit = function(e) {
	var id = (e.id == StateManager.defaultStateID) ? '' : '/' + e.id;
	Crossfader.load(Crossfader.getAlbumUrl() + id);
}
