﻿/* 
 * required: jquery.swf.js, jquery.swf.swf
 */	
 
(function() {


jQuery.sound = function(sound_name, mp3, autoplay, methods){
	return new jQuery.sound.fn.init( sound_name, mp3, autoplay);
};

jQuery.sound.fn = jQuery.sound.prototype = {
	exists: false,
	names: {},
	positions: {},
	_position: 0,
	init: function(name){
		
		if(!jQuery.sound.fn.swf) jQuery.sound.fn.swf = jQuery.swf( $("<div></div>").appendTo("body").css({position: "absolute", top: -500, left: -500}) );
		
		if(name) jQuery.sound.fn.name = this.name = name;
		var self = this;
		
		jQuery.sound.fn.swf.ready(function(){
			if(!jQuery.sound.fn.names[self.name]) jQuery.sound.fn.swf.obj(self.name, "Sound");
			jQuery.sound.fn.names[self.name] = name;
		});
		
		return this;
	},
	play: function(_position){
		if(!this._position) this._position = 0;
		this.pause();
		if(_position || _position==0) this._position = _position;
		this.swf.obj(this.name).call("start", this._position/1000);
		return this;
	},
	stop: function(){
		this._position = 0;
		this.swf.obj(this.name).call("stop");
		return this;
	},
	pause: function(){
		this._position = this.position();
		this.swf.obj(this.name).call("stop");
		return this;
	},
	volume: function(num){
		if(!num && num!=0) return this.swf.obj(this.name).call("getVolume").response;
		this.swf.obj(this.name).call("setVolume", num);
		return this;
	},
	duration: function(){
		if(this._duration) return this._duration;
		return this._duration = this.swf.obj(this.name).get("duration");
	},
	position: function(){
		return this.swf.obj(this.name).get("position");
	},
	load: function(mp3, autoplay){
		var self = this;
		if(jQuery.isFunction(mp3)){
			if(this.position()) mp3(this);
			else window.setTimeout(function(){ self.load(mp3) }, 100);
			return this;
		}
		this.swf.ready(function(i){
			self.swf.obj(self.name).call("loadSound", mp3, true);
			if(!autoplay) self.stop();
		})
		return this;
	},
	onload: function(func){
		var self = this;
		if(this.position()) func(this);
		else window.setTimeout(function(){ self.onload(func) }, 100);
		return this;
	},
	complete: function(func){
		if(!func) return (this.duration() <= this.position());
		var self = this;
		window.clearTimeout(this.completeTimeout);
		var checkcomplete = function(){
			if(self.complete()){
				self.play(0).stop();
				func(self);
			}
			else self.completeTimeout = window.setTimeout(checkcomplete, 500);
		};
		checkcomplete();
		return this;
	}
}
jQuery.sound.fn.init.prototype = jQuery.sound.fn;




}

)();


