var active_img = '';// = $('#home_bg img').attr('src');
var active_id = null;

$(document).ready(function(){

	
	$('#controls').prepend('<ul><li class="first"><a id="hide" href="#">hide panels</a></li><li><a id="next" href="#">next image</a></li><li><a id="prev" href="#">previous image</a></li></ul>');
	$('#controls').css('background','transparent url(layout/img/dark.gif) repeat-y top right');



	$('a#hide').toggle(function(me){
		me.preventDefault();
		$(this).text('show panels');
		$('div#hideme').hide();
		$("#controls").ppdrag();
	},function(me){
		me.preventDefault();
		$(this).text('hide panels');
		$('div#hideme').show();
		$("#controls").ppdrag('destroy');
		$("#controls").css({'top':0,'left':0});
	});
	
	//my images array has an extra element at the end
	images.pop();
	//now not anymore

	//check which image is the active one.
	//reorder my array
	
	active_img = $('#home_bg img').attr('src');
	active_id = null;
	//console.log(active_img);
	for(var i=0;i<images.length;i++){
		if(active_img == images[i].imgurl){
			//console.log(i);
			active_id = i;
		}
	}
	
	$('a#next').click(function(me){
		me.preventDefault();
		changeImage(+1);
	});
	$('a#prev').click(function(me){
		me.preventDefault();
		changeImage(-1);
	});
});


function changeImage(which){
	if(active_id < images.length-1 && active_id > 0){
		active_id += which;
	}else if(active_id == images.length-1){
		if(which > 0){
			active_id = 0;
		}else{
			active_id--;
		}
	}else if(active_id == 0){
		if(which < 0){
			active_id = images.length-1;
		}else{
			active_id++;
		}
	}
	//console.log(active_id);
	$.get('/dynamic.php?url='+images[active_id].page_url,function(data){
		loadImage(active_id, data);
	});
	
}

function loadImage(img,desc){
	$.get(images[img].imgurl,function(data){
		//alert("Data Loaded: " + data);
		/*$('#home_bg').fadeOut('medium',function(){
			$('#home_bg img').attr({style:'visibility:hidden;filter:alpha(opacity=0); -moz-opacity:0; opacity:0;',src:images[img].imgurl});
			$('#home_bg img').attr({style:'visibility:visible'});
			$('#home_bg').fadeIn('medium');
		});*/
		
		$('#home_bg').animate({opacity: 0},500,function(){
			$('#home_bg img').attr({src:images[img].imgurl, height:images[img].h});
			$('#home_bg').animate({opacity: 1},500,function(){
				$('#controls div').html(desc);
			});
		});
		
		
	});
}