var JPlayer = null;

if (!window.console) console={log:function(){}}

var Player = new Class({
	options:      null,
	soundManager: null,
	currentSound: null,
	currentVolume: 100,
	currentInterface: null,
	currentUrl: null,
	id3BaseUrl: null,
	imagePrevUrl: null,
	funcOpenPopup: null,
	funcClosePopup: null,
	funcRefreshContent: null,
	ratingSubmitted: false,	
	trackListing: null,
	trackPos: 0,
	trackOrder: [],
	trackListingMode: false,
	defaultImage: false,
	scroller: null,	
	videoPlayerShown: false,
	videoPlaying: false,
	videoPlayerRoot: false,
	videoPlayOnLoad: false,
	videoStreamPort: 81,
	videoLastVol: 0,
	videoCommandDelay: 0,
	ready: false,

	initialize: function(options) {
		this.options = options;
		this.soundManager = options.soundManager;
		this.soundManager.onload = this.managerLoaded.bind(this);
		this.soundManager.onerror = this.managerError.bind(this);
		this.prepareExtControls( );

		if(window.ie6) {
			this.applyPngFix( );
		}	
		
		this.ready = true;	
	},

	applyPngFix:function ( ) {
		var elements = $ES('#player *');
		elements.each(function(el) {
			var bg = el.currentStyle.backgroundImage;
			if(bg!="none") {
				var m = bg.match(/\(.*\)/);		
				var url = m[0];
				url = url.replace(/(\(|\)|\'|\")/g, '');
				if(url.substring(url.length - 4) == ".png") {
					el.setStyle("background-image",
						"url("+url.substring(0, url.length - 4)+".gif"+")"
					);
				}
			}	
		});
	},

	managerLoaded: function( ) {
		var showVideo = false;
		if(this.options.autoLoadUrl) {
			var ps = this.options.autoLoadUrl.split(".");
			var type = ps[ps.length - 1];

			if(type != "mp3")
				showVideo = true;
		}

		if(this.options.videoPlayerElement) {
			this.setVideoPlayerElement(this.options.videoPlayerElement, this.options.bodyElement);
		}

		if(this.options.interfaceElement) this.setInterfaceElement(
			this.options.interfaceElement, this.options.bodyElement, showVideo
		);

		if(this.options.id3BaseUrl) this.id3BaseUrl = this.options.id3BaseUrl;
		if(this.options.imagePrevUrl) this.imagePrevUrl = this.options.imagePrevUrl;
		if(this.options.submitBaseUrl) this.submitBaseUrl = this.options.submitBaseUrl;
		if(this.options.errorDiv) this.currentInterface.error = this.options.errorDiv;

		if(this.options.autoLoadUrl) {
			var ps = this.options.autoLoadUrl.split(".");
			var type = ps[ps.length - 1];

			if(type == "mp4")
				(function( ) {this.playVideoUrl(
					this.options.autoLoadUrl, this.options.startFrames, false, this.options.autoPlay
				)}).delay(600, this);
			else {
				this.playUrl(
					this.options.autoLoadUrl, this.options.startFrames, false, this.options.autoPlay
				);
			}
		}
		if(this.options.funcOpenPopup) this.funcOpenPopup = this.options.funcOpenPopup;
		if(this.options.funcClosePopup) this.funcClosePopup = this.options.funcClosePopup;
		if(this.options.funcRefreshContent) this.funcRefreshContent = this.options.funcRefreshContent;
		if(this.options.defaultImage) this.defaultImage = this.options.defaultImage;

		if(this.options.trackListing) {
			this.trackListing = this.options.trackListing;
			this.trackPos = 0;
			this.tracskOrder =[];
		}
	},

	showVideoPlayer: function( ) {
		if(!JPlayer) return;
		console.log(JPlayer);
		this.videoPlayerShown = true;
		if(this.currentSound) this.currentSound.stop( );
		var element = new Element(JPlayer.parentNode);
		new Fx.Style(this.currentInterface.scroller.marqueeEl, "opacity").start(0);
		if(this.trackListing) {
		    console.log("Force generating video tracklist.");
		    this.makeTracklist.delay(600, this);
		}
		new Fx.Style(this.currentInterface.root,"opacity").start(0).chain(
			function( ) { 
				JPlayer.width = 352;
				JPlayer.height = 288;
				JPlayer.style.width = 352;
				JPlayer.style.height = 288;
				$('vplyr').style.width = 352;
				$('vplyr').style.height = 288;				

				new Fx.Style(this.videoPlayerRoot, "opacity").start(1);
				if(this.currentInterface.scroller) 
					this.currentInterface.scroller.pauseMarquee( ); 
			}.bind(this)
		);
	},

	hideVideoPlayer: function( ) {
		this.videoPlayerShown = false;
		if(this.sendVEvent) {
			this.sendVEvent("STOP");
		}
		new Fx.Style(this.videoPlayerRoot,"opacity").start(0).chain(
			function( ) { 
				JPlayer.width = 1;
				JPlayer.height = 1;
				JPlayer.style.width = 1;
				JPlayer.style.height = 1;
				new Fx.Style(this.videoPlayerRoot, "opacity").start(0.1);
				this.videoPlayerRoot.setStyle("display", "block");
				this.setVolbarPosition(this.currentVolume / 100, true);
				//this.videoPlayerRoot.setStyle("display", "none");
				this.currentInterface.root.setStyle("display", "block");
				new Fx.Style(this.currentInterface.scroller.marqueeEl, "opacity").start(1);
				new Fx.Style(this.currentInterface.root,"opacity").start(1);
				if(this.currentInterface.scroller) 
					this.currentInterface.scroller.unpauseMarquee( ); 
			}.bind(this)
		);
	},

	skipVideoTrack: function(pos, play) {
		if(!this.videoPlayerShown) {
			this.showVideoPlayer( );
		}

		this.sendVEvent("ITEM", pos);
		if(play) {
			this.sendVEvent("PLAY", true);
		} else this.sendVEvent("PLAY", false);
	},

	sendVEvent: function(id, value, resetDelay) {
	    if(resetDelay) this.videoCommandDelay = 0;
		console.log("Sending video event "+id+"=> ", value);
        if(this.videoCommandDelay) {
            console.log("Video command delay specified, delaying by %d", this.videoCommandDelay);
 			this.sendVEvent.delay(this.videoCommandDelay, this, [id, value, true]);           
 			return;
        }

		if(id == "VOLUME" && value == this.videoLastVol) {
			console.log("Skipping, no change");
		}

		if(!JPlayer.sendEvent) {
			console.log("Delayed - no send event method available.", JPlayer.sendEvent);
			this.sendVEvent.delay(2000, this, [id, value]);
		}
		else {
			console.log("Event %s sent.", id);
			if(id == "VOLUME") this.videoLastVol = value;
			JPlayer.sendEvent(id, value);
		}
	},

	playVideoUrl: function(url, startPos, id3, autoPlay, tlist, count) {
		console.log("Playing video url %s, start: %d, autoplay: %b.", url, startPos, autoPlay);

		if(!this.videoPlayerShown) {
			this.showVideoPlayer( );
		}

		this.currentUrl = url;
		var id = this.urlToId(url);
		var parts = url.split("/");
		if(!count) count = 0;

		if(!JPlayer.sendEvent) {
			count++;
			if(count == 5) $clear(this.vUrlD); else
			this.vUrlD = this.playVideoUrl.delay(2000, this, [url, startPos, id3, autoPlay, tlist, count]);
			return;
		} else {
			$clear(this.vUrlD);
			this.sendVEvent("VOLUME", parseInt(this.currentVolume));

			var origUrl = url;
			var pcastId = url.split("-");
			var pid = pcastId[pcastId.length-1].split(".");
			
			var imageUrl = this.imagePrevUrl + parts[parts.length - 3] +"/podcasts/"+
				pid[0]+"-large.png";

			if(this.videoStreamPort) {
				console.log("Stream port set to ",this.videoStreamPort);
				var parts = url.replace("http://", "").split("/");
				url = "http://"+parts[0]+":"+this.videoStreamPort+"/"+parts[3]+"/"+pid[0]+".mp4";
				console.log("Streaming url: ",url);
			}

			var murl = origUrl.split("/");
			console.log(murl);
			new Ajax("/download/register_play/"+murl[6]+"/"+murl[7], {
				method: "get"
			}).request();

			this.sendVEvent("LOAD", {type: "video", file: url, image: imageUrl});
			if(autoPlay) {
				this.sendVEvent("PLAY", true);
				//this.sendVEvent("SEEK", startPos);
			}
		}

		/*if(!tlist) {
			this.trackListingMode = false;
			if(this.trackListing) {
				for(var i=0; i<this.trackListing.length; i++) {
					if(this.trackListing[i] == url) {
						if(this.trackOrder[i])
							this.trackPos = this.trackOrder[i];
						break;
					}
				}
			}		
		}			*/
	},

    loadComments: function(id) {
        if(!this.options.commentsDiv) {
            this.options.commentsDiv = $('comments');
        }

        if(this.options.commentsBase && this.options.commentsDiv) {
            this.options.commentsDiv.setStyle("display", "block");
            id = id.split("-")[1];
            var uid = id.replace(/[^0-9]/g, "");
            this.options.commentsDiv.setHTML("");
            var jsonRequest = new Json.Remote(
			    this.options.commentsBase+uid, {
                    'onComplete': function(o) {
                        this.prepareComments(o);
                    }.bind(this),
                    'onFailure': function( ) {
                        this._addCommentLink();
                    }.bind(this)
			    }
            ).send( );
        }
    },

    _addCommentLink: function( ) {
        if(this.options.commentsBase && this.options.commentsDiv) {
            var a2 = new Element("a", {
                'class': 'add-comment',
                'href': "#"+this.options.commentsDiv.id
            });
            a2.setHTML("Add Comment");
            a2.addEvent("click", function(ev) {
                this.addComment(this.options.commentsDiv);
            }.bind(this));
            a2.inject(this.options.commentsDiv);
        }
    },

    addComment: function(obj) {
        if(!this.options.addCommentDiv)
            this.options.addCommentDiv = $('commentsForm');

        if(this.options.addCommentDiv) {
            try { this.options.addCommentDiv.remove( ); } catch(e) { }
            this.options.addCommentDiv.inject(obj);
            this.options.addCommentDiv.setStyle("display", "block");
            if(showCommentForm) showCommentForm( );
        }
    },

    prepareComments: function(obj) {
        if(obj) {
            var a = new Element("a", {
                'class': 'comments',
                'href': '#'
            });
            a.addEvent("click", function(ev) {
                new Event(ev).stop( );
                this.toggleComments();
            }.bind(this));
            this.commentsShown = false;
            this.currentComments = obj;
            this.options.commentsDiv.empty();
            this._addCommentLink();
            var span = new Element("span");
            span.setHTML(" | ");
            span.inject(this.options.commentsDiv);
            a.setHTML("View Comments ("+obj.num+")");
            a.inject(this.options.commentsDiv);
        }
    },

    toggleComments: function(type) {
        var a = this.options.commentsDiv.getElement("a.comments");
        if(this.commentsShown) {
            this.commentsShown = false;
            a.setHTML(a.innerHTML.replace("Hide", "View"));
            this.options.commentsDiv.getElement("div.commentDetail").remove();
        } else {
            a.setHTML(a.innerHTML.replace("View", "Hide"));
            this.commentsShown = true;
            var comments = new Element("div", {'class': 'commentDetail'});
            if(this.currentComments.comments) {
                this.currentComments.comments.each(function(el) {
                    var comment = new Element("div", {'class': 'comment'});
                    var tdd = new Element("div", {'class': 'date'});
                    tdd.setHTML(
                        el['created'].substring(8, 10)+"/"+
                        el['created'].substring(5, 7)+"/"+
                        el['created'].substring(0,4)+" "+
                        el['created'].substring(11, 13)+":"+
                        el['created'].substring(14, 16)
                    );
                    var tdf = new Element("div", {'class': 'from'});
                    if(el['email']) {
                        tdf.setHTML("<a href='mailto:"+
                            el['email']+"'>"+el['from']+"</a><br />"+el['email']);
                    } else tdf.setHTML(el['from']);
                    var tdc = new Element("div", {'class': 'c_message'});
                    tdc.setHTML(el['message'].replace("\n", "<br />"));
                    tdd.inject(comment);
                    tdf.inject(comment);
                    tdc.inject(comment);
                    comment.inject(comments);
                });
            }
            comments.inject(this.options.commentsDiv);
        }
    },

	playUrl: function(url, startPos, id3, autoPlay, tlist) {
		if(this.videoPlayerShown) {
			this.hideVideoPlayer( );
		}
		this.currentUrl = url;
		var parts = url.split("/");
		var id = this.urlToId(url);
		this.currentId3Url = parts[parts.length-2]+"/"+parts[parts.length-1];
		var cachedSound = this.soundManager.getSoundById(id);

        this.loadComments(parts[parts.length-1].split(".")[0]);

		if(!cachedSound) {
			this.createSound(id, url);
		} else this.currentSound = cachedSound;

		this.startCurrentSound(startPos, id3, autoPlay ? false : true);
		if(!tlist) {
			this.trackListingMode = false;
			if(this.trackListing) {
				for(var i=0; i<this.trackListing.length; i++) {
					if(this.trackListing[i] == url) {
						if(this.trackOrder[i])
							this.trackPos = this.trackOrder[i];
						break;
					}
				}
			}		
		}
		//if(!noPlay) this._onPlayPauseClick( );

	},
	
	managerError: function( ) {
		if(this.currentInterface) {
			hideInterface( );
		}
		if(this.options.errorDiv) {
			$(this.options.errorDiv).setStyle("display", "block");
			new Fx.Style($(this.options.errorDiv), "opacity").start(0, 1);
		}
	},

	urlToId: function(url) {

		var parts = url.split("/");
		return "sound"+parts[parts.length-1].replace(/[^a-zA-Z0-9]/g, "");

	},

	stop: function( ) {
		this.soundManager.stopAll( );
		this.setSeekBarHandlePosition(0);
		this.setPlayPauseButtonState(false);
	},	

	pause: function( ) {
		if(this.currentSound) {
			this.currentSound.resume( );
			this._onPlayPauseClick( );
		}
	},

	startCurrentSound: function(startPos, id3, paused) {
		if(this.currentSound) {
			this.ratingSubmitted = false;
			this.soundManager.stopAll( );
			this.loadingDesc( );

			if(!paused) {
				(function(){this.setVolbarPosition(this.currentVolume / 100); }).delay(50, this); 
				this.soundManager.play(this.currentSound.sID);
			}
			if(startPos) this.currentSound.setPosition(startPos);
			if(!id3) this.retreiveId3(this.currentUrl);
			else {
				this.currentSound.id3 = id3;
				this._onId3( );			
			}

			if(!paused) this.setPlayPauseButtonState(true);
		}
	},

	currentStateToParams: function( ) {
		if(this.currentUrl && this.currentSound)
			return "url="+this.currentId3Url.replace("/", "___")+"/"+
			"position="+this.currentSound.position;

		return "url=none";
	},

	submitRating: function(rating) {
		if(!this.submitBaseUrl) { alert("Sorry, this podcast cannot be rated!"); return; }

		var parts = this.currentId3Url.split("/");
		var file = parts[parts.length-1];
		var url = this.submitBaseUrl+file+"/"+rating;

		new Ajax(url, {
			method: "get",
			onComplete: function(text) {
				this.retreiveId3( );
				var el = this.currentInterface.elements.messageEl;
				el.innerHTML = text;
				if(this.funcRefreshContent) this.funcRefreshContent( );
				var style = new Fx.Style(el, "opacity").start(1).chain(
					function() {
						style.start.delay(1000, this, 0);
					}
				)					
			}.bind(this)	
		}).request();
	},

	retreiveId3: function(url) {
		if(this.id3BaseUrl && this.currentId3Url) {
			var jSonRequest = new Json.Remote(
			    this.id3BaseUrl+this.currentId3Url, {
			onComplete: function(id3){
				this.currentSound.id3 = id3;			    	
				this._onId3( );
			}.bind(this),
			onFailure: function(id3){
				this.currentSound.id3 = null;
				this.resetDesc( );
			}.bind(this)}).send( );
		}
	},

	createSound: function (id, url) { 
		this.soundManager.createSound({
			autoPlay: false,
			id: id,
			url: url,
			//onid3: this._onId3.bind(this),
			onfinish: this._onSoundFinish.bind(this),
			onload: this._onSoundLoad.bind(this),
			whileloading: this._onSoundLoading.bind(this),
			whileplaying: this._onSoundPlaying.bind(this),
			onstop: this._onStop.bind(this),
			volume: this.currentVolume
		});

		this.currentSound = this.soundManager.getSoundById(id); 
	},

	setVideoPlayer: function(el) {
		console.log("External video player loaded: ", el);
		JPlayer = el.getParent( ).getElement("#"+el.id);
		console.log("Set to element: "+JPlayer);
	},

	videoCBVolume: function(obj) {
		console.log("Video callback, VOLUME ", obj.percentage);
		this.setVolbarPosition(obj.percentage / 100, true);
	},

	videoCBNext: function(obj) {
		console.log("Received video callback, NEXT");
		this.changeTrack(1, true);
	},

	videoCBPrev: function(obj) {
		console.log("Received video callback, PREV");
		this.changeTrack(-1, true);
	},

	videoCBPlay: function(obj) {
		console.log("Received video callback, PLAY");
		this.videoPlaying = true;
	},

	videoCBStop: function(obj) {
		console.log("Received video callback, STOP");
		this.videoPlaying = false;
	},

	videoCBLoaded: function(obj) {
		/*if(this.triggerVTrack ) {
			this.sendVEvent("ITEM", this.triggerVTrack );
			this.triggerVTrack = false;
		}*/
	},

	setVideoPlayerElement: function(rootId, body) {
		var body = body ? document.getElementById(body) : document.body;
		if(!body) return;
		var root = document.getElementById(rootId);
		if(!root) return;

        this.ready = false;

		var s1 = new SWFObject("/data/swfs/player.swf","vplyr","1","1","9","#FFFFFF");
		s1.addParam("allowfullscreen","true");
		s1.addParam("allowscriptaccess","always");
		s1.addParam(
		    "flashvars", "controlbar=bottom&streamer=lighttpd&"+
		    ""//"skin=/data/swfs/primarysiteVideo.swf"
		);

		this.videoPlayerRoot = root;
		root.innerHTML = s1.getSWFHTML( );

		JPlayer = root.getElementsByTagName("*")[0];
		console.log("Inserting video player element", JPlayer);
	},

	setInterfaceElement: function(rootId, body, video) {		
		var body = body ? $(body) : $E('body');
		if(!body) return;
		var root = body.getElement("#"+rootId);
		if(!root) return;

		var resume = false;
		if(this.currentSound) {
			if(!this.currentSound.paused) {
				resume = true;				
				this.currentSound.pause( );
			}
			this.setPlayPauseButtonState(false);
		}

		this.removeCurrentInterface( );
		this.currentInterface = {
			root: root,
			body: body,
			elements: this.loadInterfaceElements(root)
		};		

		if(this.currentInterface.elements['descriptionEl'] && Scroller) {
			this.currentInterface.elements['descriptionEl'].setStyle("white-space", "nowrap");
			this.currentInterface.scroller = 
				new Scroller(this.currentInterface.elements['descriptionEl'], 
				{step: 1, delay:18});
				this.origWidth = this.currentInterface.elements['descriptionEl'].getSize( ).size.x;
				setTimeout(this.updateMarqueeSize.bind(this), 100);		
		}

		this.currentInterface.events = this.addInterfaceEvents(
			this.currentInterface
		);
		this.currentInterface.slider = this.createInterfaceSliders(
			this.currentInterface
		);

		this.currentInterface.elements['messageEl'].setOpacity(0); 

		var storedVol = Cookie.get('player_volume');
		if(storedVol) {
			this.setVolbarPosition(parseFloat(storedVol));
		} else this.setVolbarPosition(1);

		if(this.currentSound) {	
			if(resume) {
				this.currentSound.resume( );
				this.setPlayPauseButtonState(true);
			}
		}

		this.showInterface(video);
	},

	updateMarqueeSize: function( ) {
		this.currentInterface.scroller.offsetX = 
			this.currentInterface.root.getElement(".position-status").
				getCoordinates( ).width;		
	},

	setTracklist:function(tracklist) {
	    console.log("Track listing set: ",tracklist);
		this.trackListing = tracklist;
		this.trackPos = 0;
		this.trackOrder = [];


		/*if(this.trackListingMode) {
			this.playTracklist(this.trackListMode - 1);
		}*/
	},

	makeTracklist: function(shuffle) {
		console.log("Making track list");

		this.trackOrder = [];

		for(var i = 0; i<this.trackListing.length;i++) {
			this.trackOrder[this.trackOrder.length] = i;
		}		
		if(shuffle && this.trackOrder.length > 1) {
			for(i = 0; i<this.trackListing.length; i++) {
				var r1 = Math.floor(Math.random()*this.trackListing.length);
				var r2 = Math.floor(Math.random()*this.trackListing.length);

				var t = this.trackOrder[r1];
				this.trackOrder[r1] = this.trackOrder[r2];
				this.trackOrder[r2] = t;
			}
		}

		this._generateSMIL( );
	},

	playTracklist: function(shuffle) {
		this.makeTracklist(shuffle);
		
		if(this.trackOrder.length > 0) {
			this.trackPos = 0;
			this.trackListingMode = shuffle ? 2 : 1;
			this.playUrl(
				this.trackListing[this.trackOrder[0]], 
				0, null, true, true
			);
		}
	},

	prepareExtControls: function( ) {
		var panel = $E('.extControls');

		if(panel) {
			var pAll = panel.getElement('.allNormal');
			if(pAll) {
				pAll.addEvent("click", function(e) {
					this.playTracklist( );
					new Event(e).stop( );
				}.bind(this));
			}
			var pShuf = panel.getElement('.allShuffle');
			if(pShuf) {
				pShuf.addEvent("click", function(e) {
					this.playTracklist(true);
					new Event(e).stop( );
				}.bind(this));
			}
			var next = panel.getElement('.nextTrack');
			if(next) {
				next.addEvent("click", function(e) {
					this.nextTrack( );
					new Event(e).stop( );
				}.bind(this));
			}
			var prev = panel.getElement('.prevTrack');
			if(prev) {
				prev.addEvent("click", function(e) {
					this.prevTrack( );
					new Event(e).stop( );
				}.bind(this));
			}
		}
	},

	showInterface: function(dispVideo) {
		console.log("Showing interface, video = ",dispVideo);
		if(this.currentInterface.root) {
			if(JPlayer) {
				JPlayer.style.width = 1;
				JPlayer.style.height = 1;
				this.videoPlayerRoot.style.display = "block";

				console.log("Send Event? ",JPlayer.sendEvent);
			}
			this.currentInterface.root.setOpacity(0);
			this.currentInterface.root.setStyle("visiblity", "visible");
			if(dispVideo) {
				(function( ) {this.showVideoPlayer( )}).delay(500, this);
			} else {
				this.hideVideoPlayer( );
				new Fx.Style(this.currentInterface.root,"opacity").start(1).chain(
					function( ) { 
						if(this.currentInterface.scroller) 
							this.currentInterface.scroller.start( ); 
					}.bind(this)
				);	
			}
		}
	},	

	hideInterface: function( ) {
		if(this.currentInterface.root) {
			this.hideVideoPlayer( );
			new Fx.Style(this.currentInterface.root,"opacity").start(0).chain(
				function( ) {
					this.currentInterface.root.setStyle(
						"visibility", "hidden"
					);	
				}.bind(this)
			);
		}
	},		

	loadInterfaceElements: function(rootElement) {
		var elements = { };
		var elementClasses = [
			'error', 'interface', 'title', 'position', 'status', 'description',
			'play-pause', 'new-window','close-window', 'seekbar', 'seekbar-buffered', 
			'seekbar-handle', 'volbar-empty', 'volbar-full', 'score', 'message',
			'current-score', 'score-width', 'image'
		];
		elementClasses.forEach(function(elementClass) {
			elements[elementClass.camelCase() + 'El'] = 
				rootElement.getElement('.' + elementClass);
		});


		elements['rootEl'] = rootElement;
		return elements;
	},
				
	addInterfaceEvents: function(iface) {
		var elEvents = {
			root: { 'mousedown': this._onRootMouseDown },
			playPause: { 'click': this._onPlayPauseClick },
			newWindow: { 'click': this._onNewWindowClick },
			closeWindow: { 'click': this._onCloseWindowClick},
			volbarEmpty: { 'mousedown': this._onVolbarMouseDown, 
				'mouseup': this._onVolbarMouseUp },
			volbarFull:  { 'mousedown': this._onVolbarMouseDown, 
				'mouseup': this._onVolbarMouseUp },
			score: { 'mousemove': this._onRatingMouseMove,
				 'mouseleave': this._onRatingMouseLeave,
				 'mousedown': this._onRatingMouseDown }
		};
		var el, events;

		for (var elName in elEvents) {
			events = elEvents[elName];
			for (eventName in events) {
				iface.elements[elName + 'El'].addEvent(eventName, events[eventName].
				bindAsEventListener(this));
			}
		}

		return events;
	},

	createInterfaceSliders: function(iface) {
		var slider = {
			seekbarSlider: new Slider(
				iface.elements.seekbarEl, 
				iface.elements.seekbarHandleEl, {
				onComplete: this._onSeekbarSliderComplete.bind(this)
			})
		};
	
		// Hacky, but we need to know when the slider is being dragged - the api doesn't provide for this
		slider.draggedKnob = slider.seekbarSlider.draggedKnob;
		slider.seekbarSlider.draggedKnob = this._onSeekbarSliderDraggedKnob.bind(this);

		return slider;
	},

	removeCurrentInterface: function( ) {
		/*if(this.currentInterface) {
			this.hideInterface( );
			this.oldinterface = this.currentInterface;
		}*/
	},

	updatePosition: function() {
		var text = this.positionToStr((this.currentSound.playState != 0) ? 
			this.currentSound.position : 0);
		if (this.currentSound.loaded) {
			text += '/' + this.positionToStr(this.currentSound.duration);
		}
		this.setPositionText(text);
		this.updateMarqueeSize( );	
	},

	positionToStr: function(position) {
		var seconds = Math.floor(position / 1000);
		var minutePos = new String(Math.floor(seconds / 60));
		var secondPos = new String(seconds % 60);
		if (secondPos.length < 2) {
			secondPos = '0' + secondPos;
		}
		return minutePos + ':' + secondPos;
	},

	setPositionText: function(text) {
		this.currentInterface.elements.positionEl.empty();
		this.currentInterface.elements.positionEl.appendChild(
			document.createTextNode(text)
		);
	},

	setStatusText: function(text) {
		this.currentInterface.elements.statusEl.empty();
		this.currentInterface.elements.statusEl.appendChild(
			document.createTextNode((text == '') ? '' : ' ' + 
			text.toUpperCase())
		);
		this.updateMarqueeSize( );
	},

	setSeekbarBufferPosition: function(position) {
		position = Math.max(0, Math.min(1, position));

		this.currentInterface.elements.seekbarBufferedEl.setStyle(
			"width",
			Math.floor(position * this.currentInterface.elements.seekbarEl.getCoordinates()
			.width)
		);
	},

	setSeekBarHandlePosition: function(position) {
		position = Math.max(0, Math.min(1, position));
		this.currentInterface.slider.seekbarAutoSet = true;

		this.currentInterface.slider.seekbarSlider.set(
			position * this.currentInterface.slider.seekbarSlider.options.steps
		);
		this.currentInterface.slider.seekbarAutoSet = false;
		this.updatePosition();
	},

	setVolbarPosition: function(position, skipVideo) {
		position = Math.max(0, Math.min(1, position));
		this.volbarPosition = position;

		this.currentInterface.elements.volbarFullEl.style.width = Math.floor(
			position * this.currentInterface.elements.volbarEmptyEl.
			getCoordinates().width
		) + 'px';

		this.currentVolume = position * 100;

		if(!skipVideo && JPlayer && this.sendVEvent) {
			this.sendVEvent("VOLUME", parseInt(this.currentVolume));
		}

		if (this.currentSound) {
			this.currentSound.setVolume(parseInt(this.currentVolume));
		}
	},

	setPlayPauseButtonState: function(playing) {
		this.currentInterface.elements.playPauseEl.removeClass(!playing ? 'pause' : 'play');
		this.currentInterface.elements.playPauseEl.addClass(playing   ? 'pause' : 'play');
		this.setStatusText(playing ? '' : 'Paused');
	},

	setCurrentRating: function(rating) {
		var score = this.currentInterface.elements.currentScoreEl;
		var coords = score.getCoordinates( );

		if(!score.barSize || score.barSize != size) {
			var width = (rating * (coords.width / 5)).toInt( );
			score.getElement(".five").setStyle("width", width);
		}
	},	

	_onId3: function( ) {
		var title = "";
		if(this.currentSound.id3.TIT2) title = this.currentSound.id3.TIT2;
			else title = "Unknown Podcast";
		var desc = "";
		if(this.currentSound.id3.TALB) title+="<br />"+this.currentSound.id3.TALB;
		if(this.currentSound.id3._SUM) desc+=this.currentSound.id3._SUM+" - ";

		var copy = "";
		if(this.currentSound.id3.TYER) copy+=this.currentSound.id3.TYER+" ";
		if(this.currentSound.id3.TPE1) copy+=this.currentSound.id3.TPE1;
		if(copy) desc+="(c) "+copy;

		var maxSize = this.currentInterface.elements.imageEl.getSize( );
		var imSrc;
		if(this.currentSound.id3._IMG) {
			imSrc = this.currentSound.id3._IMG;
		} else imSrc = this.defaultImage;

		if(this.currentSound.id3.DUR) {
			//this.currentSound.duration = this.currentSound.id3.DUR;
			//this.currentSound.durationEstimate = this.currentSound.id3.DUR;
		}

		var el = new Element("img");
		var ratio = 1.0;		
		el.src = imSrc;

		if(el.height > el.width) {
			ratio =  maxSize.size.y / el.height;
		} else ratio = maxSize.size.x / el.width;
	
		var newW = ratio * el.width;
		var newH = ratio * el.height;

		var img = this.currentInterface.elements.imageEl.getElement('img');

		new Fx.Style(img, "opacity").start(0).chain(function( ) {
			img.src = imSrc;
			img.width =  newW.toInt( );
			img.height = newH.toInt( );

			new Fx.Style(img, "opacity").start(1);
		}.bind(this));
		
		desc+=" ... Powered By PrimaryPodcast.com";

		if(this.currentSound.id3.RATE) {
			this.setCurrentRating(this.currentSound.id3.RATE);
		}
		
		if(this.currentInterface.elements.titleEl)
			this.currentInterface.elements.titleEl.innerHTML = title;
		if(this.currentInterface.elements.descriptionEl)
			this.currentInterface.elements.descriptionEl.innerHTML = desc;

		var el = this.currentInterface.elements.descriptionEl.clone( );

		size = (desc.length * this.currentInterface.elements.descriptionEl.
			getStyle("font-size").toInt( )) / 1.75;

		if(this.currentInterface.scroller)
			this.currentInterface.scroller.updateContentHTML(
				this.currentInterface.elements.descriptionEl.innerHTML, size
			);

	},

	_onRootMouseDown: function(e) {
		new Event(e).preventDefault();
	},

	_onPlayPauseClick: function(e) {
		if(this.currentSound) {
			if (this.currentSound.playState == 0) {
				(function(){this.setVolbarPosition(this.currentVolume / 100); }).delay(50, this); 
				this.currentSound.play();
			} else if (this.currentSound.paused) {
				this.currentSound.resume();
			} else {
				if(this.currentSound.pause) this.currentSound.pause();
			}
			this.setPlayPauseButtonState(!(this.currentSound.playState == 0
				 || this.currentSound.paused));
		}
		new Event(e).preventDefault();
	},

	_onNewWindowClick: function(e) {
		if(this.funcOpenPopup) this.funcOpenPopup(this);
		new Event(e).preventDefault();
	},
	_onCloseWindowClick: function(e) {
		if(this.funcClosePopup) this.funcClosePopup(this);
		new Event(e).preventDefault();
	},
	_onVolbarMouseDown: function(e) {
		this.volbarMouseDown = true;
		this._onVolbarMouseMove(e);
		this._onVolbarMouseMoveBound = this._onVolbarMouseMove.bindAsEventListener(this);
		this._onVolbarMouseUpBound = this._onVolbarMouseUp.bindAsEventListener(this);
		this.currentInterface.body.addEvent('mousemove', this._onVolbarMouseMoveBound);
		this.currentInterface.body.addEvent('mouseup', this._onVolbarMouseUpBound);
	},

	_onVolbarMouseMove: function(e) {
		if (this.volbarMouseDown) {
			var targetCoords = this.currentInterface.elements.volbarEmptyEl.getCoordinates();
			this.setVolbarPosition((e.clientX - targetCoords.left) / (targetCoords.width - 1));
			new Event(e).preventDefault();
		}
	},
	_onVolbarMouseUp: function(e) {
		this._onVolbarMouseMove(e);
		this.volbarMouseDown = false;
		this.currentInterface.body.removeEvent('mousemove', this._onVolbarMouseMoveBound);
		this.currentInterface.body.removeEvent('mouseup', this._onVolbarMouseMoveBound);

		if(this.currentVolume) Cookie.set("player_volume", this.currentVolume / 100, {duration: 30});
	},

	_onSeekbarSliderComplete: function(step) {
		this.currentInterface.slider.seekbarHandleDragging = false;
		if (!this.currentInterface.slider.seekbarAutoSet) {
			var position = step / this.currentInterface.slider.seekbarSlider.options.steps;

			this.currentSound.setPosition(position * (this.currentSound.loaded ?
				this.currentSound.duration : this.currentSound.durationEstimate));
		}
	},

	_onSeekbarSliderDraggedKnob: function() {
		if(this.currentSound.bytesLoaded && this.currentSound.bytesTotal) {
			this.currentInterface.slider.seekbarHandleDragging = true;
			this.currentInterface.slider.draggedKnob.apply(
				this.currentInterface.slider.seekbarSlider, this.arguments ? this.arguments : [ ]
			);
	
		}
	},

	_onSoundFinish: function() {
		this.setSeekBarHandlePosition(0);
		this.setPlayPauseButtonState(false);

		this.nextTrack( );
	},

	_generateSMIL: function( ) {
		var smilURL = [];

		var tl;
		var parts;
		var p;

		if(this.trackOrder.length == 0) return;

		this.trackOrder.each(function(el ,i) {
			tl = this.trackListing[el];
			parts = tl.split("/");
			p = parts[parts.length-1].split("-");
			smilURL.push(p[p.length-1]);
		}.bind(this));

		smilURL = this.id3BaseUrl+"SMIL/"+smilURL.join("_")+".xml";
        console.log(smilURL);
		if(JPlayer && this.sendVEvent) {
			this.sendVEvent("LOAD", smilURL);
			this.videoCommandDelay = 500;
		}
	},

	updateTrack: function(forcePlay) {
		if(this.tracklistTimer) $clear(this.tracklistTimer);

		var play = false;
		if((this.currentSound && this.currentSound.playState) || this.videoPlaying || forcePlay) {
			play = true;
		}

		console.log("Attempting to skip to track position ",this.trackPos, " (play=",play,")");

		if(this.trackListing[this.trackOrder[this.trackPos]].substring(
			this.trackListing[this.trackOrder[this.trackPos]].length - 4
		) == ".mp3")
			this.playUrl(
				this.trackListing[this.trackOrder[this.trackPos]], 
				0, null, play, true
			);
		else this.skipVideoTrack(this.trackOrder[this.trackPos], play);

	},

	changeTrack: function(inc, forcePlay) {
		if(!inc) inc = 1;

		if(this.trackListing && this.trackListing.length > 1) {
			if(this.trackOrder.length != this.trackListing.length)
				this.makeTracklist( );

			if(this.tracklistTimer) $clear(this.tracklistTimer);
			
			this.trackPos+=inc;

			if(this.trackPos > (this.trackOrder.length - 1)) {
				this.trackPos = 0;
			} else if(this.trackPos < 0) this.trackPos = this.trackOrder.length - 1;


			this.tracklistTimer = (function(){
				this.updateTrack(forcePlay);
			}).periodical(300, this);
			/*this.setTrack({bool: true});

			this.trackPos++;
			if(this.trackPos > (this.trackOrder.length - 1)) {
				this.trackPos = 0;
			}
			this.playUrl(
				this.trackListing[this.trackOrder[this.trackPos]], 
				0, null, this.trackListingMode, true
			);

			this.setTrack.pass({bool: false}).delay(900);*/
		}
	},

	nextTrack: function( ) {
		this.changeTrack(1);
	},

	prevTrack: function( ) {
		this.changeTrack(-1);
	},

	_onStop: function() {
		this.stop( );
		//his._onSoundFinish( );
	},

	_onSoundLoad: function() {
		if(this.currentSound.readyState == 2) this.loadError( );
		this.setSeekbarBufferPosition(1);
	},

	_onSoundLoading: function() {
		if(this.currentSound.bytesLoaded && this.currentSound.bytesTotal) {
			this.setSeekbarBufferPosition(
				this.currentSound.bytesLoaded / this.currentSound.bytesTotal
			);
		} else {
			this.setSeekbarPosition(0);
		}
	},

	_onSoundPlaying: function() {
		if (!this.currentInterface.slider.seekbarHandleDragging) {
			this.setSeekBarHandlePosition(
				this.currentSound.position / 
				(this.currentSound.loaded ? this.currentSound.duration :
					 this.currentSound.durationEstimate)
			);
		}
	},
		
	_onRatingMouseMove: function(e) {
		if(!this.ratingSubmitted) {
			var score = this.currentInterface.elements.scoreEl;
			var maxWidth = this.currentInterface.elements.currentScoreEl.
						getCoordinates( ).width;
			var coords = score.getCoordinates( );
			var ev = new Event(e);
			var posX = ev.page.x - coords.left;
			var size = Math.ceil(
				posX / (coords.width / 5)
			);

			if(!score.barSize || score.barSize != size) {
				var width = (size * (maxWidth / 5)).toInt( );
				score.getElement(".five").setStyle("width", width);
				this.currentInterface.elements.scoreEl.setScore = size;
			}
		}
	},

	_onRatingMouseLeave: function(e) {
		if(!this.ratingSubmitted)
			this.currentInterface.elements.scoreEl.
				getElement(".five").setStyle("width", 0);
	},

	_onRatingMouseDown: function(e) {
		if(!this.ratingSubmitted) {
			this.ratingSubmitted = this.submitRating(
				this.currentInterface.elements.scoreEl.setScore	
			);
		}
		this.ratingSubmitted = true;
	},



	loadError: function() {
		alert(
			"Sorry, we are unable to load this podcast.\n"+
			"Please try again, or contact a system administrator\n"+
			"if the problem persists."
		);			
	},

	resetDesc: function() {
		if(this.currentInterface.elements.descriptionEl && this.defDesc)
			this.currentInterface.elements.descriptionEl.innerHTML = this.defDesc;
		if(this.currentInterface.elements.titleEl && this.defTitle)
			this.currentInterface.elements.titleEl.innerHTML = this.defTitle;
	},

	loadingDesc: function() {
		if(this.currentInterface.elements.descriptionEl && this.defDesc)
			this.currentInterface.elements.descriptionEl.innerHTML = 
			"Retreiving Podcast Details...";
		if(this.currentInterface.elements.titleEl && this.defTitle)
			this.currentInterface.elements.titleEl.innerHTML = 
			"Please Wait<br />Loading...";
	}
})
