$(document).ready(function(){

	/* search field
	   clear on focus, replace with default on blur
	*/

	$.fn.search = function() {
		return this.focus(function() {
			if( this.value == this.defaultValue ) {
				this.value = "";
			}
		}).blur(function() {
			if( !this.value.length ) {
				this.value = this.defaultValue;
			}
		});
	};
	$("#searchfield").search();


	/* external links
	   based on: http://www.learningjquery.com/2008/08/quick-tip-dynamically-add-an-icon-for-external-links
	*/

	$('a').filter(function() {
		return this.hostname && (this.hostname).split(":")[0] !== (location.hostname).split(":")[0];
	})
	.not(':has(img, div)')
	.addClass('external')
	.click(function() {
		window.open(this.href);
		return false;
	});


	/* decrypt mailto links
	 *
	 */

	d_me();
	
	/*
	 * add image navigation
	 */
	$('div.paging').each(function() {
		/*
		 * init
		 */
		var actualImage = $('.image img').attr('src');
		var currentImage = 1;
		for (i=0; i < images.length; i++) {
			if (images[i] == actualImage) {
				currentImage = i+1;
			}
		}

		/*
		 * build content
		 */
		$(this).append('<a class="rewind" href="#">&lt;</a> ' +
							'<a class="forward" href="#">&gt;</a> ' +
							'<span class="counter">' +
							' 	<span class="num-current">' + currentImage + '</span> ' +
							' 	<span class="separator">/</span> ' +
							' 	<span class="num-overall">' + images.length +'</span> ' +
							'</span>' +
							'<img class="activity-indicator" src="/static/images/activity_indicator.gif" alt="" style="display: none;"/>');


		/*
		 * add events
		 */
		e = this;
		$(this).children('.rewind').click(function() {
			var actualImage = $('.image img').attr('src');
			var index = images.length-1;
			$(e).children('.activity-indicator').css('display', 'inline');
			for (i=0; i < images.length; i++) {
				if (images[i] == actualImage) {
					if (i == 0) {
						index = images.length-1;
					}
					else {
						index = i-1;
					}
				}
			}
			$('.image img').attr('src', images[index]).load(function() {  
				$(e).children('.activity-indicator').css('display', 'none');
			});  
			$(e).children('.counter').children('.num-current').text(index+1);
			return false;
		});

		$(this).children('.forward').click(function() {
			var actualImage = $('.image img').attr('src');
			var index = 0;
			$(e).children('.activity-indicator').css('display', 'inline');
			for (i=0; i < images.length; i++) {
				if (images[i] == actualImage) {
					if (i == images.length-1) {
						index = 0;
					}
					else {
						index = i+1;
					}
				}
			}
			$('.image img').attr('src', images[index]).load(function() {  
				$(e).children('.activity-indicator').css('display', 'none');
			});  
			$(e).children('.counter').children('.num-current').text(index+1);
			return false;
		});
	});
});


