/*
	fatlion's hack slide show using effects
	previous versions caused IE 7 & 8 to "explode" after a few minutes
	Microsoft, you need to get your act together
*/

// Custom additions to the Effect namespace in scriptaculous

Effect.Wait = Class.create();
Object.extend(Object.extend(Effect.Wait.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    if(!this.element) throw(Effect._elementDoesNotExistError);    
	var options = Object.extend({}, arguments[1] || {});
    this.start(options);
  }
});

if (typeof(FATLION) == "undefined") FATLION = {};

FATLION.CrossfadeQueue = Class.create();
FATLION.CrossfadeQueue.prototype = {
	queue: null,
	container: null, 
	delay: 6.0,
	fadeOutTime: 0.5,
	defaultQueueName: "fatlionXFQueue",
	currentNode: 0,
	nextIndex: 0,
	width: 248,
	height: 166,	// defaults
	stopped: false,
	thedivs: null,
	pauseTimeStamp: null,
	
	initialize: function(nodes, container, delay, w, h, fadeOutTime, queueName)
	{
		this.container	= $(container);
		this.queue		= $A(nodes);
	
		if (delay != null) this.delay = delay;
		if (w != null) this.width = w;
		if (h != null) this.height = h;
		if (fadeOutTime != null) this.fadeOutTime = fadeOutTime;
		if (queueName != null) this.defaultQueueName = queueName;
				
		this.thedivs = [];
		this.thedivs[0] = document.createElement('div');
		this.thedivs[1] = document.createElement('div');

		// save them to the <div> container
		this.container.appendChild(this.thedivs[0]);
		this.container.appendChild(this.thedivs[1]);
		
		this.nextIndex = 0;
		this.currentNode = 0;
		
		for (i = 0; i < 2; i++)
			{
			this.thedivs[i].style.visibility = "visible";
			this.thedivs[i].style.position = "absolute";
			this.thedivs[i].style.width = this.width + "px";
			this.thedivs[i].style.height = this.height + "px";
			this.thedivs[i].style.overflow = "hidden";
			}

		this.next();
	},
	
	pause: function()
	{
		var queue = Effect.Queues.get(this.defaultQueueName);
		this.pauseTimeStamp = new Date().getTime();

		// clear the animation's interval to stop it
		if (queue.interval)
			clearInterval(queue.interval);

 		this.thedivs[this.currentNode].style.opacity = 1.0;
		
		//auto resume after some period 
		setTimeout(this.resume.bind(this), 6000);
	},

	stop: function()
	{
		this.stopped = true;
		this.pause();
	},
	
	play: function()
	{
		this.stopped = false;
		this.resume();
	},

	resume: function()
	{
		if (this.stopped || !this.pauseTimeStamp)
			{
			return;
			}

		var delay = new Date().getTime() - this.pauseTimeStamp;
		this.pauseTimeStamp = null;
		
		// kickstart the queue again, delaying each by however long the user has lingered...
		var queue = Effect.Queues.get(this.defaultQueueName);
		
		queue.each(function(e)
			{
			e.startOn  += delay;
		    e.finishOn += delay;
			});
		
		queue.interval = setInterval(queue.loop.bind(queue), 40);
	},
	
	delayer: function(current, future)
	{
		current.style.zIndex	= 1.0;
		future.style.zIndex		= 2.0;
		
		new Effect.Wait(current, { duration: this.delay, 
						queue: { position:'end', scope: this.defaultQueueName},
						afterFinish: this.next.bind(this)
						});
	},
		
	next: function()
	{
		var current	= this.thedivs[this.currentNode];
		var future	= this.thedivs[1 - this.currentNode];

		future.innerHTML = this.queue[this.nextIndex];

		this.currentNode = 1 - this.currentNode;
		this.nextIndex++;
		
		if (this.nextIndex > this.queue.length - 1)
			{
			this.nextIndex = 0; // just to loop back to the start
			}
		
		// fade in twice as fast as out
		new Effect.Opacity(future, { duration: this.fadeOutTime / 2, transition: Effect.Transitions.linear, from: 0.0, to: 1.0 });
		new Effect.Opacity(current, { duration: this.fadeOutTime, 
							transition: Effect.Transitions.linear, 
							from: 1.0, to: 0.0,  queue: { position:'end', scope: this.defaultQueueName },
							afterFinish: (function() { this.delayer(current, future); }).bind(this) });
	}
}

var CrossfadeLoader = Class.create();
Object.extend(CrossfadeLoader.prototype, {
	
    errorURL:           '<a href="images/sailplanes/slide0.jpg" class="fader2" rel="lightbox[f1]" title="Pictures from Greg Smith"><img src="images/sailplanes/sm/slide0_sm.jpg" alt="Last Flight Of The Day" width="248" height="166" border="0"></a>',
	items:              null,
    delay:              1,
    width:              248,    // default sizes
    height:             166,
    
	initialize: function(container,feeder,delay,width,height)
	{
        this.feedURL = feeder;
        this.objref = $(container);
		this.items = [];
		
        if (delay != null) this.delay = delay;
            
        if (width != null) this.width = width;
            
        if (height != null) this.height = height;
        
		new Ajax.Request(
			this.feedURL,
			{
				method: "get",
				onSuccess: function(response)
					{
					this.parseXML(response.responseXML);
                    this.doit();
					}.bind(this),
					
				onFailure: function()
					{
					console.log("Please visit http://www.fatlion.com/sailplanes/pictures.html.");
                    new FATLION.CrossfadeQueue(this.errorURL, this.objref, this.delay);	
					},
					
				onException: function(req, err) 
					{
					// throw(err);
					}
			}
		);
	},
		
	parseXML: function(xml)
    {
        var caption = "";
        
		// build the array of news titles
		$A(xml.getElementsByTagName("item")).each(function(item)
            {
            // make title optional and use the last one (to save loading space and time)
            if (item.getElementsByTagName("title")[0].childNodes[0] != null)
                {
                caption = item.getElementsByTagName("title")[0].childNodes[0].nodeValue;
                }
                
			var url  = item.getElementsByTagName("url")[0].childNodes[0].nodeValue;
			var link = item.getElementsByTagName("link")[0].childNodes[0].nodeValue;
            var item = '<a href="' + link + '" class="fader2" rel="lightbox[f1]" title="' + caption + '"><img src="' + url + '"';
            
            if (this.width > 0)
                {
                item += ' width="' + this.width + '"';
                }
                
            if (this.height > 0)
                {
                item += ' height="' + this.height + '"';
                }
            
            item += ' border="0"></a>';
            
			//this.items.push({title: title, link: link, url: url});
            // '<a href="images/sailplanes/slide0.jpg" class="fader2" rel="lightbox[f1]" title="Picture title"><img src="images/sailplanes/sm/slide0_sm.jpg" alt="caption" width="248" height="166" border="0"></a>'
            //this.items.push('<a href="' + link + '" class="fader2" rel="lightbox[f1]" title="' + caption + '"><img src="' + url + '" width="' + this.width + '" height="' + this.height + '" border="0"></a>');
            
            this.items.push(item);
            }.bind(this));
        
        // mix 'em up
        this.items.sort(function() {return 0.5 - Math.random();});
	},
	
	doit: function()
    {
		new FATLION.CrossfadeQueue(this.items, this.objref, this.delay, this.width, this.height); // items, parent, delay
	}
	
});





