
$(document).ready( function() {
	log('will init the scrollables...');
	
	$("div.scrollable").scrollable({
		size:8
	});
	
	$('.gallery-link').click( onGalleryLinkClicked );
});

function onGalleryLinkClicked(event) {
		
		var href = $(this).attr('href');
		
		// If the url contains parameters then break them off and send them
		// in the AJAX params variable
		
		var params = '';
		if ( href.indexOf( "?") != -1)
		{
			var split = href.split("?");
			href = split[1];
			params = '&' + split[1];
		}
			
		//var ajax_url = '?ajax=TRUE&url=index.php' + href;
		
		var ajax_url = '?ajax=TRUE&url=site_templates/body_life-at-the-villages-photo.php';
			
		$.post( ajax_url, params, onGalleryResourceRetrieved, "json");
		
		
		event.stopPropagation();
		//return false;
		
		// If this is a new-gallery-item-button then add a new button to the scrollable
		if($(this).hasClass('new-gallery-item-button')) {
		
			// Find the parent element which is the list item containing the link
			
			var parent = $(this).parent();
			// log('parent:');
			// log(parent);
			
			// Build the id for the new element by incrementing the old id
			
			var old_id = parent.attr('id');
			
			// log('old_id = ' + old_id);

			var array = old_id.split('-');
			
			// The folder number is the last item of the array
			
			var folder_number = (array[array.length-1]);
			
			// log('number = ' + folder_number);
			
			var id = Number(folder_number);
			// log('id = ' + id);
			
			var new_id_num = id+1;
			// log('id = ' + new_id_num);
			new_id_num = pad( String(new_id_num) , 5, '0', STR_PAD_LEFT);
			
			// Build the new id string			

			var new_id = '';
			for(var i = 0; i<array.length-1; i++) {
				new_id += array[i] + '-';
			}
			new_id += new_id_num;
			// log('new_id = ' + new_id);
			
			// Create the new html object to be inserted into the dom
			
			var new_object = $('<div></div>');
			
			// Be sure to port over the class of the old element
			
			new_object.attr('id', new_id).attr('class', parent.attr('class'));
			
			// Copy over the content of the element
			
			new_object.html( parent.html() );
			
			// We also need to make sure the url of the new element has the incremented folder number
			
			var href = new_object.children('a').attr('href');
			var href_array = href.split('image=');
			href = href_array[0] + 'image=' + new_id_num;
			new_object.children('a').attr('href', href);
			
			//parent.attr('id', new_id);
			
			// log(new_object);
			
			// Discover the tab of this item
			
			var tab = $(this).closest('.tab').attr('id');
			// log('tab = ' + tab);
			
			// Add the new item to the scrollable
			
			addGalleryItem(tab, new_object);
			
			// Enable clicking on the new element's child
			
			$('#' + new_id).children('a').click( onGalleryLinkClicked );
			
			// Remove the new class from this element so it does not create another new element
			// By doing this it will become a normal button, linking to its image
			
			$(this).removeClass('new-gallery-item-button');
			
			
			
			// Update the thumbnail of the old + button to reflect the new default image
			
			var thumb_src = "site_library/php/ImageThumbnail.php?url=../../delicious_cms/_default/default.png&x=63&type=png";
			$('img', parent).attr('src', thumb_src);
			
			
		}
		
		return false;
}

function randomString(length)
{
	chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
	pass = "";
	for(x=0;x<length;x++)
	{
		i = Math.floor(Math.random() * 62);
		pass += chars.charAt(i);
	}
	return pass;
}

function onGalleryResourceRetrieved(data, textStatus) {
	/*log('onGalleryResourceRetrieved.\n\nEvent data object:');
	log(data);*/
	
	if(data.success) {
		
		if(data.content_array) {
			
			for(var i = 0; i < data.content_array.length; i++) {
				var target_id = data.content_array[i].id;
				var html = unescape(data.content_array[i].html);
				
				// Here we should append the new html behind the existing image
				// Then, after the image has had time to download, fade the old
				// image away to expose the new image
				
				var random_class = randomString(12);
				$('[id=' + target_id + ']').children().addClass(random_class);
				
				var new_random_class = randomString(12);
				var item = $(html).addClass(new_random_class);
				
				$('[id=' + target_id + ']').prepend(item);
				
				$(item).css('opacity', 0).css('position', 'absolute').animate({opacity:'1'}, 1000, function() { $(this).css('position', 'relative') });
				$('.' + random_class).css('position', 'absolute').animate({opacity:'0'}, 1000, function() {
					$(this).remove();
				});
			}
			
			// upon opening the new image dialog, wire up any event listeners
			
			$('#dialog').bind("IMAGE_EDITOR_OPENED", onImageEditorOpened);
			
		}
		
	}
}

function onImageEditorOpened(event) {
	$('#dialog').bind("IMAGE_DELETED", onGalleryImageDeleted);
	$('#dialog').bind("IMAGE_CHANGED", onGalleryImageChanged);
}

function onGalleryImageDeleted(event, id) {
	log('onGalleryImageDeleted with id ' + id);
	
	// id will be something like:
	// "life-at-villages-photo-gallery:tab-independent-living:gallery:00005|image"
	
	// We need to isolate the tab and the image number
		
	id_array = id.split('|');
	id = id_array[0];
	
	item_array = id.split(':');
	
	var tab = item_array[ item_array.length - 3];
	var folder = item_array[ item_array.length - 1];
	
	/*log('tab = ' + tab);
	log('folder = ' + folder);*/
	
	removeGalleryItem(tab, folder);
}

function onGalleryImageChanged(event, id, ext, url) {
	log('onGalleryImageChanged with id ' + id);
	
	// id will be something like:
	// "life-at-villages-photo-gallery:tab-independent-living:gallery:00005|image"
	
	// We need to isolate the tab and the image number
		
	id_array = id.split('|');
	id = id_array[0];
	
	item_array = id.split(':');
	
	var tab = item_array[ item_array.length - 3];
	var folder = item_array[ item_array.length - 1];
	
	/*log('tab = ' + tab);
	log('folder = ' + folder);*/
	
	// Update the gallery item's thumbnail src
	
	/*log('looking for id="' + id + '"');
	log($('[id=' + id + ']'));
	
	var large_image_src = $('[id=' + id + ']').children('img').attr('src');
	
	log('large image src = "' + large_image_src + '"');*/
	
	var thumbnail_div = $('[id=' + tab + '-thumbnail-' + folder + ']');
	
	var thumb_src = "site_library/php/ImageThumbnail.php?url=../../" + url + "&x=63&type=" + ext;
	
	/*log('thumb_src = "' + thumb_src + '"');
	
	log('target image:');
	log(thumbnail_div);
	log( $('img', thumbnail_div) );*/
	$('img', thumbnail_div).attr('src', thumb_src);
}

function addGalleryItem(tab, html) {
 
	// get handle to scrollable api by accessing
	// the specific tab's scrollable 
	var api = $("div#" + tab + "-scrollable").scrollable(); 

	// append new item using jQuery's append() method 
	api.getItemWrap().append(html); 

	// rebuild scrollable and move to the end to see what happened     
	api.reload().end(); 

}

function removeGalleryItem(tab, item) { 
	// get handle to scrollable api 
	var api = $("div#" + tab + "-scrollable").scrollable(); 

	// remove last item by using jQuery's remove() method 
	api.getItems().filter('#' + tab + '-thumbnail-' + item).remove(); 

	// rebuild scrollable and go one step backward 
	api.reload().prev(); 

	// Get the currently selected item and 'click' it
	// so that it loads as the current image

	var index = api.getIndex();
	log('api index = ' + index );

	var currentItem = api.getItems()[index];
	//log('current item:');
	//log(currentItem);

	$(currentItem).children('a').trigger('click');
}

