var SearchString = [];

var Moxy = new Class({
	Implements:[Options],
	options:{
		authWeb:'http://moxytunes.com/music_moxy/mp3.php',
		authType:'post',
		authValue:'auth'
	},
	initialize: function(options){
		this.setOptions(options);
		this.LoadCounter = 0;
		window.addEvent('load', function() {
			this.checkPlaylistClass();
		}.bind(this));
	},
	checkPlaylistClass: function(){
		if(Playlist && Playlist.flashLoaded)
			this.playlist = true;
		else {
			this.LoadCounter++;
			if(this.LoadCounter == 300){
				alert('Failed to load Audio Player after 30 seconds');
			}
			this.checkPlaylistClass.delay(100,this);
		};
		
	},
	changeVolume: function(volume){
		MusicObj.volume = volume;
		if(Playlist.sounds[this.currentSong]){
			Playlist.sounds[this.currentSong].setVolume(volume);
		}
	},
	loadSong: function(SongID,duration){
		this.currentSongID = SongID;
		if(Playlist.sounds['http://moxytunes.com/music_moxy/mp3.php?id=' + SongID]){
			this.pause();
			Playlist.sounds[this.currentSong].pausedAt = 0;
			this.currentSong = 'http://moxytunes.com/music_moxy/mp3.php?id=' + SongID;
			Playlist.sounds[this.currentSong].pausedAt = 0;
			this.play();
		}else{
			if(Playlist.sounds[this.currentSong]){
				this.pause();
				Playlist.sounds[this.currentSong].pausedAt=0;
			}
			
			this.auth(SongID);
			
		}
	},
	loadAfterAuth: function(){
		Playlist.loadSound('http://moxytunes.com/music_moxy/mp3.php?id=' + this.currentSongID,MusicObj);
		this.currentSong = 'http://moxytunes.com/music_moxy/mp3.php?id=' + this.currentSongID;
		//this.currentSongObj = Playlist.sounds['http://moxytunes.com/music_moxy/mp3.php?id=' + SongID];
		Moxy_Controls.createProgressBar(Playlist.sounds[this.currentSong].getDuration());
		Playlist.sounds[this.currentSong].parent = this;
		this.play();
	},
	play: function(){
		Playlist.sounds[this.currentSong].start();
		Playlist.sounds[this.currentSong].setVolume(MusicObj.volume);
		Playlist.sounds[this.currentSong].paused = false;
	},
	pause: function(){
		Playlist.sounds[this.currentSong].pause();
		Playlist.sounds[this.currentSong].paused = true;
	},
	auth: function(id){
		if(this.options.authWeb != false){
			if(this.options.authType == 'post')
			myHTMLRequest = new Request({method: 'post', url: this.options.authWeb,onComplete:this.loadAfterAuth.bind(this)}).send(this.options.authValue + "=" + id);
		}
	}
});

Moxy_Controls = new Class({
	Implements:[Options],
	options:{		
		styledvolume:'background_vol',
		styledvolumeknob:'knob_vol',
		progressbar:'progress_pwrapper',
		progressknob:'knob_progress',
		progressbg:'background_progress',
		defaultVol:80,
		
		titleBox:'title_infobox',
		artistBox:'artist_infobox',
		albumBox:'album_infobox',
		genreBox:null,
		artBox:null,
		
		prevbtn: 'back_controls',
		ppbtn: 'playpause_controls',
		forwardbtn: 'forward_controls',
		uploadbtn: 'Upload_player',
		librarybtn: 'Library_player',
		searchbox: 'Search_player',
		aboutbtn: 'About_player'
	},
	initialize: function(options){
		window.addEvent('load', function() {
			this.createVolumeBar();
			this.setButtonEvents();
		}.bind(this));
		this.tempval = '';
	},
	setButtonEvents: function(){
		$(this.options.ppbtn).addEvent('click',function(event){
				var RemoveClass = '_Playing';
				var AddClass = '_Paused';
				if(Playlist.sounds[Moxy.currentSong].paused == false){
					Moxy.pause();
				}else{
					Moxy.play();
					RemoveClass = '_Paused';
					AddClass = '_Playing';
				}
				this.removeClass(RemoveClass);
				this.addClass(AddClass);
		});
		$(this.options.prevbtn).addEvent('click',function(event){
			if(!this.hasClass('_PREVdisabled'))
				Library.getPrevious();
		});
		$(this.options.forwardbtn).addEvent('click',function(event){
			if(!this.hasClass('_FFdisabled'))
				Library.getNext();
		});
		$(this.options.uploadbtn).addEvent('click',function(event){
			Library.showUpload();
		});
		$(this.options.librarybtn).addEvent('click',function(event){
			Library.showLibrary(true);
		});
		$(this.options.aboutbtn).addEvent('click',function(event){
			if($('about').hasClass('hidepage'))
				$('about').removeClass('hidepage');
			else
				$('about').addClass('hidepage');
		});
		(function(){
			if(this.tempval != $(this.options.searchbox).value){
				this.tempval = $(this.options.searchbox).value;
				this.checkCurrentSearch.delay(800,this);
			}
		}).periodical(50,this);
	},
	checkCurrentSearch: function(){
		if(this.tempval == $(this.options.searchbox).value){
			Library.search(this.tempval);
			
		}
	},
	createVolumeBar: function(){
		this.volumeSlider = new Slider($(this.options.styledvolume), $(this.options.styledvolumeknob), {
			steps:255,
			onChange: function (step) {
				Moxy.changeVolume(step);
			}
		}).set(this.options.defaultVol);
	},
	setSongInfo: function(Title,Artist,Album,Genre,Art){
		if(Title && this.options.titleBox)$(this.options.titleBox).innerHTML = Title;
		if(Artist && this.options.artistBox)$(this.options.artistBox).innerHTML = Artist;
		if(Album && this.options.albumBox)$(this.options.albumBox).innerHTML = Album;
		if(Genre && this.options.genreBox)$(this.options.genreBox).innerHTML = Genre;
		if(Art && this.options.artBox)$(this.options.artBox).innerHTML = Art;
		
	},
	createProgressBar: function(duration){
		if(isNaN(duration)||duration==Infinity)
			this.createProgressBar.delay(100,this,Playlist.sounds[Moxy.currentSong].getDuration())
		else{
			if(this.ProgressBar){
				$(this.options.progressbar).removeEvents('mousedown');
				$(this.options.progressknob).removeEvents('mousedown');
			}
			this.ProgressBar = new Slider($(this.options.progressbar), $(this.options.progressknob), {
				steps:(duration/10),
				snap: true,
				onChange: function (step) {
					(function(){$(this.options.progressbg).style.width = $(this.options.progressknob).style.left}).delay(10,this);
					if(Playlist.sounds[Moxy.currentSong] && (this.oldstep > step +200 || this.oldstep < step -200 )){
						if(Playlist.sounds[Moxy.currentSong].paused)
							Playlist.sounds[Moxy.currentSong].pausedAt = (step*10);
						else
							Playlist.sounds[Moxy.currentSong].jumpTo(step*10);
					}
					this.oldstep = step;
				}.bind(this)
			});
		}
	},
	disableButton: function(button,disabled){
		var buttonele = '' ,AddClass = '',RemoveClass = '';
		switch(button){
			case 'forward':
				buttonele = $(this.options.forwardbtn);
				if(!disabled){
					AddClass = '_FF';
					RemoveClass = '_FFdisabled';
				}else{
					AddClass = '_FFdisabled';
					RemoveClass = '_FF';
				}
				break;
			case 'previous':
				buttonele = $(this.options.prevbtn);
				if(!disabled){
					AddClass = '_PREV';
					RemoveClass = '_PREVdisabled';
				}else{
					AddClass = '_PREVdisabled';
					RemoveClass = '_PREV';
				}
				break;
		}
		buttonele.addClass(AddClass);
		buttonele.removeClass(RemoveClass);
		
	}
});
Library = new Class ({
	Implements: [Options],
	
	options:{
		cssSelected: 'library_item_selected',
		cssHover: 'library_item_hover',
		cssNormal: 'library_item_normal',
		repeat: false,
		menudiv: 'menudiv',
		playlistmenu: 'playlistMenu',
		playlistSelector:'playlistSelector'
	},
	
	initialize: function(options){
		this.setOptions(options);
		this.currentViewLibraryID = 'library';
		this.Elements = [];
		this.Elements['library'] =  $(this.currentViewLibraryID).getElements('.song');
		var loadEvent = (Browser.Engine.gecko)?'domready':'load';
		window.addEvent(loadEvent, function() {
			new SortingTable( 'library' );
			
				
			if(Browser.Engine.trident){
				if(!IE8){
					$('libraryholder').style.position = 'relative';
					$('sidebar_library').style.position = 'absolute';
					$('sidebar_library').style.top = '0';
					$('sidebar_library').style.left = '0';	
				}
				(function(){
					docwidth = document.documentElement.clientWidth;
					if(document.documentElement.clientWidth == 0)
						docwidth = document.body.clientWidth;
					docheight = document.documentElement.clientHeight;
					if(document.documentElement.clientHeight == 0)
						docheight = document.body.clientHeight;
					if(this.width !=docwidth){
						this.width = docwidth;
						
						$('playlist_library').style.width = (parseInt(this.width) - parseInt($('sidebar_library').getStyle('width')) - 20) + 'px';
						if(!IE8)
							$('playlist_library').style.paddingLeft = (parseInt($('sidebar_library').getStyle('width')) + 10) + 'px';
						else{
							$('playlist_library').style.marginLeft = (parseInt($('sidebar_library').getStyle('width')) + 10) + 'px';
						}
					}
					if(this.height != docheight){
						this.height  = docheight;
						$('playlist_library').style.height = (parseInt(this.height) - (20 + parseInt($('player').getStyle('height')) + parseInt($('menuholder').getStyle('height')) + parseInt($('header').getStyle('height'))) ) + 'px';
					}
				}).periodical(1,this);
			}else
				(function(){
					if(this.width !=document.body.clientWidth){
						this.width = document.body.clientWidth;
						
						$('playlist_library').style.width = (parseInt(this.width) - parseInt($('sidebar_library').getStyle('width')) - 10) + 'px';
						$('playlist_library').style.marginLeft = (parseInt($('sidebar_library').getStyle('width')) + 10) + 'px';
					}
					if(this.height != window.innerHeight){
						this.height  = window.innerHeight;
						$('playlist_library').style.height = (parseInt(this.height) - (20 + parseInt($('player').getStyle('height')) + parseInt($('menuholder').getStyle('height')) + parseInt($('header').getStyle('height'))) ) + 'px';
					}
				}).periodical(1,this);
			(function(){this.width =0;this.height =0;}).delay(100,this)
			this.startFancyUpload();
			this.disableHighlight($('playlist_library'));
			this.startLibrary();
			$('libraryholder').addEvent('onclick',function(){
				$(this.options.menudiv).addClass('hidepage');
			});
		}.bind(this));		
	},
	startLibrary: function(){
		this.searchArray =[];
		$$('.folder > a').each(function(el){
			el.addEvent('click',function(event){
				if($(el.parentNode).hasClass('hidefolder')){
					$(el.parentNode).removeClass('hidefolder');
					this.keyupdater('foldervisible' + el.parentNode.id.substring(6),'true');
				}else{ 
				$(el.parentNode).addClass('hidefolder');
				this.keyupdater('foldervisible' + el.parentNode.id.substring(6),'false');
				}
				}.bind(this));
			}.bind(this));
		var selectbox = $('playlistselectbox');
		this.reloadSelectBoxes();
	},
	reloadSelectBoxes: function(){
		$('playlistselectbox').innerHTML = '<option value="Select">Select Playlist</option>';
		$('renameplaylistselectbox').innerHTML = '<option value="Select">Select Playlist</option>';
		$('deleteplaylistselectbox').innerHTML = '<option value="Select">Select Playlist</option>';
		this.ReloadPlaylistSelectBox($('playlistselectbox'));
		this.ReloadPlaylistSelectBox($('renameplaylistselectbox'));
		this.ReloadPlaylistSelectBox($('deleteplaylistselectbox'),true);
		
	},
	ReloadPlaylistSelectBox: function(ele,events){
		$$('.playlist a').each(function(el){
			if(events){
				el.removeEvents('event');
				el.addEvent('click',function(event){
					this.showPlaylist(el.parentNode.id.substring(8));
				}.bind(this));
			}
			var optn = document.createElement("OPTION");
			optn.text = el.innerHTML;
			optn.value = el.parentNode.id.substring(8);
			ele.options.add(optn);
		}.bind(this));
	},
	startFancyUpload: function(){
		//Fancy Upload script//
		if (Browser.Platform.linux)
			$('warningMsg').innerHTML = 'Warning: Due to a Bug in Adobe Flash Player Linux your browser will freeze while the song is uploading';	
		var swiffy = new FancyUpload2($('upload-status'), $('upload-list'), { // options object
			// we console.log infos, remove that in production!!
			verbose: true,
			url: $('form-upload').action,
			typeFilter: {
				'Music (*.mp3)': '*.mp3'
			},
			appendCookieData:true,
			target: 'upload-browse',
			path: 'swf/Swiff.Uploader.swf',
			onLoad: function() {
				$('upload-status').removeClass('hide'); // we show the actual UI
				$('upload-fallback').destroy(); // ... and hide the plain form
				// We relay the interactions with the overlayed flash to the link
				this.target.addEvents({
					click: function() {
						return false;
					},
					mouseenter: function() {
						this.addClass('hover');
					},
					mouseleave: function() {
						this.removeClass('hover');
						this.blur();
					},
					mousedown: function() {
						this.focus();
					}
				});
				// Interactions for the 2 other buttons
				$('upload-clear').addEvent('click', function() {
					swiffy.remove(); // remove all files
					return false;
				});
				$('start-upload').addEvent('click', function() {
					swiffy.start(); // start upload
					return false;
				});
			},
			onFileSuccess: function(file, response) {
					file.element.addClass('file-success');
					file.info.set('html', response);
					Library.loadLibrary();
			}
		});
	},
	dblclick: function(element){
		this.currentLibraryID = this.currentViewLibraryID;
		var song = Library.getSongInfo(element.className.replace(/[^0-9]*([^\s]*).*/,"$1"));
		oldid = this.songid;
		this.songid = song['ID'];
		Moxy.loadSong(song['md5']);
		Moxy_Controls.setSongInfo(song['song'],song['artist'],song['album']);
		this.changeColor(element);
		this.changeColor($(this.currentLibraryID).getElement('.id' + oldid),'normal');
		RemoveClass = '_Paused';
		AddClass = '_Playing';
		$(Moxy_Controls.options.ppbtn).removeClass(RemoveClass);
		$(Moxy_Controls.options.ppbtn).addClass(AddClass);
		this.checkDisabledButtons(song['ID']);
	},
	singleclick: function(){
		
	},
	showPlaylistMenu: function(ele){
		if(!$(this.options.playlistmenu).hasClass('hidepage'))
			$(this.options.playlistmenu).addClass('hidepage');
		else{
			$(this.options.playlistmenu).style.position = 'absolute';
			$(this.options.playlistmenu).style.left = parseInt(ele.getLeft()) + 10 + 'px';
			$(this.options.playlistmenu).style.top = parseInt(ele.getTop()) + 20 + 'px';
			$(this.options.playlistmenu).removeClass('hidepage');
		}
	},
	MenuAddNewPlaylist: function(){
		$(this.options.playlistmenu).addClass('hidepage');
		$('playlistAdder').removeClass('hidepage');
		$('playlistSelector').addClass('hidepage');
		$('playlistDeleter').addClass('hidepage');
		$('playlistRenamer').addClass('hidepage');
		$('add_newPlaylist').value='';
		$('newPlaylistName').value = '';
	},
	MenuRemovePlaylist: function(){
		$(this.options.playlistmenu).addClass('hidepage');
		$('playlistDeleter').removeClass('hidepage');
		$('playlistAdder').addClass('hidepage');
		$('playlistSelector').addClass('hidepage');
		$('playlistRenamer').addClass('hidepage');
		$('newPlaylistName').value = '';
		$('add_newPlaylist').value='';
	},
	MenuRenamePlaylist: function(){
		$(this.options.playlistmenu).addClass('hidepage');
		$('playlistRenamer').removeClass('hidepage');
		$('playlistDeleter').addClass('hidepage');
		$('playlistAdder').addClass('hidepage');
		$('playlistSelector').addClass('hidepage');
		$('newPlaylistName').value = '';
		$('add_newPlaylist').value='';
	},
	showMenu: function(ele,id){
		if(this.menuid == id && !$(this.options.menudiv).hasClass('hidepage')){
			$(this.options.menudiv).addClass('hidepage');
		}else{
			this.menuid = id;
			$(this.options.menudiv).removeClass('hidepage');
			eletop = parseInt(ele.getTop());
			if(this.height < (eletop + parseInt($(this.options.menudiv).getStyle('height')))){
				$(this.options.menudiv).style.top = eletop - parseInt($(this.options.menudiv).getStyle('height')) + 'px';
			}else $(this.options.menudiv).style.top = eletop + 20 + 'px';
			$(this.options.menudiv).style.left = ele.getLeft() + 'px';
		}
	},
	showUpload: function(){
		$('PageViewlist').addClass('hidepage');
		$('PagePlaylist').addClass('hidepage');
		$('PageUploadSongs').removeClass('hidepage');
	},
	MenuShowEditor: function(){
		var songInfo = this.getSongInfo(this.menuid,this.currentViewLibraryID);
		$('editSongSID').value = this.menuid;
		$('editSongTitle').value = songInfo['song'];
		if( songInfo['artist'] != undefined)
			$('editSongArtist').value = songInfo['artist'];
		else
			$('editSongArtist').value = '';
		if( songInfo['album'] != undefined)
			$('editSongAlbum').value = songInfo['album'].replace('&nbsp;','');
		else
			$('editSongAlbum').value = '';
		if( songInfo['genre'] != undefined)
			$('editSongGenre').value = songInfo['genre'];
		else
			$('editSongGenre').value = '';
		$('editSong').removeClass('hidepage');
		$(this.options.menudiv).addClass('hidepage');
	},
	MenuAddToPlaylist: function(){
		$(this.options.playlistSelector).removeClass('hidepage');
		$(this.options.menudiv).addClass('hidepage');
		$('playlistRenamer').addClass('hidepage');
		$('playlistDeleter').addClass('hidepage');
		$('playlistAdder').addClass('hidepage');
		$('newPlaylistName').value = '';
		$('add_newPlaylist').value='';
	},
	addToPlaylist: function(pid){
		updater = new Request.HTML().get('php/key.php?key='+ pid + '&set=AddPlaylist&data=' + $(this.currentViewLibraryID).getElement('.md5' + this.menuid).innerHTML);
	},
	RemoveFromPlaylist: function(pid){
		if(this.currentViewLibraryID == 'library')
			alert('Songs cannot be Removed from the Library');
		else
			updater = new Request.HTML({onComplete:function(){this.showPlaylist(this.currentViewLibraryID.substr(8));}.bind(this)}).get('php/key.php?key='+ this.currentViewLibraryID.substr(8) + '&set=RemoveFromPlaylist&data=' + $(this.currentViewLibraryID).getElement('.md5' + this.menuid).innerHTML);
		$(this.options.menudiv).addClass('hidepage');
		
	},
	checkDisabledButtons: function(songid){
		if(this.options.repeat == false){
			if(songid == this.getSiblingID(songid,'last')){
				Moxy_Controls.disableButton('forward',true);
			}else
				Moxy_Controls.disableButton('forward',false);
			if(songid == this.getSiblingID(songid,'first'))
				Moxy_Controls.disableButton('previous',true)
			else
				Moxy_Controls.disableButton('previous',false)
		}
	},
	getNext: function(){
		
		oldid = this.songid;
		
		song = (this.getSongInfo(this.getSiblingID(this.songid,'next')));
		this.songid = song['ID'];
		Moxy.loadSong(song['md5']);
		Moxy_Controls.setSongInfo(song['song'],song['artist'],song['album']);
		
		this.changeColor($(this.currentLibraryID).getElement('.id' + song['ID']));
		this.changeColor($(this.currentLibraryID).getElement('.id' + oldid),'normal');
		this.checkDisabledButtons(song['ID']);
	},
	getPrevious: function(){
		
		oldid = this.songid;
		
		song = (this.getSongInfo(this.getSiblingID(this.songid,'previous')));
		if(oldid == song['ID'] && this.options.repeat == true)
			song = (this.getSongInfo(this.getSiblingID(song['ID'],'last')));
			
		this.songid = song['ID'];
		Moxy.loadSong(song['md5']);
		Moxy_Controls.setSongInfo(song['song'],song['artist'],song['album']);
		
		this.changeColor($(this.currentLibraryID).getElement('.id' + song['ID']));
		this.changeColor($(this.currentLibraryID).getElement('.id' + oldid),'normal');
		this.checkDisabledButtons(song['ID']);
	},
	getSongInfo: function(songid,otherLib){
		var songsInfo = [];
		fromLib = this.currentLibraryID;
		if(otherLib)
			fromLib = otherLib;
		songsInfo['ID']  = songid;
		this.currentSongElement = $(fromLib).getElement('.id' + songid);
		if($(fromLib).getElement('.artist' + songid).innerHTML !=""){
			songsInfo['artist'] = $(fromLib).getElement('.artist' + songid).innerHTML;
		}
		if($(fromLib).getElement('.song' + songid).innerHTML !=""){
			songsInfo['song'] = $(fromLib).getElement('.song' + songid).innerHTML;
		}
		if($(fromLib).getElement('.album' + songid).innerHTML !=""){
			songsInfo['album'] = $(fromLib).getElement('.album' + songid).innerHTML.replace(/<div.*/ig,'');
		}
		if($(fromLib).getElement('.md5' + songid).innerHTML !=""){
			songsInfo['md5'] =  $(fromLib).getElement('.md5' + songid).innerHTML;
		}
		if($(fromLib).getElement('.songtime' + songid).innerHTML !=""){
			songsInfo['length'] = $(fromLib).getElement('.songtime' + songid).innerHTML;
		}
		if($(fromLib).getElement('.albumart' + songid) && $(fromLib).getElement('.albumart' + songid).innerHTML !=""){
			songsInfo['albumart'] = $(fromLib).getElement('.albumart' + songid).innerHTML;
		}else{
			songsInfo['albumart'] = 'images/noart.png';
		}
		//this.loadSongInfo(songsInfo);
		return songsInfo;
	},
	changeColor: function(ele,css){
		if(ele){
			ele = $(ele);
			if(!this.songid) 
				var pid = 'not set';
			else
				var pid =this.songid;
			if(ele.className.replace(/[^0-9]*([^\s]*).*/,"$1") != pid){
				if(css == 'hover'){
					ele.addClass(this.options.cssHover);
					ele.removeClass(this.options.cssNormal);
					ele.removeClass(this.options.cssSelected);
				}else if(css == 'normal'){
					ele.addClass(this.options.cssNormal);
					ele.removeClass(this.options.cssHover);
					ele.removeClass(this.options.cssSelected);
				}
			}else{ 
				ele.removeClass(this.options.cssHover);
				ele.removeClass(this.options.cssNormal);
				ele.addClass(this.options.cssSelected);
			}
		}
	},
	disableHighlight: function(element){
		if(Browser.Engine.trident){
			element.onselectstart=function(){return false};
		}else if(Browser.Engine.gecko){
			element.style.MozUserSelect="none";
		}else{
			element.unselectable = "on";
			element.onmousedown =function(){return false;}
		}
	},
	getSiblingID: function(startBrother,direction){
		var exit = false;
		var searchResults = false;
		if(document.getElementById(this.currentLibraryID).hasClass('_Searching'))
			searchResults = true;
		
		counter = 0;
		if(direction == 'first'){
			this.endBrother = document.getElementById(this.currentLibraryID).firstChild;//.firstChild.nextSibling.nextSibling.nextSibling.firstChild;//.nextSibling;
			while(exit == false){
				if(this.endBrother.nodeName != 'TBODY'){
					this.endBrother = this.endBrother.nextSibling;
					counter++;
				}
				else break;
			}
			
			this.endBrother= this.endBrother.firstChild;
			while(1==1){
				if(this.endBrother.nodeType == 1){
					if(searchResults == true){
						if(this.endBrother.hasClass('_SearchShow')){
							return this.endBrother.className.replace(/[^0-9]*([^\s]*).*/,"$1");
						}else
							this.endBrother = this.endBrother.nextSibling;
					}else{
						return this.endBrother.className.replace(/[^0-9]*([^\s]*).*/,"$1");
					}
				}else{
				this.endBrother = this.endBrother.nextSibling;	
				}
				counter++;
				if(counter > 3000){
					break;
				}
			}
		}else if(direction == 'last'){
			this.endBrother = document.getElementById(this.currentLibraryID).firstChild;//.firstChild.nextSibling.nextSibling.nextSibling.firstChild;//.nextSibling;
			while(exit == false){
				if(this.endBrother.nodeName != 'TBODY'){
					this.endBrother = this.endBrother.nextSibling;
					counter++;
				}
				else break;
			}
			
			this.endBrother= this.endBrother.lastChild;
			while(1==1){
				if(this.endBrother.nodeType == 1){
					if(searchResults == true){
						if(this.endBrother.hasClass('_SearchShow')){
							return this.endBrother.className.replace(/[^0-9]*([^\s]*).*/,"$1");
						}else
							this.endBrother = this.endBrother.previousSibling;
					}else{
						return this.endBrother.className.replace(/[^0-9]*([^\s]*).*/,"$1");
					}
					exit = true;
				}else{
					this.endBrother = this.endBrother.previousSibling;	
				}
				counter++;
				if(counter > 3000){
					break;
				}
			}
		}else if(direction == 'next'){
			if( this.currentSongElement.className.replace(/[^0-9]*([^\s]*).*/,"$1") ==startBrother)
				this.endBrother = this.currentSongElement.nextSibling;
			else
				this.endBrother = $(this.currentLibraryID).getElement('.id' + startBrother).nextSibling;
			while(1==1){
				if(this.endBrother.nodeType == 1){
					if(searchResults == true){
						if(this.endBrother.hasClass('_SearchShow')){
							return this.endBrother.className.replace(/[^0-9]*([^\s]*).*/,"$1");
						}else
							this.endBrother = this.endBrother.nextSibling;
					}else{
						return this.endBrother.className.replace(/[^0-9]*([^\s]*).*/,"$1");
					}
				}else{
				this.endBrother = this.endBrother.nextSibling;	
				}
				counter++;
				if(counter > 3000){
					break;
				}
			}
		}else if(direction == 'previous'){
			if( this.currentSongElement.className.replace(/[^0-9]*([^\s]*).*/,"$1") ==startBrother)
				this.endBrother = this.currentSongElement.previousSibling;
			else
				this.endBrother = $(this.currentLibraryID).getElement('.id' + startBrother).previousSibling;
			while(1==1){
				if(this.endBrother.nodeType == 1){
					if(searchResults == true){
						if(this.endBrother.hasClass('_SearchShow')){
							return this.endBrother.className.replace(/[^0-9]*([^\s]*).*/,"$1");
						}else
							this.endBrother = this.endBrother.previousSibling;
					}else{
						return this.endBrother.className.replace(/[^0-9]*([^\s]*).*/,"$1");
					}
					exit = true;
				}else{
					this.endBrother = this.endBrother.previousSibling;	
				}
				counter++;
				if(counter > 3000){
					break;
				}
			}
		}
		var lib = this.currentLibraryID;
		//if( $(this.currentLibraryID).hasClass('_Searching')){
			//this.Elements['search'] = $(this.currentLibraryID).getElements('.SearchShow');
		//	lib = 'search'
		//}else if(!this.Elements[this.currentLibraryID]) this.Elements[this.currentLibraryID] = $(this.currentLibraryID).getElements('.song');
		
		//lets find the next sibling down
		var SearchList = false;
		if(direction=='next'){
			if(SearchList == true){
				
			}else{
				//this.endBrother=$(lib).getElement('.id' + startBrother).getNext();
			}
			/*console.log(startBrother);
			for(var i = 0;i < this.Elements[lib].length;i++){
				//if(this.Elements[lib][i].className.replace(/[^0-9]*([^\s]*).* /,"$1") == startBrother){
					this.endBrother = this.Elements[lib][i+1];
					break;
				}
			}*/
			this.endBrother=$(lib).getElement('.id' + startBrother).nextSibling;
			while(this.endBrother.nodeType!=1){
				this.endBrother = this.endBrother.nextSibling;
				if(Playlist.options.repeat ==true && this.endBrother == null)
					this.endBrother = $(lib).getElement('.id' + startBrother).parentNode.firstChild;
				
			}/**/
		}else if(direction == "previous"){
				for(var i = 0;i < this.Elements[lib].length;i++){
				if(this.Elements[lib][i].className.replace(/[^0-9]*([^\s]*).*/,"$1") == startBrother){
					this.endBrother = this.Elements[lib][i-1];
					break;
				}
			}
		//if we are looking for the last sibling
		}else if(direction == "last"){
			/*this.endBrother = $(lib).getElement('.id' + startBrother).parentNode.lastChild;
			while(this.endBrother.nodeType!=1&& 
					((!this.endBrother.hasClass || (!this.endBrother.hasClass('_SearchShow') 
						&& $(lib).hasClass('_Searching'))) 
					|| !$(lib).hasClass('_Searching'))){
				this.endBrother = this.endBrother.previousSibling;
			}*/
			
			this.endBrother = this.Elements[lib][this.Elements[lib].length-1];
		}else if(direction == "first"){
			this.endBrother = this.Elements[lib][0];
			/*
			this.endBrother=$(lib).getElement('.id' + startBrother).previousSibling;
			/*
			 * keep going until it crashes on the first one
			 * though not elegant it works ATM
			 * *********** SHOULD UPDATE **************
			 *//*
			try{
				while(1==1){
					if(this.endBrother.nodeType==1)
						this.tempBrother = this.endBrother;
					this.endBrother = this.endBrother.previousSibling; 
					
				}
			}catch(e){
			*///	return (this.tempBrother.className.replace(/[^0-9]*([^\s]*).*/,"$1"));
			//}		
			//	*/
		//otherwise look for the first sibling
		}else{
			this.endBrother = this.Elements[lib][0];
			/*
			if(!$(lib).getElement('.id' + startBrother))
				startBrother--;
			this.endBrother=$(lib).getElement('.id' + startBrother).previousSibling;
			
			/* 
			 * If the first sibling IS the one entered 
			 * as startBrother this will automatically 
			 * die because there are no previous siblings 
			 * to find so lets return to them the fact 
			 * that this is the first sibling
			 *//*
			try{
				while(this.endBrother.nodeType!=1){
					this.endBrother = this.endBrother.previousSibling;
					
				}
			}catch(e){
				return startBrother;
			}
			
			//alert(this.endBrother.id.substr(2));
			*/
		}
		return this.endBrother.className.replace(/[^0-9]*([^\s]*).*/,"$1");
	},
	disableHighlight: function(element){ 
		if(Browser.Engine.trident){
			element.onselectstart=function(){return false};
		}else if(Browser.Engine.gecko){
			element.style.MozUserSelect="none";
		}else{
			element.unselectable = "on";
			
		}
	},
	showLibrary: function(visible){
		if(visible == true && this.currentViewLibraryID != 'library'){
			this.currentViewLibraryID = 'library';
			$('PagePlaylist').removeClass('hidepage');
			$('PageUploadSongs').addClass('hidepage');
			$('PageViewlist').addClass('hidepage');
		}else if(!visible){
			$('hiddenlibrary').appendChild($('library'));
			this.currentViewLibraryID = 'none';
		}else if(visible){
			$('PagePlaylist').removeClass('hidepage');
			$('PageViewlist').addClass('hidepage');
			$('PageUploadSongs').addClass('hidepage');
		}
		$(document.body).getElement('.swiff-uploader-box').style.left = '-999px';
	},
	showPlaylist: function(pid){
		$('playliPL' + pid).addClass('loadingplaylist');
		this.currentViewLibraryID = 'playlist' + pid;
		this.playlist = new Request.HTML({evalScripts:true,onComplete:function(r1,r2,r3,r4){
			$('PageViewlist').innerHTML = r3 ;
			new SortingTable( Library.currentViewLibraryID);
			$('playliPL' + pid).addClass('loadingplaylist');
			$('PagePlaylist').addClass('hidepage');
			$('PageViewlist').removeClass('hidepage');
			$('PageUploadSongs').addClass('hidepage');
			$(document.body).getElement('.swiff-uploader-box').style.left = '-999px';
		}}).get('php/playlist.php?pid=' + pid);
	},
	loadLibrary: function(){
		this.loadLib = new Request.HTML({evalScripts:true,onComplete:function(r1,r2,r3,r4){
			$('PagePlaylist').innerHTML = r3 ;
			new SortingTable( 'library');
		}}).get('php/playlist.php?pid=library');
	},
	search: function(val){
		if(this.searchArray)
		for(var i=0;i<this.searchArray.length;i++){
			$(this.currentViewLibraryID).getElement('.id' + this.searchArray[i]).removeClass('_SearchShow');
		}
		if(val == '')
			$(this.currentViewLibraryID).removeClass('_Searching');
		else{
			try{
			var regexSearch = new RegExp(val + "[^:]*:([^\|]*)","gi");
			this.searchArray = SearchString[this.currentViewLibraryID].match(regexSearch,"$1");
			for(var i=0;i<this.searchArray.length;i++){
				this.searchArray[i] =this.searchArray[i].replace(/[^:]*:/g,'');
				$(this.currentViewLibraryID).getElement('.id' + this.searchArray[i]).addClass('_SearchShow');
			}
			$(this.currentViewLibraryID).addClass('_Searching');
			}catch(e){};
		}
	},
	addNewPlaylist: function(PlaylistName){
		var newplaylist = new Request.HTML({evalScripts:true,onComplete:function(r1,r2,r3,r4){
			$('sidebar_content').innerHTML = r3;		
			Library.reloadSelectBoxes();
		}}).get('php/playlist.php?newplaylist=' + PlaylistName);
	},
	RenamePlaylist: function(pid,PlaylistName){
		var newplaylist = new Request.HTML({evalScripts:true,onComplete:function(r1,r2,r3,r4){
			$('sidebar_content').innerHTML = r3;		
			Library.reloadSelectBoxes();
		}}).get('php/playlist.php?renameplaylist=' + PlaylistName + '&plid=' + pid);
	},
	deletePlaylist: function(pid){
		var newplaylist = new Request.HTML({evalScripts:true,onComplete:function(r1,r2,r3,r4){
			$('sidebar_content').innerHTML = r3;	
			Library.reloadSelectBoxes();
		}}).get('php/playlist.php?deleteplaylist=' + pid);
	},
	editSong: function(){
		if(!$('editSong').hasClass('hidepage')){
			var editSong = new Request.HTML({evalScripts:true,onComplete:function(r1,r2,r3,r4){
				$('PagePlaylist').innerHTML = r3 ;
				new SortingTable( 'library');
			}}).get('php/editSong.php?title=' + $('editSongTitle').value + '&artist=' + $('editSongArtist').value + '&album=' + $('editSongAlbum').value + '&genre=' + $('editSongGenre').value + '&sid=' + $('editSongSID').value );
		}
		$('editSong').addClass('hidepage')
	},
	keyupdater: function(key,data){
		updater = new Request.HTML().get('php/key.php?key='+ key + '&set=XMLRequest&data=' + data);
	}	
});

MusicObj = {
	autostart: false,  //autostart
	streaming: true,   //streaming
	volume: 50,        //volume to start at
	pan: 0,            //pan between -100 (left) and 100 (right)
	progressInterval: 500, //milliseconds between getProgress(); calls
	positionInterval: 100,//milliseconds between getPosition(); calls
	onRegister: function(){if(!this.soundloaded)$('loadicon').addClass('_LoadSong');},//fires when the sound is registered
	onLoad: function(){$('loadicon').removeClass('_LoadSong');},    //fires when the sound is downloaded
	onPlay: $empty,    //fires when the sound begins playing
	onPause: $empty,   //fires when the sound is paused
	onStop: $empty,    //fires when the sound stops playing
	onComplete: function(){Library.getNext();}, //fires when the sound completes playing
	onProgress: $empty,//fires when download makes progress
	onPosition: function(position,duration) {
		try{
			if(Moxy_Controls.ProgressBar)
				Moxy_Controls.ProgressBar.set(position/10);
				if( Moxy_Controls.ProgressBar.steps +1000 > duration/10 ||Moxy_Controls.ProgressBar.steps -1000 < duration/10)
					 Moxy_Controls.ProgressBar.steps = duration/10;
		}catch(e){}
	        },//fires when position within the song changes
	onID3: $empty      //fires when ID3 tags become available
}

//Mootable Sort

//
// new SortingTable( 'my_table', {
//   zebra: true,                        // Stripe the table, also on initialize
//   details: false,                     // Has details every other row
//   paginator: false,                   // Pass a paginator object
//   dont_sort_class: 'nosort',          // Class name on th's that don't sort
//   forward_sort_class: 'forward_sort', // Class applied to forward sort th's
//   reverse_sort_class: 'reverse_sort'  // Class applied to reverse sort th's
// });
//
// The above were the defaults.  The regexes in load_conversions test a cell
// begin sorted for a match, then use that conversion for all elements on that
// column.
//
// Requires mootools Class, Array, Function, Element, Element.Selectors,
// Element.Event, and you should probably get Window.DomReady if you're smart.
//

var SortingTable = new Class({

  Implements: Options,
  
  options: {
    zebra: false,
    details: false,
    paginator: false,
    dont_sort_class: 'nosort',
    forward_sort_class: 'forward_sort',
    reverse_sort_class: 'reverse_sort'
  },

  initialize: function( table, options ) {
    this.table = $(table);
    this.setOptions(options);
    
    this.tbody = this.table.getElement('tbody');
    if (this.options.zebra) {
      SortingTable.stripe_table(this.tbody.getChildren());
    }

    this.headers = this.table.getElement('thead').getElements('th');
    this.headers.each(function( header, index ) {
      if (header.hasClass( this.options.dont_sort_class )) { return }
      header.store( 'column', index )
      header.addEvent( 'mousedown', function(evt){
        this.sort_by_header( evt.target );
        if ( this.options.paginator) this.options.paginator.to_page( 1 );
      }.bind( this ) );
    }, this);

    this.load_conversions();
  },

  sort_by_header: function( header ){
    var rows = [];
    
    var before = this.tbody.getPrevious();
    this.tbody.dispose();
    
    var trs = this.tbody.getChildren();
    while ( row = trs.shift() ) {
      row = { row: row.dispose() };
      if ( this.options.details ) {
        row.detail = trs.shift().dispose();
      }
      rows.unshift( row );
    }
    
    if ( this.sort_column >= 0 &&
         this.sort_column == header.retrieve('column') ) {
      // They were pulled off in reverse
      if ( header.hasClass( this.options.reverse_sort_class ) ) {
        header.removeClass( this.options.reverse_sort_class );
        header.addClass( this.options.forward_sort_class );
      } else {
        header.removeClass( this.options.forward_sort_class );
        header.addClass( this.options.reverse_sort_class );
      }
    } else {
      this.headers.each(function(h){
        h.removeClass( this.options.forward_sort_class );
        h.removeClass( this.options.reverse_sort_class );
      }, this);
      this.sort_column = header.retrieve('column');
      if (header.retrieve('conversion_function')) {
        this.conversion_matcher = header.retrieve('conversion_matcher');
        this.conversion_function = header.retrieve('conversion_function');
      } else {
        this.conversion_function = false;
        rows.some(function(row){
          var to_match = $(row.row.getElementsByTagName('td')[this.sort_column]).get('text');
          if (to_match == '') return false;
          this.conversions.some(function(conversion){
            if (conversion.matcher.test( to_match )){
              this.conversion_matcher = conversion.matcher;
              this.conversion_function = conversion.conversion_function;
              return true;
            }
            return false;
          }, this);
          return !!(this.conversion_function);
        }, this);
        header.store('conversion_function', this.conversion_function );
        header.store('conversion_matcher', this.conversion_matcher );
      }
      header.addClass( this.options.forward_sort_class );
      rows.each(function(row){
        var compare_value = this.conversion_function( row );
        row.toString = function(){
          return compare_value;
        };
      }, this);
      rows.sort();
    }

    var index = 0;
    while ( row = rows.shift() ) {
      this.tbody.appendChild(row.row);
      if (row.detail) this.tbody.appendChild(row.detail);
      if ( this.options.zebra ) {
        row.row.className = row.row.className.replace( this.removeAltClassRe, '$1').clean();
        if (row.detail)
          row.detail.className = row.detail.className.replace( this.removeAltClassRe, '$1').clean();
        if (index % 2) {
          row.row.addClass( 'alt' ); 
          if (row.detail) row.detail.addClass( 'alt' );
        }
      }
      index++;
    }
   this.tbody.inject(before, 'after');
   if(Library.songid)
	   Library.checkDisabledButtons(Library.songid);
  },

  load_conversions: function() {
    this.conversions = $A([
      // 1.75 MB, 301 GB, 34 KB, 8 TB
      { matcher: /([0-9.]{1,8}).*([KMGT]{1})B/,
        conversion_function: function( row ) {
          var cell = $(row.row.getElementsByTagName('td')[this.sort_column]).get('text');
          cell = this.conversion_matcher.exec( cell );
          if (!cell) { return '0' }
          if (cell[2] == 'M') {
            sort_val = '1';
          } else if (cell[2] == 'G') {
            sort_val = '2';
          } else if (cell[2] == 'T') {
            sort_val = '3';
          } else {
            sort_val = '0';
          }
          var i = cell[1].indexOf('.')
          if (i == -1) {
            post = '00'
          } else {
            var dec = cell[1].split('.');
            cell[1] = dec[0];
            post = dec[1].concat('00'.substr(0,2-dec[1].length));
          }
          return sort_val.concat('00000000'.substr(0,2-cell[1].length).concat(cell[1])).concat(post);
        }
      },
      // 1 day ago, 4 days ago, 38 years ago, 1 month ago
      { matcher: /(\d{1,2}) (.{3,6}) ago/,
        conversion_function: function( row ) {
          var cell = $(row.row.getElementsByTagName('td')[this.sort_column]).get('text');
          cell = this.conversion_matcher.exec( cell );
          if (!cell) { return '0' }
          var sort_val;
          if (cell[2].indexOf('month') != -1) {
            sort_val = '1';
          } else if (cell[2].indexOf('year') != -1) {
            sort_val = '2';
          } else {
            sort_val = '0';
          }
          return sort_val.concat('00'.substr(0,2-cell[1].length).concat(cell[1]));
        }
      },
      // Currency
      { matcher: /((\d{1}\.\d{2}|\d{2}\.\d{2}|\d{3}\.\d{2}|\d{4}\.\d{2}|\d{5}\.\d{2}|\d{6}\.\d{2}))/,
        conversion_function: function( row ) {
          var cell = $(row.row.getElementsByTagName('td')[this.sort_column]).get('text');
          cell = cell.replace(/[^\d]/g, "");
          return '00000000000000000000000000000000'.substr(0,32-cell.length).concat(cell);
        }
      },
      // YYYY-MM-DD, YYYY-m-d
      { matcher: /(\d{4})-(\d{1,2})-(\d{1,2})/,
        conversion_function: function( row ) {
          var cell = $(row.row.getElementsByTagName('td')[this.sort_column]).get('text');
          cell = this.conversion_matcher.exec( cell );
          return cell[1]+
                 '00'.substr(0,2-cell[2].length).concat(cell[2])+
                 '00'.substr(0,2-cell[3].length).concat(cell[3]);
        }
      },
      // Numbers
      { matcher: /^\d+$/,
        conversion_function: function( row ) {
          var cell = $(row.row.getElementsByTagName('td')[this.sort_column]).get('text');
          return '00000000000000000000000000000000'.substr(0,32-cell.length).concat(cell);
        }
      },
      // Fallback 
      { matcher: /.*/,
        conversion_function: function( row ) {
          return $(row.row.getElementsByTagName('td')[this.sort_column]).get('text');
        }
      }
    ]);
  }

});

SortingTable.removeAltClassRe = new RegExp('(^|\\s)alt(?:\\s|$)');
SortingTable.implement({ removeAltClassRe: SortingTable.removeAltClassRe });

SortingTable.stripe_table = function ( tr_elements  ) {
  var counter = 0;
  tr_elements.each( function( tr ) {
    if ( !tr.hasClass('collapsed') ) counter++;
    tr.className = tr.className.replace( this.removeAltClassRe, '$1').clean();
    if (counter % 2) tr.addClass( 'alt' );
  });
}

