(function(){
 
var Clst=
{	
	$body:$('body'),
	Ajax:
	{
		HashPoller:null,
		hash:'',
		loadOthers:true,
		init:function()
		{
			this.convertLinks();
			this.hash=decodeURIComponent(window.location.hash);
			 
			if("onhashchange" in window)$(window).bind('hashchange',function(){Clst.Ajax.onHashChange();});
			else this.HashPoller=$.timer(20,function()
			{
				if(Clst.Ajax.hash!=decodeURIComponent(window.location.hash))Clst.Ajax.onHashChange();
			});
			
			if(this.hash=='')window.location.hash='#/';
			else this.onHashChange();
		},
		convertLinks:function(c)
		{
			if(c!=undefined)c=c+' '; else c='';
			var s=c+'a.hash';
			$(s).each(function(){this.href='/#'+$(this).attr('href');});
			s=c+'.btnLogin, '+c+'.btnSignup';
			$(s).colorbox({innerWidth:"340px",innerHeight:"270px",iframe:true});
		},
		onHashChange:function()
		{
			this.hash=decodeURIComponent(window.location.hash);
			if (this.hash!='')
			{
				var page = this.hash.replace('#/','/');
				$.ajax(
				{
					type: "GET",
					url: page,
					dataType: "html",
					success:function(data, stat, Xhr)
					{
						var container=Xhr.getResponseHeader("X-Clst-Xhr-Container");
						var $container = $(container);
						$container.html(data);
						document.title=Xhr.getResponseHeader("X-Clst-Xhr-Title");
						if(container=='#paneListen'){$('#btnListen').attr('href',Clst.Ajax.hash);}
						if (typeof window.pageTracker=='object') pageTracker._trackPageview(page);
						if (typeof window.woopraTracker=='object') woopraTracker.track(page,document.title);
						if (typeof window.FB=='object') FB.XFBML.parse($container[0]);
						if(Clst.Ajax.loadOthers==true)
						{
							$('body').append('<script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script>')
							.append('<script type="text/javascript" src="http://twitter.com/statuses/user_timeline/callistofm.json?callback=twitterCallback2&count=1"></script>')
							.append('<script type="text/javascript">window.fbAsyncInit = function(){FB.init({"appId":"126989500647852","status":true,"cookie":true,"xfbml":true});};(function(){var e = document.createElement("script"); e.async = true;e.src = document.location.protocol+"//connect.facebook.net/en_US/all.js";document.getElementById("fb-root").appendChild(e);}());</script>');
							Clst.Ajax.loadOthers=false;
						}
					}
				});
			}
		}
	},
	Casts:
	{
		channel:'',
		init:function(c)
		{
			this.channel=c;
			$('#castList #casts .cast').mouseenter(function(){$(this).find('a.castStatus.play').css({"display":"inline"});}).mouseleave(function(){$(this).find('a.castStatus.play').css({"display":"none"});});
			$('#castList #casts .cast a.castStatus').click(function(e)
			{
				e.preventDefault();
				var $e=$(this);
				if ($e.hasClass('play'))
				{
					if(Clst.Player.Playlist.url!=Clst.Ajax.hash)
					{
						Clst.Player.Playlist.retrieve(Clst.Ajax.hash); 
					}
					Clst.Player.play($.inArray(Clst.cleanHref($e.attr('href')), Clst.Player.Playlist.casts));
					Clst.UI.scrollToTop();
				}
			});
			
			var btnPlayThisChannel=$('#btnPlayThisChannel');
			if (Clst.Player.Playlist.channel==this.channel) btnPlayThisChannel.hide();
			else btnPlayThisChannel.click(function(){Clst.Player.Playlist.retrieve(Clst.Ajax.hash,function(){Clst.Player.play();}); $(this).hide();});

			if(Clst.Player.$f.getState()<3)Clst.Player.Playlist.retrieve(Clst.Ajax.hash);
		},
		setNowPlaying:function(id)
		{
			var $e = $('#casts #cast'+id+' .details a.castStatus.play');
			$e.parents('#casts').find('a.castStatus.nowplay').removeClass('nowplay').addClass('play').html('Play this Episode').css({"display":"none"});
			$e.addClass('nowplay').removeClass('play').html('Now Playing').css({"display":"inline"});
		},
		Sidebar:
		{
		},
		Episode:
		{
			init:function(c)
			{
				Clst.Player.Playlist.casts.push(c);
				$('#btnPlayThisEpisode').click(function(){Clst.Player.play(Clst.Player.Playlist.casts.length-1);$(this).hide();});
			}
		}
	},
	Player:
	{
		Clip:null,
		Options:{},
		Timer:
		{
			$t:null,
			start:function()
			{
				if (this.$t==null)
				{
					this.$t=$.timer(1000,function(t)
					{
						Clst.Player.Controls.Track.update();
					});
				}
			},
			stop:function(){this.$t.stop(); this.$t=null; this.count=0;}
		},
		trackPosition:function()
		{
			var clip=Clst.Player.$f.getClip();
			var state=Clst.Player.$f.getStatus();
			$.post("/cast/track/",{"episode":clip.id,"time":state.time});
		},
		Config:
		{
			onLoad:function()
			{
				Clst.Player.Controls.init();
				Clst.Player.Tray.init();
			},
			clip:
			{
				onBegin:function(c)
				{
					Clst.Player.Controls.Buttons.PlayPause.playing();
					Clst.Player.Timer.start();
				},
				onStart:function(c){},
				onPause:function(c)
				{
					Clst.Player.Controls.Buttons.PlayPause.paused();
					Clst.Player.Timer.stop();
				},
				onResume:function(c)
				{
					Clst.Player.Controls.Buttons.PlayPause.playing();
					Clst.Player.Timer.start();
				},
				onStop:function(c){Clst.Player.Controls.Buttons.PlayPause.stopped();Clst.Player.Timer.stop();},
				onLastSecond:function(c){},
				onFinish:function(c){$.timer(200,function(t){Clst.Player.Controls.Buttons.PlayPause.stopped();Clst.Player.next();t.stop();Clst.Player.Timer.stop();});}
			}
		},
		Status:
		{
			$:$('#conPlayerStatus'),
			update:function(d)
			{
				/* this.$.show(); */
				this.$.children('img.avatar').attr('src',d.i);
				this.$.children('h1').children('a').html(d.e.t).attr('href','#'+d.e.u);
				this.$.children('h2').children('a.podcast').html(d.p.t).attr('href','#'+d.p.u);
				var c={};
				if (Clst.Player.Playlist.channel!='')
				{
					c.t=Clst.Player.Playlist.channel;
					c.u=Clst.Player.Playlist.url;
				}
				else
				{
					c.t=d.p.t;
					c.u=d.p.u;
				}
				this.$.find('h2 span a.channel').html(c.t).attr('href',c.u);
				Clst.Player.Controls.Buttons.NPD.onupdate();
				if (typeof d.a=='object') this.Ads.roll(d.a);
			},
			Ads:
			{
				$:$('#conPlayerAds a'),
				roll:function(a)
				{
					for(var i in a) break;
					var ad = a[i];
					this.$.attr('href',ad.url);
					this.$.children('.title').html(ad.title.substring(0,35)+'&#8230;');
					this.$.children('.price-merchant').html('$'+ad.price+' @ '+ad.merchant);
					this.$.children('img').attr('src',ad.tracker);
				}
			}
		},
		Playlist:
		{
			index:0,
			casts:[],
			url:null,
			channel:'',
			getClip:function(i)
			{
				if(i==undefined)i=0;
				return this.casts[this.index];
			},
			retrieve:function(u,cb)
			{
				this.url=u;
				this.casts=[];
				this.channel=Clst.Casts.channel;
				$('#casts .cast a.castStatus').each(function(i,e)
				{
					Clst.Player.Playlist.casts[i]=Clst.cleanHref(e.href);
				});
				if (typeof cb=='function') cb.call();
			}
		},
		$:$('#tray .swf'),
		$f:null,
		$d:$('#tray .detail'),
		$n:$('#footer .player'),
		init:function()
		{
			this.$f=flowplayer(this.$[0],this.Options,this.Config);
		},
		load:function(i)
		{
			this.$d.load('/cast/detail/podcast/'+i+'/');
		},
		play:function(i)
		{
			if(this.$f.isPlaying())this.$f.stop();
			if(i==undefined)i=0;
			this.Playlist.index=i;
			this.load(this.Playlist.casts[i]);
		},
		prev:function(){this.play(parseInt(Clst.Player.Playlist.index)-1);},
		next:function(){this.play(parseInt(Clst.Player.Playlist.index)+1);},
		Controls:
		{
			$:$('#controls'),
			init:function()
			{
				Clst.Player.$f.unmute();
				Clst.Player.$f.setVolume(100);				
				
				this.Buttons.PlayPause.$.click(function(){Clst.Player.Controls.Buttons.PlayPause.onclick();});
				this.Buttons.Prev.click(function(){Clst.Player.prev();});
				this.Buttons.Next.click(function(){Clst.Player.next();});
				this.Buttons.Mute.$.click(function(){Clst.Player.Controls.Buttons.Mute.toggle();});
				this.Buttons.Tray.$.click(function(){if(!Clst.Player.Controls.Buttons.Tray.$.hasClass('disabled'))Clst.Player.Tray.toggle();});
				this.Track.init();
				this.Buttons.Tray.disable();
				this.Buttons.NPD.$.click(function(){Clst.Player.Controls.Buttons.NPD.onclick();});
				$('#btnHideVideo').click(function(){Clst.Player.Tray.up();});
			},
			Buttons:
			{
				PlayPause:
				{
					$:$('#controls .play'),
					state:'',
					paused:function(){this.state='paused'; this.$.removeClass('pause'); return this.$;},
					stopped:function(){this.state='stopped'; this.$.removeClass('pause'); return this.$;},
					playing:function(){this.state='playing'; this.$.addClass('pause'); return this.$;},
					onclick:function()
					{
						switch (this.state)
						{
							case '': Clst.Player.play(0); break;
							case 'stopped':
							case 'paused': Clst.Player.$f.resume(); break;
							case 'playing': Clst.Player.$f.pause(); break;
							
						}
					}
				},
				Prev:$('#controls .prev'),
				Next:$('#controls .next'),
				Mute:
				{
					$:$('#controls .mute'),
					mute:function(){Clst.Player.$f.mute(); this.$.addClass('un');},
					unmute:function(){Clst.Player.$f.unmute(); this.$.removeClass('un');},
					toggle:function()
					{
						if(this.$.hasClass('un'))this.unmute();
						else this.mute();
					}
				},
				Tray:
				{
					$:$('#controls .tray'),
					up:function(){this.$.attr('class','tray up');},
					down:function(){this.$.attr('class','tray down');},
					disable:function(){this.$.attr('class','tray disabled');}
				},
				NPD:
				{
					$:$('#controls .npd-button'),
					$s:$('#footer .starfield'),
					disable:function(){this.$.attr('class','npd-button disabled');},
					onupdate:function()
					{
						if (this.$.hasClass('disabled')) this.expand();
					},
					expand:function()
					{
						this.$s.animate({"margin-bottom":"90px"},200);
						Clst.Player.$n.animate({"bottom":"0px"},200,'',function(){Clst.Player.Controls.Buttons.NPD.$.removeClass('disabled').removeClass('expand').addClass('collapse');});
					},
					collapse:function()
					{
						this.$s.animate({"margin-bottom":"41px"},200);
						Clst.Player.$n.animate({"bottom":"-49px"},200,'',function(){Clst.Player.Controls.Buttons.NPD.$.removeClass('disabled').removeClass('collapse').addClass('expand');});
					},
					onclick:function()
					{
						if (this.$.hasClass('expand')) this.expand();
						else if (this.$.hasClass('collapse')) this.collapse();
					}
				}
			},
			Track:
			{
				Scrubber:$('#controls .track .scrubber'),
				Buffer:$('#controls .track .buffer'),
				Progress:$('#controls .track .progress'),
				Playhead:$('#controls .track .playhead'),
				init:function()
				{
					this.Scrubber.click(function(e)
					{
						var clip=Clst.Player.$f.getClip();
						var ratio=clip.duration/196;
						var s=ratio*e.layerX;
						Clst.Player.$f.seek(s);
					});
				},
				update:function()
				{
					if(Clst.Player.Controls.Buttons.PlayPause.state=='playing')
					{
						var clip=Clst.Player.$f.getClip();
						var state=Clst.Player.$f.getStatus();
						state.time=state.time+clip.start;
						
						/* if (Math.floor(state.time)%5==0) Clst.Player.trackPosition(); */
												
						Clst.Player.Controls.Time.Duration.html(Clst.Player.Controls.Time.format(clip.duration));
						Clst.Player.Controls.Time.Played.html(Clst.Player.Controls.Time.format(state.time));
						
						var progress = Math.floor((state.time/clip.duration)*100);
						var buffer=Math.floor(((state.time+state.bufferEnd)/clip.duration)*100);

						/* this.Buffer.css('width',buffer+'%'); */
						this.Progress.css('width',progress+'%');
						this.Playhead.css('left',(progress-3)+'%');
					}
				}
			},
			Time:
			{
				Played:$('#controls .time .played'),
				Duration:$('#controls .time .duration'),
				format:function(s)
				{
					var minutes=Math.floor(s/60);
					var seconds=Math.floor(s%60);
					return (minutes<10?'0':'')+minutes+':'+(seconds<10?'0':'')+seconds;
				}
			}
		},
		Tray:
		{
			upMargin:'-250px',
			downMargin:'117px',
			duration:750,
			$:$('#content'),
			toggle:function()
			{
				if(this.isDown())this.up();
				else this.down();
			},
			up:function(disable)
			{
				this.$.animate({marginTop:this.upMargin},this.duration);
				if(disable!=undefined)Clst.Player.Controls.Buttons.Tray.disable();
				else Clst.Player.Controls.Buttons.Tray.down();
			},
			down:function()
			{
				this.$.animate({marginTop:this.downMargin},this.duration);
				Clst.Player.Controls.Buttons.Tray.up();
			},
			isDown:function(){if(this.$.css('margin-top')==this.downMargin)return true; else return false;},
			init:function(){$('#tray .fullscreen').click(function(){Clst.Player.$f.toggleFullscreen();});}
		}
	},
	Panes:
	{
		$:$('#content .wrapper .ninesixty .pane'),
		toggle:function(e)
		{
			this.$.filter(':visible').fadeOut(250,function()
			{
				var p=this;
				$(e).fadeIn(250,function()
				{
					if(e.match('[Listen|Browse|Search]')!=null)Clst.Nav.Main.toggle(e);
					Clst.UI.scrollToTop();
					if (e!='#'+p.id) $(p).html('');
				});
			});
		}
	},
	Nav:
	{
		Main:
		{
			$:$('#header .nav.main li a'),
			toggle:function(e)
			{
				var e=e.replace('#pane','');
				this.$.removeClass('selected');
				$('#header .nav.main li.'+e.toLowerCase()+' a').addClass('selected');
			}
		}
	},
	Cmnts:
	{
		bindPagination:function(obj)
		{
			$('#conComments .pagination .list-pages a').each(function(i)
			{
				$(this).click(function(e){Clst.Cmnts.list(this.href); return false;});
			});
		},
		bindForm:function()
		{
			$('#btnCommentsAdd').click(function(){Clst.Cmnts.add();});
		},
		list:function(url)
		{
			$('#conComments').load(url||this._data.url);
		},
		add:function()
		{
			$.post('/comment/add/',$('#frmComments').serialize(),function(r){$('#conComments').html(r);},'html');
		},
		setCount:function(count)
		{
			count=count||0;
			$('#conNumCmnts').html('('+count+')');
		}
	},
	Auth:
	{
		Dialog:null,
		init:function()
		{
			$('.btnLogout').live('click',function(){$.get('/auth/logout/',null,function(r){$('body').append(r);},'html'); return false;});
		},
		initForm:function()
		{
			Clst.UI.Forms.labelize('#frmLogin');
			$('#frmLogin').submit(function(){Clst.UI.loading(this);});
			$('.btnSwitch').click(function(){window.top.window.$.fn.colorbox.next(); return false;});
		},
		postLogin:function()
		{
			$.timer(1000,function(t){$.fn.colorbox.close();t.stop();});
			$('#footer ul.user-nav, .btnSignup, .btnLogin').hide();
			$('#header .starfield .nav.secondary').load('/auth/nav/');
			Clst.Rtngs.bind();
			Clst.Cmnts.list();
		},
		postLogout:function()
		{
			$('#footer ul.user-nav').show();
			$('#header .starfield .nav.secondary').load('/auth/nav/');
			Clst.Rtngs.unbind();
			Clst.Cmnts.list();
			$('#paneAccount').html('');
			if(Clst.Ajax.hash.match('dashboard'))window.location.hash='#/';
		}
	},
	Acnt:
	{
		init:function()
		{
			$('.btnSignup').colorbox({innerWidth:"340px",innerHeight:"270px",iframe:true,rel:"signup-login"});
		},
		initForm:function()
		{
			Clst.UI.Forms.labelize('#frmSignup');
			$('#frmSignup').submit(function(){Clst.UI.loading(this);});
			$('.btnSwitch').click(function(){window.top.window.$.fn.colorbox.next();});
		},
		refreshPhoto:function()
		{
			$('#conProfilePhoto').html('').load('/account/editphoto/');
		},
		bindPhotoForm:function()
		{
			$('#frmProfilePhoto').submit(function(){Clst.UI.loading(this);});
		},
		bindAccountForm:function()
		{
			$('#frmAccount').submit(function(){Clst.UI.loading(this); $.post('/account/edit/',$(this).serialize(),function(r){$('#conAccount').html(r)},'html');});
		},
		bindProfileForm:function()
		{
			$('#frmProfileDetails').submit(function(){Clst.UI.loading(this); $.post('/account/editprofile/',$(this).serialize(),function(r){$('#conProfileDetails').html(r)},'html');});
		},
		bindPassword:function()
		{
			$('#frmChangepass').submit(function(){Clst.UI.loading(this); $.post('/account/changepass/',$(this).serialize(),function(r){$('#conChangepass').html(r)},'html');});
		},
		bindFeed:function()
		{
			$('#frmSubmitFeed').submit(function(){Clst.UI.loading(this); Clst.Feed.add();}); 
		}
	},
	Feed:
	{
		list:function(user)
		{
			$('#conListFeeds').load('/feed/list/user/'+user+'/');
		},
		add:function()
		{
			Clst.UI.loading('#frmSubmitFeed');
			$.post('/feed/add/',$('#frmSubmitFeed').serialize(),function(r){$('#conSubmitFeed').html(r);},'html');
		}
	},

	Dshbd:
	{
		tabs:function(i)
		{
			$('#paneAccount .tabs').tabs({selected:i||0});
		}
	},
	Rtngs:
	{
		bind:function()
		{
			$('.btnRateUp, .btnRateDown').unbind('click').click(function(){Clst.Rtngs.rate($(this).attr('rel'),$(this).attr('rev')); return false;});
		},
		unbind:function()
		{
			$('.btnRateUp, .btnRateDown').unbind('click').click(function(){$('.btnLogin:first').click();});
		},
		rate:function(r,id)
		{
			$.post('/rating/rate/',{rating:r,episode:id},function(data)
			{			
				$('#conRatingBtns'+data.episode+' .btnRateUp var').html(data.ups);
				$('#conRatingBtns'+data.episode+' .btnRateDown var').html(data.downs);
			},'json');
		}
	},
	Cmnts:
	{
		bindPagination:function(obj)
		{
			$('#conComments .pagination .list-pages .pages a').click(function(){Clst.Cmnts.list($(this).attr('href')); return false;});
		},
		bindForm:function()
		{
			$('#btnCommentsAdd').click(function()
			{
				$.post('/comment/add/',$('#frmComments').serialize(),function(r){$('#conComments').html(r);},'html');
			});
		},
		list:function(url)
		{
			$('#conComments').load(url||$('#conComments').data('url'));
		},
		setCount:function(count)
		{
			if(count==undefined)count=0;
			$('#conNumCmnts').html('('+count+')');
		}
	},
	About:
	{
		bindSuggest:function()
		{
			$('#frmSuggest').submit(function(){Clst.UI.loading(this); $.post('/about/suggest/',$(this).serialize(),function(r){$('#paneMisc').html(r)},'html');});
		},
		bindContact:function()
		{
			$('#frmContact').submit(function(){Clst.UI.loading(this); $.post('/about/contact/',$(this).serialize(),function(r){$('#paneMisc').html(r)},'html');});
		}
	},
	Search:
	{
		bind:function()
		{
			var $frm=$('#header .bluebar .ninesixty form.castSearch');
			var $inp = $frm.children('fieldset').children('input[type=text]');
			$frm.submit(function(e)
			{
				var term = $inp.val();
				e.preventDefault();
				if (term!='') window.location.hash='#/search/'+escape(term)+'/';
			});
		}
	},
	UI:
	{
		Forms:
		{
			labelize:function(c)
			{
				if(c!=undefined)c=c+' '; else c='';
				var s=c+"label.inlined + .input-text";

				$(s).each(function()
				{
					if($(this).val()!="")$(this).prev("label.inlined").addClass("has-text");
					$(this).focus(function(){$(this).prev("label.inlined").addClass("focus");});	
					$(this).keypress(function(){$(this).prev("label.inlined").addClass("has-text").removeClass("focus");});
					$(this).blur(function(){if($(this).val()==""){$(this).prev("label.inlined").removeClass("has-text").removeClass("focus");}});
				});
			}
		},
		hideSuccess:function()
		{
			$.timer(3000,function(timer){$('div.success').hide();timer.stop();})
		},
		loading:function(c)
		{
			$(c).find('input[type=image]').addClass('loading');
		},
		scrollToTop:function(){$('html, body').animate({scrollTop:0}, 500);},
		Dropdown:
		{
			open:false,
			init:function()
			{
				var open=this.open;
				$('.dropdown').mouseenter(function()
				{
					if (open==false)
					{
						$(this).children('ul').slideDown('fast',function(){open=true;});
					}
				}).mouseleave(function()
				{
					if (open==true)
					{
						$(this).children('ul').slideUp('fast',function(){open=false;});
					}
				});
			}
		}
	},
	redirect:function(url){window.location.href=url;},
	cleanHref:function(href){return href.replace('#','').replace('http://'+Clst.$body.data('domain')+'/','');}
};
window.Clst=Clst;

})();