window.activity = function(){}
window.addEvent( 'blur', function(){ window.activity = function(){ document.title=document.title.replace(/^(\[\!\] )?/,'[!] ') } });
window.addEvent( 'focus', function(){ window.activity = function(){}; document.title=document.title.replace(/^\[\!\] /,'') });

var mutedUsers = new Array();

var emoticons = [
	{ symbols: ['(+)', '(*)'], image: '/img/emoticons/yes.gif', desc: 'yes' },
	{ symbols: ['(-)', '(#)'], image: '/img/emoticons/no.png', desc: 'no' },
	{ symbols: [':|', ':-|', '=|', ':-/', ':/', '=/'], image: 'img/emoticons/neutral.png', desc: 'meh' },
	{ symbols: [':X', ':-X', '=X', ':-x', ':x', '=x'], image: 'img/emoticons/silence.png', desc: 'silence' },
	{ symbols: [':)', ':-)', '=)', ':]', ':-]', '=]'], image: 'img/emoticons/smile.png', desc: 'smile' },
	{ symbols: [':(', ':-(', '=(', ':[', ':-[', '=['], image: 'img/emoticons/sad.png', desc: 'sad' },
	{ symbols: [':D', '=D'], image: 'img/emoticons/laugh.png', desc: 'laugh' },
	{ symbols: ['>:(', '>:-(', '>:[', '>:-['], image: 'img/emoticons/angry.png', desc: 'angry' },
	{ symbols: [';)', ';-)', ';]', ';-]'], image: 'img/emoticons/wink.png', desc: 'wink' },
	{ symbols: [':p', ':-p', '=p', ':P', ':-P'], image: 'img/emoticons/tongue.png', desc: 'pffft' }
];
emoticons.get = function(s){ return this.filter( function(i){ return i.symbols.contains(s) })[0] }

$extend( String.prototype, {
	asEmotedHTML: function(shouldScroll){
		var run = shouldScroll? 'ChannelDisplay.chatToBottom()': '';
		var msg = new String(this.asHTML());
		var symbols = [];
		var pattern = '(https?:\/\/|ftp:\/\/|mailto:)[^\\s]+';
		emoticons.each( function(e){ symbols.merge(e.symbols) });
		symbols.sort().reverse().each( function(s){ pattern += '|' + s.asHTML().escapeRegExp() });
		return msg.replace( new RegExp(pattern,'g'), function( m ) {
			var e = emoticons.get(m.asPlain());
			if( e && e.image ) {
				return '<img src="' + e.image + '" alt="' + m + '" class="emoticon"/>';
			} else {
				if( false && m.test(/\.(jpg|jpeg|png|gif)(\?.*)?$/i) ) {
					return '<a href="' + m.asPlain() + '" target="_blank"><img src="' + m.asPlain() + '" class="inline" onload="' + run + '" onerror="' + run + '"></a>';
				} else {
					return '<a href="' + m.asPlain() + '" target="_blank">' + m + '</a>';
				}
			}
		});
	},

	asWrappableHTML: function(){
		// this inserts a zero width space character in long text blocks between html elements in the string
		var msg = ''+this;
		var parts = [];
		var rx = /([^<]+)?(<[^>]*>|&[^;]+;)?/;
		while( msg.length ) {
			var m = msg.match(rx);
			if( m[1] ) parts.push( m[1] );
			if( m[2] ) parts.push( m[2] );
			msg = msg.replace( rx, '' );
		}
		parts.each( function(p){
			if( p.substr(0,1) == '<' || p.substr(0,1) == '&' ) {
				msg += p;
			} else {
				msg += p.replace( /([^\s]{15})/g, '$1&#8203;' );
			}
		});
		return msg;
	},

	asWithoutHTML: function(){
		return this.replace( /<[^>]*>/g, '' );
	},

	asHashified: function(){
		var str = this.replace( /\s|\?|\-|\#/g, '_' );
		str = str.replace( /__+/g, '_' );
		return str;
	}
});

// ---------------------------------------------------------------------------------------------

var ContentDisplay = {
	clearContent: function(){
		ContentDisplay.template.hideTabs();
	},

	setContent: function(o){
		ContentDisplay.clearContent();
		ContentDisplay.current = o;
		var func;
		switch( o.type ) {
		case 'song':		func = ContentDisplay.showSong;	break;
		case 'feed':		func = ContentDisplay.showRSS;	break;
		case 'advertisement':	func = ContentDisplay.showAd;	break;
		case 'lobby':		func = ContentDisplay.showLobby; break;
		default:		func = ContentDisplay.showUser;	break;	// not ideal
		}
		// this is a hack to prevent overloading when booting and loading too many content blocks
		if( func ) {
			$clear(ContentDisplay.getcontent);
			ContentDisplay.getcontent = setTimeout( func.pass(o), 100 );
		}
	},

	_setTab: function(tab,o){
		var tab = ContentDisplay.template.tab(tab);
		tab.set(o);
		var element = tab.show(true).template;
		$ES('a', element).each(function(e){ e.setAttribute( 'target', '_blank' ) });	// make links open in new window
		tab.template.scrollTop = 0;
		return tab;
	},

	_getContent: function(url, params, o, success){
		if( o._content ) {
			if( ContentDisplay.current == o )
				success( o._content );
		} else {
			Ajax.get( url, params, function(r){
				o._content = r;
				if( ContentDisplay.current == o )
					success(r);
			});
		}
	},

	showSong: function(o){
		var tab = ContentDisplay._setTab('song', {
			artist: o.by.asPlain(),
			title: o.title.asPlain(),
			rank: o.rank? o.rank: 'n/a',
			itunes: o.id.asiTunesURL(ChannelDisplay.channel.channel.stream),
			amazon: o.by.asAmazonURL(),
			cover: o.cover
		});
		tab.panel('lyrics').show(false);
		tab.element('musicVideo').innerHTML = '';
		var url = "http://"+ChannelDisplay.channel.channel.name+".rew.fm/"+o.id+"/"+o.by+"/"+o.title;
		if(ChannelDisplay.channel.channel.type == 'radio')
		{
			tab.element('fbLike').innerHTML = '<iframe src="http://www.facebook.com/plugins/like.php?href='+escape(url)+'&amp;layout=standard&amp;colorscheme=light&amp;show_faces=true&amp;width=200&amp;font=lucida%2Bgrande" scrolling="no" frameborder="0" style="margin-top:3px;background-color:transparent;border:none; overflow:hidden; width:200px; height:50px" allowTransparency="true" bgcolor="white" onmouseover="ContentDisplay._getContent(\'/ajax/loglike.php\',{call:\''+ChannelDisplay.channel.channel.name+'\', mid:'+o.id+'}, function(){})"></iframe>';
		}else{
			tab.element('fbLike').innerHTML = '';
		}

		function show(r){
			tab.panel('lyrics').show(true).set({ lyrics: r.lyrics, edit: r.lyricsUrl });
			if( false && r.video && r.video.length > 0 ) {
//				swfobject.embedSWF( 'http://www.youtube.com/v/' + r.video[0].id, 'musicVideo', '250', '208', '8' );
				var swf = new SWFObject( 'http://www.youtube.com/v/' + r.video[0].id, 'youtube-vid', '250', '208', '8' );
				swf.addParam('wmode', 'transparent');
				if( !swf.write(tab.element('musicVideo')) ) {
					tab.element('musicVideo').innerHTML = 'Sorry, your browser cannot play videos.';
				}
			}
		}

		ContentDisplay._getContent( '/ajax/videoAndLyrics.php', {artist: o.by, song: o.title}, o, show );
		ContentDisplay.adsFor( o.by.asPlain() + ' ' + o.title.asPlain() );
	},

	showRSS: function(o){
		var tab = ContentDisplay._setTab('rss', {
			title: o.title.asHTML().asWrappableHTML(),
			sourceName: o.by,
			sourceURL: o.link,
			content: o.body
		});
		// hack to try to make display of certain images better by applying styles
		$ES( 'img', tab.template ).each(function(e){
			if( e.align == 'left' ) e.addClass('fl');
			if( e.align == 'right' ) e.addClass('fr');
		});
		ContentDisplay.adsFor( o.title.asPlain() );
	},

	showLobby: function(o){
		var tab = ContentDisplay._setTab('lobby', o);
		//ContentDisplay.adsFor( 'yes.com lobby' );
		ContentDisplay.adsFor( 'music' );
	},

	showAd: function(o){
		var tab = ContentDisplay._setTab('ad', {title: o.by.asPlain() });
		tab.element('adVideo').innerHTML = '';

		function show(r){
			if( r.id ) {
				var swf = new SWFObject( 'http://www.youtube.com/v/' + r.id, 'youtube-vid', '250', '208', 8 );
				swf.addParam('wmode', 'transparent');
				if( !swf.write(tab.element('adVideo')) ) {
					tab.element('adVideo').innerHTML = 'Sorry, your browser cannot play videos.';
				}
			}
		}
		ContentDisplay._getContent( '/ajax/advideo.php', {s: o.by.asPlain()}, o, show );

		ContentDisplay.adsFor( o.by.asPlain() );
	},

	showUser: function(o){
		var tab = ContentDisplay._setTab('user', {user: o, avatar: o.asAvatarURL()});
		tab.removeAllChildren();
		tab.hidePanels();
		function show(r){
			if( r.fullname ) tab.panel('name').show(true).set({ name: r.fullname });
			if( r.location ) tab.panel('location').show(true).set({ location: r.location });
			if( r.website ) tab.panel('website').show(true).set({ website: r.website });
			if( r.email ) tab.panel('email').show(true).set({ email: r.email });
			if( parseInt(r.byear) > 0 ) {
				var bdate = new Date();
				bdate.setMonth( r.bmon );
				bdate.setFullYear( r.byear );
				bdate.setDate( r.bday );
				var age = parseInt(((new Date()).getTime() - bdate.getTime()) / (1000 * 60 * 60 * 24 * 365));
				tab.panel('age').show(true).set({ age: age + ' years old' });
			}

			r.votes.each(function(v){
				var vote = v.voteType == 'Y'? '(+)': '(-)';	// hehe.. silly hack
				var e = tab.appendChild( 'songVote', {itunes: parseInt(v.id).asiTunesURL(ChannelDisplay.channel.channel.stream), amazon: v.by.asAmazonURL(), cover: v.cover, title: v.title.asPlain(), artist: v.by.asPlain(), time: v.voteTime, date: v.voteDate.asDate(), vote: vote.asEmotedHTML(), station: v.voteStation.asPlain(), gotoStation: joinFirstSearchResult.pass(v.voteStation)});
			});
		}
		ContentDisplay._getContent( '/ajax/userChannel.php', {u: o}, o, show );
	},

	adsFor: function(f){
		//console.log('adsfor: ' + _focus);
		if (_focus) {
			$('ad').name = 'google-' + Math.random();
			$('ad').src = '/get-ads.php?z=' + Math.random();
                	$('ad-new').name = 'google-' + Math.random();
                	$('ad-new').src = '/get-ads-g.php?for=' + encodeURIComponent(f) + '&z=' + Math.random();
                	//$('ad-banner').name = 'google-' + Math.random();
                	//$('ad-banner').src = '/get-banner.php?for=' + encodeURIComponent(f) + '&z=' + Math.random(); 
		}
	}
}


var ChannelDisplay = {
	_resetTabs: function(){
		$(document.body).removeClass('chat');
		$(document.body).removeClass('chart');
		$(document.body).removeClass('log');
	},

	showChat: function(){
		ChannelDisplay._resetTabs();
		$(document.body).addClass('chat');
		ChannelDisplay.chatToBottom(true);
		ChannelDisplay.input.focus();
		setURLParams( null );
	},

	showChart: function(){
		ChannelDisplay._resetTabs();
		$(document.body).addClass('chart');
		ChannelDisplay._topSongsSource( ChannelDisplay._setTopSongs );
		setURLParams( 'chart' );
	},

	showLog: function(){
		ChannelDisplay._resetTabs();
		$(document.body).addClass('log');
		ChannelDisplay.setSongLogView( 0, new Date().getHours() );
		setURLParams( 'log' );
	},

	hideTabs: function(){
		// always leave the chat tab visible
		$$('.chart-tab', '.log-tab').setStyle('display','none');
	},

	hideStreamingLink: function(){
		$('stream').setStyle('display', 'none');
	},

	setStreamingLink: function(link){
		$('stream').setStyle('display', '');
		$TT('stream').set({ url: link });
	},

	showTabs: function(){
		$$('.chat-tab', '.chart-tab', '.log-tab').setStyle('display','');
	},

	connectSwitcher: function(teeny){
		teeny.set({ chat: ChannelDisplay.showChat, chart: ChannelDisplay.showChart, log: ChannelDisplay.showLog });
	},

	connectInputBox: function(textarea){
		ChannelDisplay.input = $(textarea);

		// stupid hacks... even the iPhone is not immune...
		if( navigator.userAgent.contains('iPhone') ){
			setInterval( function(){
				var input = ChannelDisplay.input.value;
				if( input.contains('\n') ) {
					ChannelDisplay.sendMessage( input.replace(/\n|\r/g, '') );
					ChannelDisplay.input.value = '';
					ChannelDisplay.input.focus();
					document.execCommand("selectAll"); 
					document.execCommand("delete"); 
				}
			}, 100);
		} else {
			ChannelDisplay.input.addEvent( 'keypress', function(e){
				e = new Event(e);
				if( e.key == 'enter' ){
					ChannelDisplay.sendMessage( ChannelDisplay.input.value.replace(/\n|\r/g, '') );
					e.preventDefault();
					ChannelDisplay.input.value = '';
					ChannelDisplay.input.focus();
				}
			});
		}
	},

	sendMessage: function(msg){
		if( ChannelDisplay.channel && msg ) {
			if( Cookie.get('username') ) {
				ChannelDisplay.channel._say( msg );
				var vote = null;
				if( msg.match(/\((\+|\*)\)/) ) vote = 1;
				else if( msg.match(/\((\-|\#)\)/) ) vote = 0;
				if( vote != null && ChannelDisplay.voteInformation ) {
					Ajax.get( '/ajax/vote.php', {song: ChannelDisplay.voteInformation.songID, station: ChannelDisplay.voteInformation.stationName, vote: vote} );
				}
			} else {
				showLogin();
			}
		}
	},

	setChannel: function(c){
		if( ChannelDisplay.channel == c ) return;
		if( ChannelDisplay.channel ) ChannelDisplay.channel._disconnect(c);
		ContentDisplay.clearContent();
		ChannelDisplay.channel = c;
		ChannelDisplay.transcript.removeAllChildren();
		ChannelDisplay.hideTabs();
		ChannelDisplay.hideStreamingLink();
		ChannelDisplay._songLogSource = ChannelDisplay._topSongsSource = null;
		c._connect();

		var params = parseURLLocation().params;
		if( ChannelDisplay._songLogSource && params.contains('log') ) {
			ChannelDisplay.showLog();
		} else if( ChannelDisplay._topSongsSource && params.contains('chart') ) {
			ChannelDisplay.showChart();
		} else {
			ChannelDisplay.showChat();
		}

		setURLChannel( c.channel.name );
		if( c.channel.stream == 'yes' )
			ContentDisplay.setContent({ type: 'lobby' });
	},

	leaveChannel: function(){
		if( ChannelDisplay.channel )
			ChannelDisplay.channel._leave();
	},

	deselectItems: function(){
		$ES( '.this', 'chat' ).removeClass('this');
	},

	// the animation messes with this... need to think about it
	chatAtBottom: function(){
		if( ChannelDisplay.scrollingToBottom ) return true;
		var e = $('chat');
		var bounds = e.getSize();
		return (bounds.scroll.y + bounds.size.y >= bounds.scrollSize.y);
	},

	chatToBottom: function(){
		if( !$(document.body).hasClass('chat') ) return;
		if( ChannelDisplay.scroller ) ChannelDisplay.scroller.stop();
		ChannelDisplay.scroller = (new Fx.Scroll('chat',{duration:200})).toBottom();
		if( ChannelDisplay.scrollingToBottom ) $clear(ChannelDisplay.scrollingToBottom);
		ChannelDisplay.scrollingToBottom = setTimeout( function(){ ChannelDisplay.scrollingToBottom = null }, 201 );
	},

	newItem: function(c, o){
		if( c != ChannelDisplay.channel || !o.type ) return;
		var scroll = ChannelDisplay.chatAtBottom();

		switch( o.type ) {
		case 'chat':		ChannelDisplay.newMessage(o,scroll);	break;
		case 'song':		ChannelDisplay.newSong(o);		break;
		case 'advertisement':	ChannelDisplay.newAd(o);		break;
		case 'feed':		ChannelDisplay.newRSSItem(o);		break;
		case 'leave':		ChannelDisplay.newLeave(o);		break;
		case 'join':		ChannelDisplay.newJoin(o);		break;
		}

		if( scroll ) ChannelDisplay.chatToBottom();
	},

	add: function(c,t,o,s,autocontent){
		var e = ChannelDisplay.transcript.appendChild(t+c);
		var content = function(){ 
			ChannelDisplay.deselectItems();
			$(e.template).addClass('this');
			ContentDisplay.setContent(o);
			return true;
		};
		s.show = content;
		if( autocontent ) content();

		// manage memory/performance by removing entries if we have too many
		while( e.template.parentNode.childNodes.length > 200 )
			$(e.template.parentNode.firstChild).remove();

		return e.set(s);
	},

	newMessage: function(o,scroll){
		if( !mutedUsers.contains(o.from) )
			ChannelDisplay.add('Message', 'chat', o.from, {msg: o.txt.asEmotedHTML(scroll).asWrappableHTML(), user: o.from, avatar: o.from.asAvatarURL()}, false );
	},

	newSong: function(o){
		ChannelDisplay.voteInformation = { songID: o.id, stationName: o.station? o.station: ChannelDisplay.channel.channel.name };
		var e = ChannelDisplay.add('Song', 'chat', o, { artist:o.by.asPlain(), title:o.title.asPlain(), cover: o.cover, time: o.time.asTime(), date: o.date.asDate(), itunes: o.id.asiTunesURL(ChannelDisplay.channel.channel.stream), amazon: o.by.asAmazonURL() }, true);
		if( o.station ) {
			e.panel('station').show(true).set({station: o.station.asPlain(), gotoStation: joinFirstSearchResult.pass(o.station) });
		} else {
			e.panel('station').show(false);
		}
	},

	newAd: function(o){
		ChannelDisplay.voteInformation = null;
		ChannelDisplay.add('Ad', 'chat', o, { title:o.by.asPlain(), time: o.time.asTime(), date: o.date.asDate() }, true);
	},

	newRSSItem: function(o){
		ChannelDisplay.voteInformation = null;
		if( !o.body ) return;
		var at = new Date();
		at.setTime( o.at );
		ChannelDisplay.add('RSS', 'chat', o,{ title: o.title.asHTML().asWrappableHTML(), icon: o.icon, date: at.getDateString(), time: at.getTimeString() }, true);
	},

	newJoin: function(o){
		//ChannelDisplay.add('Join', 'chat', o.from, {user: o.from}, false );
	},

	newLeave: function(o){
		if( o.id && o.name && o.relay ) {
			var entry = ChannelDisplay.add('Switch', 'chat', o.from, {user: o.from, channel: o.name}, false );
			entry.set({ follow: function(){
				joinFirstSearchResult( o.name );
			}});
		} else {
			//ChannelDisplay.add('Gone', 'chat', o.from, {user: o.from}, false );
		}
	},

	setTopSongsSource: function(src){
		ChannelDisplay._topSongsSource = src;
		ChannelDisplay.showTabs();
	},

	_setTopSongs: function(c,r){
		if( c != ChannelDisplay.channel ) return;
		var first = true;
		r.songs.each(function(o){
			ChannelDisplay.add('Song','chart',o, { rank: o.rank, artist:o.by.asHTML().asWrappableHTML(), title:o.title.asWrappableHTML(), cover: o.cover, itunes: o.id.asiTunesURL(ChannelDisplay.channel.channel.stream), amazon: o.by.asAmazonURL() }, first);
			first = false;
		});
	},

	setSongLogSource: function(src){
		ChannelDisplay._songLogSource = src;
		ChannelDisplay.showTabs();
	},

	setSongLogView: function(day,hour){
		$$('.log-display').each( function(e){
			e.getChildren().each( function(i){ i.remove() } )
		});

		// set the chooser display with the settings
		var chooser = ChannelDisplay.transcript.appendChild( 'logChooser' );
		chooser.removeAllChildren();
		var date = new Date();
		for( var d=0; d<7; d++ ) {
			chooser.appendChild( 'day',{ day: date.getDayOfTheWeek() + ', ' + date.getMonthName() + ' ' + date.getDate() });
			date.setYesterday();
		}
		for( var h=0; h<24; h++ ) chooser.appendChild( 'hour',{ hour: (h+':00').asTime() });
		chooser.set({update: function(){
			ChannelDisplay.setSongLogView($('log-day').selectedIndex, $('log-hour').selectedIndex);
		}});

                // Message Mod
//                if (day == 0) {
//			$$('.submit_is_update')[0].innerHTML += '<p>Buy 4 Songs today to win a song, iPhone or $100,000. Check prior days to see winning songs.<small>No purchase necessary.  <a href="/YESwidget.php" class="buy" target="_blank" >Click for details.</a></small></p>';
//                } else {
//                        $$('.submit_is_update')[0].innerHTML += '<p>If you bought 2, 3 or all 4Tunes you won a song, iPhone or $100,000. Buy 4 Songs today to win.<small>No Purchase necessary. <a href="/YESwidget.php" class="buy" target="_blank">Click for Details.</a></small></p>';
//                }
		  var station = ChannelDisplay.channel.channel.name;
                  $$('.submit_is_update')[0].innerHTML += '<p>Check out '+station+' on Rewind at <a href="http://'+station+'.rew.fm/log/" class="buy" target="_blank">'+station+'.REW.FM</a></small></p>';

	        if (ChannelDisplay.channel.channel.name.length < 5) {
			//$$('.submit_is_update')[0].innerHTML += '<p>Stay up to date with the latest logs and charts via...  <img class="" width="16" height="16" alt="image" src="/img/feed.png"/> <a href="http://yes.com/' + ChannelDisplay.channel.channel.name + '/log/rss">Log</a> OR <img class="" width="16" height="16" alt="image" src="/img/feed.png"/> <a href="http://yes.com/' + ChannelDisplay.channel.channel.name + '/chart/rss">Chart</a>'; 
        	}

                $('log-day').selectedIndex = day;
                $('log-hour').selectedIndex = hour;

		// get the data
		ChannelDisplay._songLogSource( ChannelDisplay._setSongLog, day, hour );
	},

	_setSongLog: function(c,r){
		if( c != ChannelDisplay.channel ) return;
		if( !r.songs || !r.songs.length ) {
			ChannelDisplay.transcript.appendChild( 'logNone' );
		} else r.songs.each(function(o){
			ChannelDisplay.add('Song','log',o, { rank: o.rank, artist:o.by.asHTML().asWrappableHTML(), title:o.title.asWrappableHTML(), cover: o.cover, time: o.time.asTime(), date: o.date.asDate(), itunes: o.id.asiTunesURL(ChannelDisplay.channel.channel.stream), amazon: o.by.asAmazonURL() }, false);
		});
	}
}

var SmartChannel = new Class({
	initialize: function(c) {
		this.channel = c;
		this.group = null;
		c.name = c.name.asPlain();
		var title = c.name;
		if( c.desc ) title += ' - ' + c.desc.asPlain();
		this.titleHTML = $TT( SmartChannel.titleTemplate.clone(true), {name: title, icon: c.icon, active: this.setActive.bind(this) });
		this.rosterHTML = $TT( SmartChannel.rosterTemplate.clone(true) ).show( false );
		this.titleHTML.panel('bookmark').set({ bookmark: this.toggleBookmark.bind(this) });

		c.addEvent( 'roster-count', this.onRosterCount.bind(this) );
		c.addEvent( 'roster-refresh', this.onRosterRefresh.bind(this) );
		c.addEvent( 'booted', this.onBooted.bind(this) );
		c.addEvent( 'user-message', ChannelDisplay.newItem.arg1(this) );
		c.addEvent( 'user-leave', ChannelDisplay.newItem.arg1(this) );
		c.addEvent( 'user-join', ChannelDisplay.newItem.arg1(this) );
	},

	setGroup: function(g){
		if( ChannelGroup.get(g) == this.group ) return this;
		if( this.group ) this.group.removeChannel(this);
		if( g ) {
			if( g == 'My Bookmarked Channels' ) {
				$(this.titleHTML.panel('bookmark').template).removeClass('add');
				$(this.titleHTML.panel('bookmark').template).addClass('remove');
			} else {
				$(this.titleHTML.panel('bookmark').template).addClass('add');
				$(this.titleHTML.panel('bookmark').template).removeClass('remove');
			}
			ChannelGroup.get(g).addChannel( this );
			this.channel.startRosterCount();
		}
		return this;
	},

	setActive: function(){
		ChannelDisplay.setChannel(this);
	},

	toggleBookmark: function(){
		var todo;
		if( this.group.name == 'My Bookmarked Channels' ) {
			todo = 'rem';
			this.setGroup( 'Recently Visited Channels' );
		} else {
			todo = 'add';
		}
		Ajax.get( '/ajax/' + todo + 'Bookmark.php', {f: this.channel.stream, t: this.channel.type}, refreshBookmarkedChannels );
	},

	_connect: function(){
		this.rosterHTML.removeAllChildren();
		$(this.titleHTML.template).addClass('this');
		this.titleHTML.panel('bookmark').show(true);
		this.channel.connect();
	},

	_disconnect: function(to){
		$(this.titleHTML.template).removeClass('this');
		this.titleHTML.panel('bookmark').show(false);
		this.rosterHTML.show(false);
		this.channel.disconnect(to? to.channel: null);
	},

	_leave: function(){
		this.channel.leave();
	},

	_say: function(msg){
		this.channel.send(msg);
	},

	onRosterCount: function(c){
		if( c )
			this.titleHTML.panel('count').show(true).set({ online: c });
		else
			this.titleHTML.panel('count').show(false);
	},

	onRosterRefresh: function(r){
		this.rosterHTML.removeAllChildren();
		var me;
		r.sort().each(function(u){
			var e = this.rosterHTML.appendChild( 'user', {user: u, avatar: u.asAvatarURL()} );
			if( u == Cookie.get('username') ) {
				me = $(e.template);
			} else {
				e.tab('silenceOff').set({ select: function(){ 
					mutedUsers.include(u);
					e.focusTab('silenceOn'); 
					Ajax.get( '/ajax/mute.php', {user: u, from: Cookie.get('username')} );
				 }});
				e.tab('silenceOn').set({ select: function(){ mutedUsers.remove(u); e.focusTab('silenceOff') }});
				e.focusTab( mutedUsers.contains(u)? 'silenceOn': 'silenceOff' );
			}
		}, this);
		if(me) {
			me.injectTop(me.parentNode);
			me.addClass('me');
		}
	},

	onBooted: function(){
		this.rosterHTML.show(true);
	}
});

var RadioChannel = SmartChannel.extend({
	initialize: function(c){
		//c.icon = '/img/radio.png';
		this.parent(c);
		this.channel.addEvent( 'song-item', ChannelDisplay.newItem.arg1(this) );
		this.channel.addEvent( 'ad-item', ChannelDisplay.newItem.arg1(this) );
	},
	_connect: function(){
		this.parent();
		ChannelDisplay.setTopSongsSource( this._topSongs.bind(this) );
		ChannelDisplay.setSongLogSource( this._songLog.bind(this) );
		if( this.channel.audiostream )
			ChannelDisplay.setStreamingLink( this.channel.audiostream );
	},
	_topSongs: function(callback){
		Ajax.get( '/ajax/chart.php', {s: this.channel.stream}, callback.arg1(this) );
	},
	_songLog: function(callback,day,hour){
		Ajax.get( '/ajax/log.php', {s: this.channel.stream, h:hour, d:day}, callback.arg1(this) );
	}
});

var RSSChannel = SmartChannel.extend({
	initialize: function(c){
		this.parent(c);
		this.channel.addEvent( 'feed-item', ChannelDisplay.newItem.arg1(this) );
	}
});

var ArtistChannel = SmartChannel.extend({
	initialize: function(c){
		//c.icon = '/img/radio.png';
		this.parent(c);
		this.channel.addEvent( 'song-item', ChannelDisplay.newItem.arg1(this) );
	}
});

SmartChannel.knownChannels = [];
SmartChannel.get = function(c) {
	var n;
	if( !SmartChannel.knownChannels.some(function(i){ return (c.stream == i.channel.stream)? (n=i,true): false }) ) {
		switch( c.type ) {
		case 'radio':	n=new RadioChannel(c);	break;
		case 'artist':	n=new ArtistChannel(c);	break;
		default: 	n=new RSSChannel(c);
		}
		SmartChannel.knownChannels.include( n );
	}
	return n;
}

var ChannelGroup = new Class({
	initialize: function(name) {
		this.name = name;
		this.heading = ChannelGroup.template.appendChild( 'groupHeading', {title: name, toggle: this.toggle.bind(this)} );
		this.list = ChannelGroup.template.appendChild( 'groupChannels' );
		this.open();
		this.hide();
		this.updateDisplay();
	},

	show: function() {
		this.heading.show(true);
		this.list.show(true);
	},

	hide: function() {
		this.heading.show(false);
		this.list.show(false);
	},

	open: function() {
		$(this.heading.element('title')).addClass('open');
		this.list.show(true);
	},

	close: function() {
		$(this.heading.element('title')).removeClass('open');
		this.list.show(false);
	},

	toggle: function() {
		if( $(this.heading.element('title')).hasClass('open') )
			this.close();
		else
			this.open();
	},

	updateDisplay: function() {
		var group = this;
		if( SmartChannel.knownChannels.some(function(i){ return i.group == group }) ) {
			this.show();
		} else {
			this.hide();
		}
	},

	addChannel: function(c) {
		c.group = this;
		$(c.titleHTML.template).injectInside( this.list.template );
		$(c.rosterHTML.template).injectAfter( c.titleHTML.template );
		this.updateDisplay();
	},

	removeChannel: function(c) {
		c.group = null;
		$(c.titleHTML.template).remove();
		$(c.rosterHTML.template).remove();
		this.updateDisplay();
	}

});
ChannelGroup.groups = {}
ChannelGroup.get = function(name){
	if( !ChannelGroup.groups[name] )
		ChannelGroup.groups[name] = new ChannelGroup(name);
	return ChannelGroup.groups[name];
}

var SearchManager = {
	connectSearchForm: function(){
		function find(e){
			new Event(e).stop();
			SearchManager.search($('searchfield').value);
			SearchManager.resetButton.injectInside('search');
		}
		function done(e){
			new Event(e).stop();
			SearchManager.clear();
			$('searchfield').value = '';
		}
		$('reset').addEvent('click', SearchManager.clear);
		$('search').addEvent('submit', find);
		$('searchfield').addEvent('click',done);
		SearchManager.clear();
	},
	clear: function(){
		if( !SearchManager.resetButton ) SearchManager.resetButton = $('reset');
		if( SearchManager.resetButton.parentNode ) SearchManager.resetButton.remove();
		$(document.body).removeClass( 'showing-search-results' );
		$('searchfield').value = 'Search For Channels';
	},
	search: function(str){
		Ajax.get( '/ajax/search.php', {q: str}, SearchManager._setSearchResults );
	},
	_setSearchResults: function(r){
		SearchManager.resultHTML.removeAllChildren();
		if( r.r.length > 0 ) {
			r.r.each(function(c){
				var title = c.name.asPlain();
				if( c.desc ) title += ' - ' + c.desc.asPlain();
				SearchManager.resultHTML.appendChild('searchResult', {name: title, icon: c.icon, active: SearchManager._click.pass(c) });
			});
		} else {
			SearchManager.resultHTML.appendChild('searchNothing');
		}
		$(document.body).addClass( 'showing-search-results' );
	},
	_click: function(c){
		var n = SmartChannel.get(new Channel(c)).setGroup('Recently Visited Channels')
		ChannelDisplay.setChannel( n );
		SearchManager.clear();
	}
}

// loader helper function - just because
function loader( g, c ) {
	c = SmartChannel.get(c);
	if( !c.group
	 || g == 'My Bookmarked Channels'
	 || (g == 'Popular Channels' && c.group.name != 'My Bookmarked Channels')
	) c.setGroup(g);
	return c;
}

function refreshPopularChannels(){
	loadChannelList( '/ajax/channel-new.php', loader.compose(this,'Popular Channels') );
}

function refreshBookmarkedChannels(){
	loadChannelList( '/ajax/getBookmarks.php', loader.compose(this,'My Bookmarked Channels') );
}

var loginBox, registerBox, profileBox;
function showLogin(){
	registerBox.close();
	loginBox.open();
	setTimeout( function(){ loginBox.template.username.focus() }, 200 );
}
function showRegister(){
	loginBox.close();
	registerBox.open();
	setTimeout( function(){ registerBox.template.username.focus() }, 200 );
}
function showProfileEditor(){
	profileBox.open();
	$('profile-box').src = '/user/embedEditPrefs.php';
}

function parseURLLocation(){
	var h = document.location.hash.substr(1);
	var parts = h.split( /\?/, 2 );
	return { channel: parts[0], params: parts[1]? parts[1]: '' };
}

function setURLLocation( o ){
	document.location.hash = '#' + o.channel.asHashified() + ((o.params)? ('?'+o.params): '');
	document.title = o.channel + ' @ yes.com';

}

function setURLChannel(channel){
	var o = parseURLLocation();
	o.channel = channel;
	setURLLocation( o );
}

function setURLParams(params){
	var o = parseURLLocation();
	o.params = params;
	setURLLocation( o );
}

function joinRecentChannel(o){
	var c = loader( 'Recently Visited Channels', new Channel(o) );
	ChannelDisplay.setChannel(c);
}

function joinFirstSearchResult( name, fail ) {
	function got(r) { if( r && r.r && r.r.length ) { joinRecentChannel(r.r[0]); } else { if( fail ) fail() } }
	Ajax.get( '/ajax/search.php', {q: unescape(name)}, got, fail );
}

window.addEvent( 'domready', function(){
	SmartChannel.titleTemplate = $('template-channelTitle').remove();
	SmartChannel.rosterTemplate = $('template-channelRoster').remove();
	SearchManager.resultHTML = $TT('search-results');
	SearchManager.connectSearchForm();
	ChannelGroup.template = $TT('channels');
	ChannelDisplay.transcript = $TT('chat');
	ChannelDisplay.connectSwitcher($TT('tabs'));
	ChannelDisplay.connectInputBox($('message').input);
	ContentDisplay.template = $TT('info');
	var accountMenu = $TT('user');
	$(document.body).setStyle('visibility', 'visible');
	window.addEvent( 'resize', ChannelDisplay.chatToBottom );

	function lobby() {
		joinRecentChannel({ relay:'r2a',stream:'yes',name:'YES Lobby',type:'rss' });
	}

	var goHere = parseURLLocation().channel;
	if( goHere ) {
		joinFirstSearchResult( goHere, lobby );
	} else {
		lobby();
	}

	// load popular channels and bookmarks
	refreshPopularChannels();
	// refreshBookmarkedChannels(); // handled below in the user login monitor

	loginBox = TeenyOverlay( 'login', {register: showRegister, login: function(e,t){
		new Event(e).stop();
		function bad(){
			alert( 'Incorrect username or password.  Please try again.' );
		}
		function good(o){
			if( o )
				loginBox.close();
			else
				bad();
		}
		Ajax.post( '/ajax/login.php', {lu: t.template.username.value, lp: t.template.password.value}, good, bad );
	}});
	registerBox = TeenyOverlay( 'register', {login: showLogin, register:function(e,t){
		new Event(e).stop();
		function bad(){
			alert( 'Please try again.' );
		}
		function good(o){
			if( o.status ) {
				registerBox.close();
			} else {
				alert( o.message );
			}
		}
		Ajax.post( '/ajax/register.php', {username: t.template.username.value, password: t.template.password.value, password2: t.template.password2.value, email: t.template.email.value}, good, bad );
//		Ajax.post( '/ajax/register.php', {username: t.template.username.value, password: t.template.password.value, password2: t.template.password2.value, email: t.template.email.value, "recaptcha_challenge_field":t.template["recaptcha_challenge_field"].value, "recaptcha_response_field":t.template["recaptcha_response_field"].value}, good, bad );
	}});
	profileBox = TeenyOverlay( 'profile' );

	accountMenu.set({ help: function(){ $('helpOverlay').setStyle('display', 'block'); } });
	$('helpOverlay').addEvent( 'click', function(){ $('helpOverlay').setStyle('display', 'none') });

	// user login/out monitor
	var olduser;
	setInterval( function(){
		var user = Cookie.get('username');
		if( user != olduser ) {
			olduser = user;
			if( !user ) {
				accountMenu.focusTab('loggedOut').set({ login: showLogin, register: showRegister });
				ChannelGroup.get("Bookmarks").hide();
			} else {
				function logout(){
					ChannelDisplay.leaveChannel();
					Ajax.get('/ajax/logout.php');
				}
				accountMenu.focusTab('loggedIn').set({ logout: logout, edit: showProfileEditor });
				refreshBookmarkedChannels();
				ChannelGroup.get("Bookmarks").updateDisplay();
			}
		}
	}, 500 );

	$ES('.yes', 'message').addEvent( 'click', function(){ insertAtCursor( $('message').input, '(+)' ) });
	$ES('.no', 'message').addEvent( 'click', function(){ insertAtCursor( $('message').input, '(-)' ) });
	$ES('.smile', 'message').addEvent( 'click', function(){ insertAtCursor( $('message').input, ':)' ) });
	$ES('.laugh', 'message').addEvent( 'click', function(){ insertAtCursor( $('message').input, ':D' ) });
	$ES('.sad', 'message').addEvent( 'click', function(){ insertAtCursor( $('message').input, ':(' ) });
	$ES('.meh', 'message').addEvent( 'click', function(){ insertAtCursor( $('message').input, ':|' ) });
	$ES('.silence', 'message').addEvent( 'click', function(){ insertAtCursor( $('message').input, ':x' ) });
	$ES('.angry', 'message').addEvent( 'click', function(){ insertAtCursor( $('message').input, '>:(' ) });
	$ES('.wink', 'message').addEvent( 'click', function(){ insertAtCursor( $('message').input, ';)' ) });
	$ES('.tongue', 'message').addEvent( 'click', function(){ insertAtCursor( $('message').input, ':p' ) });
});

function insertAtCursor(myField, myValue) {
        //IE support
        if (document.selection) {
                var temp;
                myField.focus();
                sel = document.selection.createRange();
                temp = sel.text.length;
                sel.text = myValue;
                if (myValue.length == 0) {
                        sel.moveStart('character', myValue.length);
                        sel.moveEnd('character', myValue.length);
                } else {
                        sel.moveStart('character', -myValue.length + temp);
                }
                sel.select();
        }
        //MOZILLA/NETSCAPE support
        else if (myField.selectionStart || myField.selectionStart == '0') {
                var startPos = myField.selectionStart;
                var endPos = myField.selectionEnd;
                myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
                myField.selectionStart = startPos + myValue.length;
                myField.selectionEnd = startPos + myValue.length;
        } else {
                myField.value += myValue;
        }
	myField.focus();
}


var _focus = true;

/*

window.onfocus = function() {
	_focus = true;
	//console.log(_focus);
}

window.onblur = function() {
	_focus = false;
        //console.log(_focus);
}

document.onblur = window.onblur;
document.focus = window.focus;

*/
 

