/**
 * @author jkl@unitb.de
 * @requires jQuery.js
 */
$().ready(function(){
// CONFIG
	var a_images       = new Array();
	var a_subtxt       = new Array();
	var s_image_dir    = '';
	var e_myStage      = $('.bildergalerie .stage img');
	var e_myDescr      = $('.bildergalerie #bildunterschrift p');
	var i_active_index = 0;
	var b_cycle        = false;
	var i_intertvall   = 1850;
	var s_regex        = /^.*\?img\=(.*)\&txt\=(.*)$/;

// FUNCTIONS

	// read html and collect the images and the subtext
	function get_img_array() {
		a_images = Array();
		a_subtxt = Array();
		$('.ig_navigation .index li a').each(function() {
			var a_hits = s_regex.exec($(this).attr('href'));
			a_images.push(decodeURI(a_hits[1]));
			a_subtxt.push(decodeURI(a_hits[2]));
			$(this).attr('href', '#bg_top');
		});
	}

	// get the active index from the html
	function get_act_index() {
		var i=0;
		$('.ig_navigation .index li').each(function(){
			i++;
			if($(this).attr('class') == 'active') {
				i_active_index = i;
			}
		});
	}

	// set the active index in the html
	function set_active_index(n) {
		$('.ig_navigation .index li.active').removeClass('active');
		var i=0;
		$('.ig_navigation .index li').each(function(){
			i++;
			if(i == n) {
				$(this).addClass('active');
			}
		});
	}

	function go_next() {
		get_act_index();
		if(i_active_index == a_images.length) {
			i_active_index = 1;
		} else {
			i_active_index = i_active_index+1;
		}
		set_active_index(i_active_index);
		go_active_index();
	}

	function go_prev() {
		get_act_index();
		if(i_active_index == 1) {
			i_active_index = a_images.length;
		} else {
			i_active_index = i_active_index-1;
		}
		set_active_index(i_active_index);
		go_active_index();
	}

	function go_active_index() {
		get_act_index();
		i_my_index = i_active_index-1;
		e_myStage.attr('src', s_image_dir+a_images[i_my_index]);
		e_myDescr.html(a_subtxt[i_my_index]);
		show_active_index();
	}
	
	function show_active_index() {
		$('li.img_ind span').each(function() {
			get_act_index();
			$(this).html('Bild ' + i_active_index + ' von ' + a_images.length );
		});
	}

	function toggle_cycle() {
		b_cycle = !b_cycle;
	}

	function cycle() {
		if(b_cycle === true) {
			go_next();
			document.o_aktiv = setInterval(function() {go_next()}, i_intertvall);
		} else {
			clearInterval(document.o_aktiv);
		}
	}

// ACTION
	get_img_array();
	if(a_images.length > 1) {
		$('.body_img_big .stage').addClass('slidestage');
		go_active_index();
	}

//LISTENERS
	$('.ig_navigation .index li a').click(function() {
		b_cycle = false;
		cycle();
		$('.ig_navigation .index li.active').removeClass('active');
		$(this.parentNode).addClass('active');
		go_active_index();
		$(this).blur();
	});

	$('.img_sel .prev a').click(function() {
		b_cycle = false;
		cycle();
		go_prev();
		$(this).blur();
	});

	$('.img_sel .next a').click(function() {
		cycle();
		go_next();
		$(this).blur();
	});
});
