var imagesm = [];
var imagesl = [];
var id = "";

function blah(id){
	disploader();
	var myRequest = new Request.JSON({method: 'get', url: '/cat.json.php',
	onSuccess: function(myJSON, myText){
		var jsonObj = JSON.decode(myText);
		imagesl = jsonObj.images;
		if (id != "-1") {
		var loader = new Asset.images(jsonObj.imagesth, {
		onProgress: function(counter,index) {
			this.set({'class':'thumb',
			'id':'th'+index,
			'events':{
				'click':function(){
					populate(index);
					$$('img.thumbsel').removeClass('thumbsel');
					$('th'+index).addClass('thumbsel');
				}
			}});
			imagesm[index] = this;
		},
		onComplete: function() {
			$$('#thumbnails img').each(function(el){
				el.set('tween', {duration: 'long'});
				el.tween('opacity',[1,0]);
				el.destroy();
			});
			imagesm.each(function(im, index) {
				im.inject($('thumbnails'));
				im.set('tween', {duration: 'long'});
				im.tween('opacity',[0,1]);
			});
			randm(id);
			imagesm = [];
		}
		})}else{
			randm(id);
		};
	},
	onFailure: function (xhr){
		alert (xhr);
	}
	});
	myRequest.send('catid=cat'+id);

}
function disploader(){
	var myFx = new Fx.Tween('pic');
	myFx.start('opacity', '1', '0');
	$('pic').setProperties({'src':'/ajax-loader.gif','class':'loader'});
}
function populate(im, id){
		disploader();
		if ($('contact').hasClass('hidden') == false) {
			hideinfo();
		}
		var myFx = new Fx.Tween('pic');
		myFx.start('opacity', '0', '1');
		if (id != "-1"){
			$$('img.thumbsel').removeClass('thumbsel');
			$('th'+im).addClass('thumbsel');
		}
		var myImage = new Asset.image(imagesl[im], {'id': 'pic', 'class':'hidden',
		onload: function (){
			$('pic').destroy(); 
			$('pic').removeClass('hidden'); 		
			$('pic').set({
					'events':{
					'click':function(){ 
						if (id == "-1"){
							blah(0);
						}else{
							next(im, id);
						}
					}
			}});
			var myFx = new Fx.Tween('pic'); 
			myFx.start('opacity', '0', '1');
		}}).inject($('image'));
}
function showinfo(){
	var myFx = new Fx.Tween('pic');
	myFx.start('opacity', '1', '0');
	$('contact').removeClass('hidden');
	var myFx = new Fx.Tween('contact');
	myFx.start('opacity', '0', '1');
}
function hideinfo(){
	var myFx = new Fx.Tween('contact');
	myFx.start('opacity', '1', '0');
	$('contact').addClass('hidden');
	var myFx = new Fx.Tween('pic');
	myFx.start('opacity', '0', '1');
}
function randm(id){
	var random = $random(0, imagesl.length-1);
	populate(random, id);
}
function next(im, id){
	if (im == imagesl.length-1) {im = 0}else{im++};
	populate(im, id);
}
window.addEvent('domready', function() {
 	blah(-1);
	$$('#nav img').tween('opacity',[0,1]);
});
