/*
	media player plugin
	author: marcus wendt 
	url: www.marcuswendt.com
	requires: jquery
*/

var players = new Array();
var mp_auto_play = true;
var mp_auto_play_interval = 3500;
var mp_fade_duration = 750;

// needs to be called from jquery's document.ready function
function mp_init()
{
	for(id in players) {
		players[id].init();
	};
}


// media player object accessor
function mp(id)
{
	var mp = players[id];
	
	// create a new media player object when necessary
	if(mp == null) {
		mp = new Object();
		// fields
		mp.id = id;
		mp.index = 0;
		mp.playing = false;
		mp.timeout = null;

		// getters
		mp.children = function() {
			return $("#"+this.id+" > li");
		};
		mp.images = function() {
			return $("#"+this.id+" > li > img");
		}
		mp.image_nav = function() {
			return $("#"+this.id+"-image-nav > a");
		}
		mp.size = function() {
			return this.children().length;
		}

		// actions
		mp.init = function() {
			this.images().click(function() {
				mp.click();
			});

			$(this.image_nav().get(0)).addClass("mpLinkActive");
			
			if(mp_auto_play) this.start();
		};
		mp.toggle = function(newIndex, user) {
			// stop auto__play when this is a user generated event (click or next)
			if(user==undefined) user = true;
			if(user && this.playing) { 
				this.playing=false; 
			}
			
			// check bounds
			if(newIndex >= this.size()) newIndex = 0;
			if(newIndex < 0) newIndex = this.size() -1;
			
			// cross-fade images
			$(this.children().get(this.index)).fadeOut(mp_fade_duration);
			$(this.children().get(newIndex)).fadeIn(mp_fade_duration);

			// update navigation
			$(this.image_nav().get(this.index)).removeClass("mpLinkActive");
			$(this.image_nav().get(newIndex)).addClass("mpLinkActive");
			
			this.index = newIndex;
		};
		
		// events
		mp.click = function() {
			this.playing ? this.stop() : this.next(true);
		}		
		mp.start = function() {
			if(!this.playing) {
				this.playing = true;
				setTimeout(function() { mp.loop(); }, mp_auto_play_interval);
			}
		};
		mp.stop = function() {
			if(this.playing) {
				this.playing = false;
				clearTimeout(this.timeout);
			}			
		};
		mp.loop = function() {
			if(this.playing) {
				this.next(false);
				this.timeout = setTimeout(function() { mp.loop(); }, mp_auto_play_interval);
			}
		}
		mp.next = function(user) {
			this.toggle(this.index+1, user);
		};
		mp.prev = function(user) {
			this.toggle(this.index-1, user);
		};		
		
		players[id] = mp;
	}
	
	return mp;
}
