

function setup_imgviewer() {
	thumbs = $('kaimg_preview').getElements('a');
	thumbs.each(function(item) {
		item.addEvent('click',function() {
			$clear(img_timer);
			if(!inaction)
				set_new_image(this);
			return false;
		});
	});
}

function set_new_image(atag) {
	inaction = true;
	atag.blur();
	thumbs = $$('#kaimg_preview img');
	thumbs.each(function(item) {
		if(item.hasClass('pic-current'))
			item.removeClass('pic-current');
	});
	img = atag.getElement('img');
	img.addClass('pic-current');
	// fade new image
	$('kaimg_big_ol').setStyle('display','block');
	newImage = new Asset.image(atag.get('href'), {title: atag.get('href'), onload: function() {
		ni = new Element('img', {
    		'src': this.get('href'),
			'alt': this.get('title'),
			'border': 0,
			'tween': { duration:1000, onComplete: function() {
				$('kaimg_big_ol').empty();
				$('kaimg_big_ol').setStyle('display','none');
				$('kaimg_big').getElement('img').set('src',this.get('href'));
				inaction = false;
				img_timer = fire_random_pic_click.delay(5000);
			}.bind(this)}
    	});
		ni.fade('hide');
		ni.inject($('kaimg_big_ol'));
		ni.fade('in');
	}.bind(atag)});

}

function fire_random_pic_click() {
	tags = $$('#kaimg_preview a');
	m = tags.length;
	if(m < 2)
		return false;
	rand = $random(1,m)-1;
	if(rand == current_img) {
		if(current_img > 0)
			rand = 0;
		else
			rand = 1;
	}
	if(!inaction)
		tags[rand].fireEvent('click', tags[rand]);
}

function init_calendar() {
	if($('field3') && $('field4')) {
		cal1 = new Calendar({ field3: 'd.m.y' }, { });
		cal2 = new Calendar({ field4: 'd.m.y' }, { });
	}
}


// ONLOAD
var inaction = false;
var current_img = 0;
var img_timer = false;
window.addEvent('domready', function() {
	if($('kaimg_preview') && $('kaimg_big')) {
		setup_imgviewer();
		img_timer = fire_random_pic_click.delay(5000);
		init_calendar();
	}
});

