var timer = null;
var lnks, tIdx = 0;
var pl,ph_img, ph_title, ph_desc;
var slideshow = true;
var len, dir = '320x210', replace_dir = '90x60';
var imgs = [];

function changePhoto(idx) {
	idx = (isNaN(idx) ? (tIdx + 1) : idx) % lnk_len; 
	tIdx = idx;
	cur_lnk = lnks.eq(idx);
	var url = cur_lnk.attr('href');
	var title = cur_lnk.find('img').attr('title');
	var desc = cur_lnk.find('img').attr('alt');
	clearTimeout(timer);
	if(typeof (imgs[idx]) != 'undefined'){
		img = imgs[idx];
		ph_img = ph_wrapper.find('img');
		ph_img.css({opacity: 0.6})
        	.attr({'src':img[0].src, alt:title})
        	.animate({opacity: 1.0}, 700);
		ph_title.attr({'href': url}).text(title);
		ph_desc.text(desc);
		lnks.removeClass('hover');
		cur_lnk.addClass('hover').find('span.load').remove();
		ph_wrapper.css({'background':'none'});
		if(slideshow)timer = setTimeout('changePhoto()', 5000);
	}else{
		cur_lnk.append('<span class="load"/>').children('span:last-child');
		ph_wrapper.css({'background':'url(/images/loading-large.gif) no-repeat center center'}).find('img').css({opacity: 0.7});
		var img = new Image();
		loadWidth = cur_lnk.outerWidth();
		loadHeight = cur_lnk.outerHeight();
		$(img).bind('load', function(){
			imgs[idx] = new Array(img);
			$(this).unbind();
			if(slideshow) changePhoto(idx);
		});
		img.src = cur_lnk.find('img').attr('src').replace(replace_dir, dir);
	}
}

$(document).ready(function(){
	ph_wrapper = $('#newsPhoto');
	ph_title = $('#photoDesc').find('a');
	ph_desc = $('#photoDesc').find('p');
	pl = $('#photoList');
	lnks = pl.find('a');
	lnk_len = lnks.length;
	lnks.eq(0).addClass('hover');
	ph_wrapper.append('<img src="'+lnks.eq(0).find('img').attr('src').replace(replace_dir, dir)+'" alt="'+lnks.eq(0).find('img').attr('alt')+'"/>');
	lnks.click(function(){
		var cur_id = $(this).index();
		changePhoto(cur_id);
		return false;
	});
	
	$("#photoNext").click(function() {
		var active = $('#photoList .hover');
		var cur_id = (active.index()+1)%lnk_len;
		changePhoto(cur_id);
		return false;
	});
	$("#photoPrev").click(function() {
		var active = $('#photoList .hover');
		var cur_id = ((active.index()-1))%lnk_len;
		changePhoto(cur_id);
		return false;
	});	
	$("#photoStop").click(function(){clearTimeout(timer);return false;});
	if(slideshow)timer = setTimeout('changePhoto()', 5000);

});	

