/*

v	to loop or not
v	to remain paused on next / previous
v	reset timer on interval change
-	ignore controls

*/

jQuery.fn.fullscreen = function(options) {
	
/*
	container_selector = '#page';
	left_ignore_selectors = new Array('#header');
	top_ignore_selectors = new Array();
	fill = true;
	centre = true;
*/
	settings = jQuery.extend({
		container_selector : 'body',
		fill :		false,
		centre :	true,
		loop : true,
		top_ignore_selectors	: new Array(),
		left_ignore_selectors	: new Array(),
		preload_next : 3,
		preload_previous : 2,
		original : this,
		interval : 2500,
		memory : new Array(),
		source_selector : 'div:not(.ignore)',
		start_selector : '.activeslide a',
		onShowItem : function(){},
		onShowTitle : function(){},
		onShowDescription : function(){}
	}, options);

	counter = 0;
	
	jQuery(this).memory = new Array();
	
/*
//	get the settings from the rel tag if there are anybody
	if ( jQuery(this).attr('rel') ) {
		extra = jQuery(this).attr('rel');
		pairs = extra.split('&');
		for ( i = 0; i < pairs.length; i++ ) {
			pair = pairs[i].split('=');
			eval('settings.' + pair[0] + ' = "' + pair[1] + '";');
		}
	}
*/


//	load existing elements into our memory array
	jQuery(this).find(settings.source_selector).each(
		function() {
			id = jQuery(this).attr('id');
//	if there's no id create one
			if ( ! id ) 
				id = 'item-' + counter++;
			
//	lets store id, src, and title instead
			obj = new Object();

			obj.id = id;
			obj.src = jQuery(this).find('a').attr('href');
			obj.title = jQuery(this).find('a').attr('title');
			obj.description = escape(jQuery(this).find('img').attr('longdesc'));
			
			settings.memory.push(obj);
		}
	);
		
	jQuery(this).addClass('fullscreen');

	jQuery(this).find(settings.source_selector + ' a').bind(
		'click',
		function() {
//			alert(250);
//			alert(title);
			jQuery(this).start(this);
		}
	);
	
	jQuery.fn.start = function(obj) {	
		if ( jQuery.browser.msie && parseInt(jQuery.browser.version) < 7 )
			return;
		
		if ( ! obj ) {
			obj = jQuery(settings.start_selector);
		}
		
			jQuery(obj).showItem();
			if ( jQuery(settings.container_selector).is(':hidden') ) {
				jQuery(settings.container_selector).show();
				jQuery(settings.info_selector).show();
				jQuery('.fullscreen').oneTime(settings.interval, 'next', function() {
					jQuery(settings.original).play();
				});
			}
	}


	jQuery(settings.pause_selector).bind(
		'click',
		function() {
			jQuery(this).togglePlaying();
		}
	);
	

	jQuery(settings.close_selector).bind(
		'click',
		function() {
			jQuery(this).close();
		}
	);
	
	
	jQuery(settings.next_selector).bind(
		'click',
		function() {
//			alert('next');
//	play works better than nextItem as play doesn't need to know what the next item is
//			jQuery(this).play();
			jQuery(this).nextItem();
		}
	);
	
	
	jQuery(settings.previous_selector).bind(
		'click',
		function() {
			jQuery(this).previousItem();
		}
	);
	
	
	jQuery(settings.faster_selector).bind(
		'click',
		function() {
			settings.interval /= 1.5;
			window.status = settings.interval;
			jQuery(".fullscreen").stopTime("next").oneTime(settings.interval, "next", function() {
				settings.original.nextItem(next_item);
			});
//			jQuery(this).pause();
//			jQuery(this).play();
		}
	);
	
	
	jQuery(settings.slower_selector).bind(
		'click',
		function() {
			settings.interval *= 1.5;
			window.status = settings.interval;
			jQuery(".fullscreen").stopTime("next").oneTime(settings.interval, "next", function() {
				settings.original.nextItem(next_item);
			});
		}
	);
	
	
	jQuery(window).keydown(function (e) {
		switch(e.which) {
			case 27:	//	esc
			case 8:		//	delete / backspace
			case 88:	//	x
				jQuery(settings.original).close();
				break;
			case 39:
				jQuery(settings.original).nextItem();
				break;
			case 37:
				jQuery(settings.original).previousItem();
				break;
			default:
//				alert(e.which);
				break;
		}
	});


	jQuery.fn.close = function() {
		jQuery(this).pause();
		jQuery(".fullscreen").stopTime("next");
		jQuery(settings.container_selector).hide();
		jQuery(settings.info_selector).hide();
	}
	

	jQuery.fn.togglePlaying = function() {
		if ( settings.paused ) {
			jQuery(this).play();
		} else {
			jQuery(this).pause();
		}			
	}


	jQuery.fn.play = function() {
//	alert('play')
		jQuery(".fullscreen").stopTime("next");
		settings.paused = false;
		next_item = jQuery('.full-item.active-item');
		next_item = next_item[0];

//	play immediately - do not wait
		settings.original.nextItem(next_item);
		jQuery(settings.pause_selector).removeClass('pause').addClass('play');
				
//		jQuery(".fullscreen").oneTime(settings.interval, "next", function() {
//			settings.original.nextItem(next_item);
//		});
	}
	
	
	jQuery.fn.pause = function() {
		jQuery(".fullscreen").stopTime("next");		
		jQuery(settings.pause_selector).addClass('pause').removeClass('play');
		settings.paused = true;
	}	
	
	
	jQuery.fn.showItem = function(obj) {
		if ( obj ) {
			id = obj.id;
			src = obj.src;
			title = obj.title;
			description = obj.description;
		} else {
			id = jQuery(this).parent().attr('id');
			src = jQuery(this).attr('href');
			title = jQuery(this).attr('title');
			description = escape(jQuery(this).find('img').attr('longdesc'));
		}
		
		if ( ! jQuery('#full-' + id).size() && id ) {
//			jQuery(this).buildItem();
			_buildItem(id, src, title);
		}
		
		current_item = jQuery('.full-item.active-item');
		next_item = jQuery('#full-' + id);
		
//	check that the next n images and previous p images are loaded
//		index = jQuery('.fullscreen a').index(this);
		index = settings.memory.array_search(id);
		
/*
		jQuery('.fullscreen a:gt(' + index +'):lt(' + (settings.preload_next) + ')').each(
			function() {
				jQuery(this).buildItem();
			}
		);
*/
//	instead call buildItem using the variables from the settings.memory array
		preload_max = index + settings.preload_next;
		if ( preload_max > settings.memory.length )
			preload_max = settings.memory.length - 1;
			
//	we get an early warning of a lack of items here as index is returning false		
		for ( i = index; i < preload_max; i++ ) {
			if ( settings.memory[i] && settings.memory[i].id )
				the_item = _buildItem(settings.memory[i].id, settings.memory[i].src, settings.memory[i].title);
		}
		
//	how do we figure out if there are no more images so we can ask the server .
		if ( index + settings.preload_next > settings.memory.length ) {
			if ( settings.next_gallery && ! settings.loading ) {
				galleries = settings.next_gallery.split(',');
				next_gallery = galleries.shift();
				settings.next_gallery = galleries.join(',');
				
				window.status = ('getting more from ' + next_gallery);
				settings.loading = true;

//	TO FIX - this should be extracted into a callback so that it becomes specific to the situation
//	get the next set from any provided ajax request
				jQuery.post(ajaxurl, {action: 'is_attachments', id:	next_gallery, type: 'image', subaction: 'get', response: 'json', callback: '_galleryLoaded'}, function(data) {
					try {
						var json = eval('(' + [data] + ')');
					} catch (e) {
						alert('error in data');
						alert(data);
					}
					_galleryLoaded(json);
					settings.loading = false;
				});
			}
		}

//	instead call buildItem using the variables from the settings.memory array
		preload_max = index - settings.preload_previous;
		if ( preload_max < 0 )
			preload_max = 0;
			
		
		for ( i = preload_max; i < index; i++ ) {
//			alert(i + ' ' + settings.memory[i].id);
			if ( settings.memory[i] && settings.memory[i].id )
				the_item = _buildItem(settings.memory[i].id, settings.memory[i].src, settings.memory[i].title);
			else
				alert('No item [showItem ' + i + ']');
		}

//	remove those that shouldn't be here
//	get the position in our memory array of where we are now
		full_index = settings.memory.array_search(id);

		r_start = full_index - settings.preload_previous;
		r_stop = full_index + settings.preload_next
		
		if ( r_start < 0 )
			r_start = 0;
		
		remove_array = settings.memory.slice(0, r_start);
		remove_array.concat(settings.memory.slice(r_stop, settings.memory.length));
		
		for ( r = 0; r < remove_array.length; r++ ) {
			jQuery('#full-' + remove_array[r].id).remove();
		}

		
//	remove active-item from all elements
		jQuery('.full-item.previous-item').removeClass('previous-item').css('z-index', '9999');
		
		jQuery('.full-item.active-item').removeClass('active-item').addClass('previous-item');
		
//	we need to detect if the next images is loaded too		
		next_item.addClass('active-item').css('z-index', '10000').find('img').css('z-index', '10000').load(
			function() {
				jQuery(".fullscreen").stopTime("next");
				if ( ! settings.paused ) {
					jQuery(".fullscreen").oneTime(settings.interval, "next", function() {
						settings.original.nextItem(next_item);
					});
				}
			}
		);
		
//	this is a timeout for the load() event - if we have waited more than 200% of the normal interval then proceed regardless
//	also fired at the end of the entire sequence
		jQuery(".fullscreen").oneTime(settings.interval * 2, "next", function() {
			window.status = "Time out on load event.";
			jQuery(".fullscreen").stopTime("next");
			if ( ! settings.paused )
				settings.original.nextItem(next_item);
		});
		
		
//	place the current item immediately beneath and then transition
		current_item.css('z-index', 9999).addClass('previous-item');
		
		next_item.animate({opacity: 1}, settings.interval/10, null, function() {
			if ( jQuery(settings.title_selector).size() ) {
				if ( ! title )
					title = '';
				jQuery(settings.title_selector).html(unescape(title)).parents().show().css('z-index', '10001');
				settings.onShowTitle.call(this);

			//	alert('Updated title ' + obj.title);
			}
			if ( jQuery(settings.info_selector).size() ) {
				if ( ! description )
					description = '';
				jQuery(settings.info_selector).html(unescape(description)).parents().show().css('z-index', '10001');
				settings.onShowDescription.call(this);

			//	alert('Updated title ' + obj.title);
			}
		});

//	if this image has preloaded then the load event above wont be firing
//	if the image has loaded then it will have a size
		if ( next_item.find('img:first').width() ) {
			jQuery(".fullscreen").stopTime("next");
			if ( ! settings.paused ) {
				jQuery(".fullscreen").oneTime(settings.interval, "next", function() {
					settings.original.nextItem(next_item);
				});
			}
		}
		
//	here we should be able to know if there are any more items coming or not and handle it
		if ( index == settings.memory.length - 1 ) {
			window.status = ("no more items");
//	go into a waiting loop 
			if ( settings.loading ) {
				window.status += (' but there are more coming');
			} else {
				window.status += (' and no more on the horizon');
			}
		}
		
//	callback 
		settings.onShowItem.call(this);
	}
	
	
	jQuery.fn.nextItem = function(current_item) {
//	stops extra events piling up
		jQuery(".fullscreen").stopTime("next");
		
		if ( ! current_item )
			current_item = jQuery('.full-item.active-item');		
		
		id = jQuery(current_item).attr('id');
		if ( id ) {
			id = id.substr(5, id.length);

//	find the next item from the original list
//		next_items = jQuery('.' + id + ' ~ div');
//		next_items = jQuery('.' + id + ' ~ ' + settings.source_selector);
			index = settings.memory.array_search(id);
			next_item = settings.memory[index + 1];
		} else if ( settings.loop == true ) {
			next_item = settings.memory[0];
		} else {
			return false;
		}
		settings.original.showItem(next_item);
		return;
	}
	
	
	jQuery.fn.previousItem = function(current_item) {
//	stops extra events piling up
		jQuery(".fullscreen").stopTime("next");
		if ( ! current_item )
			current_item = jQuery('.full-item.active-item');
			
		id = jQuery(current_item).attr('id');
		if ( ! id ) {
			return false;
		}
		id = id.substr(5, id.length);

//	find the next item from the original list
//		next_items = jQuery('.' + id + ' ~ div');
//		next_items = jQuery('.' + id + ' ~ ' + settings.source_selector);
		index = settings.memory.array_search(id);

//	if we go too far we hit the load time out error
//	dont go below 1
		if ( index < 1 ) index = 0;

		previous_item = settings.memory[index - 1]
		settings.original.showItem(previous_item);
		return;
	}
	
	


	_buildItem = function(the_id, src, title) {
		if ( ! the_id ) {
			alert ('No ID [_buildItem]');
			return false;
		}
		
		if ( jQuery('#full-' + the_id).size() )
			return jQuery('#full-' + the_id);
		
/*
	<div style="opacity : 0; position : fixed; background-color : black; width : 100%; height : 100%; overflow : hidden; top : 0; left : 0;" id="full-' + the_id + '">
	<a href="">
	<img title="' + title + '" src="' + src + '" />
	</a>
	</div>
*/

//		the_html = '<div style="opacity : 0; position : fixed; background-color : black; width : 100%; height : 100%; overflow : hidden; top : 0; left : 0;" id="full-' + the_id + '"><a href=""><img title="' + title + '" src="' + src + '" /></a></div>';
		the_html = '<div style="opacity : 0; position : fixed; background-color : black; width : 100%; height : 100%; overflow : hidden; top : 0; left : 0;" id="full-' + the_id + '"><img title="' + title + '" src="' + src + '" /></div>';
//		html = '<div><img src="' + src + '"></div>';
//		alert(html)

		the_item = jQuery(settings.container_selector).append(the_html);
		the_item = jQuery('#full-' + the_id);

		the_item.addClass('full-item');
		the_item.find('img').load(
			function() {
		//		alert('loaded');
				_scaleImage(this);	
			}
		);
		
		return the_item;
	}
	

		_galleryLoaded = function(json) {
//	doesn't create enough space for some reason
//			settings.memory.concat(json.attachments);
			if ( json.attachments ) {
				window.status = ( "Loaded " + json.attachments.length + " new items");
				for ( i = 0; i < json.attachments.length; i++ )	{
					if ( json.attachments[i].id && json.attachments[i].id != '' )
						settings.memory.push(json.attachments[i]);
					else
						alert('No ID [_galleryLoaded]');
				}
			} else {
				alert('no json');
			}
		};


			_scaleImage = function(img, bg_container) {

//	get the images parent ( this gives us our size )
				img = jQuery(img);
				
				if ( ! bg_container )
					bg_container = img.parents('div.full-item');

//	get the original image sizes if we don't have them already
				if ( img.attr('rel') ) {
					sizes = img.attr('rel').split(',');
					_iw = sizes[0];
					_ih = sizes[1];
				} else {
					_iw = img.width();
					_ih = img.height();
					img.attr('rel', _iw + ',' + _ih);
				}
				
				_pw = bg_container.width();
				_ph = bg_container.height();
				
				_pratio = _pw/_ph;
				_iratio = _iw/_ih;
				
//	are we scaling to fit or fill ?
				if ( settings.fill ) {
					if ( _pratio > _iratio ) {
						_w = _pw;
						_h = _pw / _iratio;
					} else {
						_w = _ph * _iratio;
						_h = _ph;					
					}
				} else {
					if ( _pratio < _iratio ) {
						_w = _pw;
						_h = _pw / _iratio;
					} else {
						_w = _ph * _iratio;
						_h = _ph;					
					}				
				}
				
				if ( settings.centre ) {
					_ml = (_pw - _w) / 2;
					_mt = (_ph - _h ) / 2;
					
					img.css('margin-top', _mt).css('margin-left', _ml);
				}
				
//				alert('w ' + _w + ' h ' + _h);
//				alert('w ' + _pw + ' h ' + _ph);
//				alert(bg_container.attr('id'))
				img.css('width',_w).css('height',_h);
			}
			
	//		_scaleBackground();
	return this;
}


Array.prototype.array_search = function(p_val) {
	for(var i = 0, l = this.length; i < l; i++) {
		if(this[i].id == p_val) {
			return i;
		}
	}
	return false;
}