/**
 * Wavetrex Eu - A DonReY Application
 */
donrey.wtx = (function() {

	return {
		init: function() {
		
			// ajax loading of images - this is done to allow thumbnail generation/caching on the fly

			// test if the DIV with ID "photos" exists
			var photos = $('div#photos');
			if(photos.length > 0) {
//				dump(photos);

				$.ajax({
					url: "/ajax",
					data: {
						cmd: 'readphotos',
						cpath: $('#cpath').val()
					},
					dataType: 'json',
					success: function(r) {
						
						var total_imgs = r.data.images.length, loaded_imgs = 0, c,
							dom_imgs = [],
							display_images = function() {
							var imgdiv = $('#photos').empty();
								for(c = 0;c<dom_imgs.length;c++) {
		
									// TODO: better way to append images ( with template ? )
									z = imgdiv.append($("<a class='fzoom' rel='wpg' href='/img/?i=" + escape(r.data.images[c]) + "&cpath=" + r.data.cpath +"' />").append(dom_imgs[c]));
									
									$("a.fzoom").fancybox({
										'speedIn'		: 400,
										'speedOut'		: 400,
//										'opacity'		: true,
										'type'				: 'image',
										'transitionIn'		: 'fade',
										'transitionOut'		: 'fade',
										'changeSpeed'		: 120,
										'hideOnContentClick':true,
										'cyclic'		: true
									});
								}
							},
							disp_to;
						
						if(total_imgs == 0) {
							$('#photos').empty().html("No images in this folder, please try another.");
							return;
						}

						// preload images 
						for(c = 0; c<total_imgs; c++) {
							dom_imgs[c] = new Image();
							dom_imgs[c].onload = function() {
								
								loaded_imgs ++;
								
								// when all loaded, display them
								if(loaded_imgs == total_imgs) {
									// finished loading, append all
									clearTimeout(disp_to);
									display_images();
								}
							};
							dom_imgs[c].src = "/img/?th=1&i=" + escape(r.data.images[c]); // + "&cpath=" + r.data.cpath; 
						}
						// sometimes, loading fails for some image, so do a timeout of 5 seconds which will display what has been loaded anyway
						disp_to = setTimeout(function() {
							display_images();
							$('#photos').append("<div style='clear: both'>Warning! Some images could not be loaded properly !</div>");
						},3000);
					}
				});
			
			}
		}
	};

}());

//jQuery's on ready
$(donrey.wtx.init);
