// for ExtJS
if (Ext) {
	Ext.ns('aTunes.Ext');
	// patch for prototypejs/IE
	if (window.Event) {
		Object.extend(Event, {
			element: function(event){
				var node = Event.extend(event).target;
				return node && Element.extend(node.nodeType == Node.TEXT_NODE ? node.parentNode : node);
			},
			pointer: function(event){
				return {
					x: event.pageX ||
					(event.clientX +
					((document && document.documentElement && document.documentElement.scrollLeft) ||
					(document && document.body && document.body.scrollLeft))),
					y: event.pageY ||
					(event.clientY +
					((document && document.documentElement && document.documentElement.scrollTop) ||
					(document && document.body && document.body.scrollTop)))
				};
			}
		});
	}
} // end of for ExtJS

Ext.apply(aTunes.Ext,{
	createBox: function(t, s) {
		return ['<div class="msg">',
			'<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>',
			'<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><h3>', t, '</h3>', s, '</div></div></div>',
			'<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>',
			'</div>'].join('');
	},
	msg: function(title, format){
		var msgCt = Ext.DomHelper.insertFirst(document.body, {id:'msg-div'}, true);
		msgCt.alignTo(document, 't-t');
			var s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
			var m = Ext.DomHelper.append(msgCt, {html:this.createBox(title, s)}, true);
			m.slideIn('t').pause(1).ghost("t", {remove:true});
	}
});

aTunes.Ext.BookmarkDialog = function(config) {
	this.homeUrl = config.homeUrl;
	this.removeUrl = config.removeUrl;
	this.limit = 10;
	
	this.ds = new Ext.data.JsonStore({
		url: config.listUrl,
		autoLoad: false,
		id:'id',
		//remoteSort:true,
		root:'artists',
		totalProperty: 'totalCount',
		fields:['id', 'name'],
		baseParams: {fmt:'json',limit:this.limit},
		listeners: {
			'beforeload': {fn:function(){this.btnRemove.disable();this.showIndicator(true,'お気に入りの読み込み中...')},scope:this},
			'load': {fn:function(){this.btnRemove.enable();this.showIndicator(false);},scope:this},
			'loadexception': {fn:function(){this.showIndicator(false);},scope:this}
		}
	});
	
	this.btnRemove = new Ext.Button({
		text:'削除',
		handler:function() {
			var sm = this.grid.getSelectionModel();
			var records = sm.getSelections();
			var ids = [];
			for (var i=0; i<records.length; i++) {
				ids.push(records[i].id);
			}
			Ext.Ajax.request({
				url:this.removeUrl,
				params: {fmt:'json',artistid:ids.join(',')},
				success: function(response) {
					this.ds.reload();
				},
				scope:this
			});
		},
		scope: this
	});
	
	this.btnPlay = new Ext.Button({
		text:'aTunesで再生',
		handler:function() {
			var sm = this.grid.getSelectionModel();
			var records = sm.getSelections();
			if (records.length>0) {
				location.href = this.homeUrl+"/artist/"+encodeURI(records[0].data.name);
				return;
			}
		},
		scope: this
	});
	
	var sm = new Ext.grid.CheckboxSelectionModel({singleSelect:false});
	this.grid = new Ext.grid.GridPanel({
		store: this.ds,
		stateful:false,
		columns: [
			sm,
			{header: "名前", width: 150, sortable: false, dataIndex: 'name'}
		],
		viewConfig: {
			deferEmptyText: true,
			emptyText: 'お気に入りアーティストが登録されていません。',
			forceFit: true
		},
		sm: sm,
		stripeRows: true,
		bbar: new Ext.PagingToolbar({
			store: this.ds,
			pageSize: this.limit,
			displayInfo: true,
			displayMsg: ' {2}件中 {0} - {1}件',
			emptyMsg: ''
		})
	});
	
	Ext.apply(config,{
		title:'お気に入りの編集',
		modal:true,
		layout:'fit',
		width:380,
		height: 240,
		closeAction:'hide',
		plain:true,
		defaults:{
			frame:false,
			border:false
		},
		buttons: [this.btnPlay,this.btnRemove],
		items: this.grid
	});
	aTunes.Ext.BookmarkDialog.superclass.constructor.call(this, config);
}
Ext.extend(aTunes.Ext.BookmarkDialog, Ext.Window, {
	doLoad: function() {
		this.ds.load();
	},
	
	showIndicator: function(show,msg) {
		if (show) {
			Ext.MessageBox.show({
				title:'atunes',
				msg: msg,
				width:300,
				wait:true,
				waitConfig: {interval:200}
			});
		} else {
			Ext.MessageBox.hide();
		}
	}
});

aTunes.Ext.OpenIdLoginDialog = function(config) {
	this.url = config.url;
	this.fmHatena = new Ext.form.FormPanel({
		url: config.url,
		method: 'POST',
		frame: false,
		standardSubmit: true,
		labelAlign: 'right',
		labelWidth: 85,
		items: [
			{xtype:'hidden',id:'hatenaLogin_op',name:'hatenaLogin[op]',value:'hatena.ne.jp'},
			{
				layout:'column',
				frame: false,
				border: false,
				items: [{
					columnWidth:.7,
					layout: 'form',
					border: false,
					items: [{
						xtype: 'textfield',
						fieldLabel: 'はてなID',
						id: 'hatenaLogin_id',
						name: 'hatenaLogin[id]',
						selectOnFocus:true,
						allowBlank: true,
						emptyText: 'はてなIDを入力',
						blankText: 'はてなIDを入力してください'
						//stateful: true,
						//stateEvents: ['valid','blur'],
						//getState: function() {return {value: this.getValue()};},
						//applyState: function(state) {this.setValue(state.value);},
					}]
				},
				{
					columnWidth:.3,
					border: false,
					items: [{
							xtype: 'button',
							text:'ログイン', 
							handler: function(){
								this.fmHatena.getForm().getEl().dom.action = this.url;
								this.fmHatena.getForm().submit();
							},
							icon:'/images/icon/fammini/action_go.gif',
							iconCls:'x-btn-text-icon',
							scope: this
						}
					]
				}]
			}
		]
	});
	
	Ext.apply(config,{
		title:'OpenID ログイン',
		modal:true,
		layout:'fit',
		width:380,
		height: 240,
		closeAction:'hide',
		plain:true,
		defaults:{
			frame:false,
			border:false
		},
		listeners: {
			'show': function(){ 
				this.fmHatena.getForm().getEl().dom.action = this.url;
			},
			scope:this
		},
		items: [
		{layout:'ux.row',id:'login-container',defaults:{frame:false,border:false},
		items:[
			{html:'<p>はてな, Yahoo! JAPAN, mixiのいずれかのアカウントでログインできます。</p>'},
			{html:'<h3 id="hatena_login">はてなIDでログイン</h3>'},
			this.fmHatena,
			{html:'<h3 id="yahooj_login">Yahoo! JAPAN IDでログイン</h3>'+
				'<a href="/frontend_dev.php/openid/auth/openid/yahoo.co.jp"><img src="http://i.yimg.jp/images/login/btn/btnXSYid.gif" width="241" height="28"alt="Yahoo! JAPAN IDでログイン" border="0"></a>'+
				'<h3 id="mixi_login">mixiでログイン</h3>'+
				'<a href="/frontend_dev.php/openid/auth/openid/mixi.jp"><img src="/images/op/mixi/b_150.gif" alt="B_150" /></a>'
			}
		]}
		]
	});
	
	aTunes.Ext.OpenIdLoginDialog.superclass.constructor.call(this, config);
	this.addEvents({posted:true});
};
Ext.extend(aTunes.Ext.OpenIdLoginDialog, Ext.Window, {
});

aTunes.Ext.SearchPanel = function(config) {
	this.ds = new Ext.data.JsonStore({
		url: config.url,
		root:'artists',
		totalProperty: 'totalCount',
		fields: ['name'],
		baseParams: {fmt:'json'}
	});
	
	this.btnSubmit = new Ext.Button({
		text:'Search',
		icon:'/images/icon/fammini/arrow_right.gif',
		iconCls:"x-btn-text-icon",
		handler:function(){
			this.getForm().submit();
		},
		scope:this
	})
	Ext.apply(config,{
		method: 'GET',
		standardSubmit: true,
		defaults: {bodyStyle:'padding-left:1px',style:'color:#fff',frame:false,border:false},
		layout:'table',
		items: [
			//{xtype:'textfield',name:'artist',hideLabel:true, value:config.artist},
			{
				xtype:'combo',
				name:'artist',
				loadingText:'履歴を読み込んでいます...',
				hideLabel:true,
				editable:true,
				value:config.artist,
				store: this.ds,
				valueField:'name',
				displayField:'name'
			},
			this.btnSubmit
		]
	});
	aTunes.Ext.SearchPanel.superclass.constructor.call(this, config);
};
Ext.extend(aTunes.Ext.SearchPanel, Ext.form.FormPanel, {
});

aTunes.Ext.RelateArtistPanel = function(config) {
	this.ds = new Ext.data.JsonStore({
		url: config.url,
		autoLoad: false,
		id:'id',
		root:'relates',
		totalProperty: 'totalCount',
		fields: ['name','image_small'],
		baseParams: {artist:config.artist, fmt:'json'},
		listeners: {
			'load': {fn:function(store,records,options){
					if (store.getCount()>0) {
						var el = Ext.fly("relateartists");
						if (el) el.fadeIn({duration: 2});
					}
				}
			},
			scope:this
		}
	});
	
	// list template
	var tpl = new Ext.XTemplate(
		'<tpl for=".">',
		'<div class="thumb-wrap" title="{name}">',
			'<div class="thumb">',
				'<a href="{url}">',
					'<img src="{image_small}" height="50"/>',
				'</a>',
			'</div>',
			'<p><a href="{url}">{name}</a></p>',
		'</div>',
		'</tpl>'
	);
	
	var formatData = function(data){
		data.url = config.homeUrl+'?'+Ext.urlEncode({artist:data.name});
		return data;
	};
	
	this.view = new Ext.DataView({
		id:'relateartists',
		title:'view',
		store: this.ds,
		height:config.height,
		//autoHeight:true,
		autoScroll:true,
		itemSelector:'div.thumb-wrap',
		overClass:'x-view-over',
		emptyText: '関連アーティストがみつかりませんでした',
		loadingText: '関連アーティストを探しています...',
		tpl:tpl,
		prepareData: formatData.createDelegate(this)
	});
	Ext.apply(config,{
		layout:'fit',
		items:[this.view]
	});
	aTunes.Ext.RelateArtistPanel.superclass.constructor.call(this, config);
};
Ext.extend(aTunes.Ext.RelateArtistPanel, Ext.Panel, {
	doLoad: function() {
		this.ds.load();
	}
});

aTunes.Ext.YoutubePlayerPanel = function(config) {
	this.player = config.player;
	Ext.apply(config,{
		html:''
			//+ '<div id="youtubeplayerpanel_control">'
			//+ '<div onclick="aTunes.MediaPlayer.doNext();"><img src="/images/icon/famsilk/control_end.png"/></div>'
			//+ '</div>'
			+ '<div id="youtubeplayerpanel_content"><div class="loading-indicator">ビデオリストを読み込み中...</div></div>'
	});
	aTunes.Ext.YoutubePlayerPanel.superclass.constructor.call(this, config);
};
Ext.extend(aTunes.Ext.YoutubePlayerPanel, Ext.Panel, {
});

aTunes.Ext.VideoListPanel = function(config) {
	this.player = config.player;
	this.ds = new Ext.data.JsonStore({
		url: config.url,
		autoLoad: false,
		id:'id',
		root:'videos',
		totalProperty: 'totalCount',
		fields: ['id','title','imgurl','source'],
		baseParams: {artist:config.artist, fmt:'json', limit:config.itemPerPage},
		listeners: {
			'load': function(store,records,options){
				try {
					if (store.getCount()>0) {
						var el = Ext.fly("videolist");
						if (el) el.fadeIn({duration: 2});
						this.player.addVideoList(store,records,options);
						// first play
						if (!this.player.isInitialzed) {
							this.view.select(0);
						} else {
							// update selection
							this.updateSelection();
						}
					}
				} catch (e) {
				}
			},
			scope:this
		}
	});
	
	// list template
	var tpl = new Ext.XTemplate(
		'<tpl for=".">',
		'<div id="v{id}" class="thumb-wrap" title="{title}({id})">',
			'<div class="videoitem">',
				'<img src="{imgurl}" width="130" height="97"/>',
				'<div class="videotitle">{title}</div>',
			'</div>',
		'</div>',
		'</tpl>'
	);
	
	var formatData = function(data){
		data.url = config.homeUrl+'?'+Ext.urlEncode({artist:data.name});
		this.lookup["v"+data.id] = data;
		return data;
	};
	
	this.view = new Ext.DataView({
		id:'videolist',
		store: this.ds,
		singleSelect:true,
		//autoHeight:true,
		autoWidth:true,
		autoScroll:true,
		itemSelector:'div.thumb-wrap',
		overClass:'x-view-over',
		emptyText: 'ビデオがみつかりませんでした',
		loadingText: 'ビデオリストを読み込み中...',
		tpl:tpl,
		prepareData: formatData.createDelegate(this),
		listeners: {
			//'beforeselect':function(view){},
			'selectionchange':function(view,selections){
				if (selections && selections.length > 0) {
					var el = selections[0];
					var data = this.lookup[el.id];
					if (data) this.fireEvent('videoselected', this, data);
				}
			},
			scope:this
		}
	});
	Ext.apply(config,{
		layout:'fit',
		bodyStyle:'padding:2px',
		autoScroll:true,
		items:[this.view],
		bbar: new Ext.PagingToolbar({
			store: this.ds,
			pageSize: config.itemPerPage,
			displayInfo: true,
			displayMsg: ' {2}件中 {0} - {1}件',
			emptyMsg: ''
		})
	});
	aTunes.Ext.VideoListPanel.superclass.constructor.call(this, config);
	this.addEvents({videoselected:true});
};
Ext.extend(aTunes.Ext.VideoListPanel, Ext.Panel, {
	// v+videoid -> videoitem
	lookup:{},
	
	// index -> videoid
	list:{},
	
	findByVideoId: function(id) {
		return this.lookup['v'+id];
	},
	
	findIndexByVideoId: function(videoid) {
		var index = this.ds.indexOfId(videoid);
		if (index!=-1) {
			var s = 0;
			if (this.ds.lastOptions.params && this.ds.lastOptions.params.start) 
				index += this.ds.lastOptions.params.start;
		} else {
			// TODO: search from list
		}
		return index;
	},
	
	updateSelection: function() {
		if (this.player.playingVideoId != '') {
			var index = this.view.indexOf('v'+this.player.playingVideoId);
			if (index!=-1) this.view.select(index);
		}
	},

	doLoad: function(start) {
		this.ds.load({params:{start:start}});
	}
});

aTunes.Ext.ArtistDetailPanel = function(config) {
	Ext.apply(config,{
		html:'<div id="artistdetail_img"></div>'
			+ '<div id="artistdetail_indicator" class="loading-indicator">詳細情報を検索しています...</div>'
			+ '<p id="artistdetail_comment"></p>'
			+ '<div id="artistdetail_footer"></div>'
	});
	aTunes.Ext.ArtistDetailPanel.superclass.constructor.call(this, config);
};
Ext.extend(aTunes.Ext.ArtistDetailPanel, Ext.Panel, {
	setImageUrl: function(url) {
		if (url) {
			var image = Ext.get('artistdetail_img');
			if (image) {
				image.update('<img src="'+url+'"/>',true);
				image.fadeIn();
			}
		}
	},
	
	doLoad: function(artist) {
		Ext.Ajax.request({
			url:this.url,
			params: {fmt:'json',artist:artist},
			success: function(response) {
				var indicator = Ext.get('artistdetail_indicator');
				if (indicator) indicator.remove();
				var response = eval("("+response.responseText+")");
				if (response.success && response.detail) {
					if (response.detail.url) {
						var footer = Ext.get('artistdetail_footer');
						footer.update('<a href="'+response.detail.url+'">Wikipedia</a>',true);
					}
					if (response.detail.body) {
						var comment = Ext.get('artistdetail_comment');
						if (comment) {
							comment.update(response.detail.body,true);
							comment.fadeIn();
						}
					}
					if (response.detail.picture) {
						var picture = Ext.get('artistdetail_img');
						if (picture) {
							picture.update('<img src="'+response.detail.picture+'"/>',true);
							picture.fadeIn();
						}
					}
				}
			},
			failure: function(response) {
				//this.showIndicator(false);
				//var response = eval("("+response.responseText+")");
			},
			scope:this
		});
	}
});

aTunes.Ext.NewReleasePanel = function(config) {
	this.ds = new Ext.data.JsonStore({
		url: config.url,
		autoLoad: false,
		id:'id',
		root:'items',
		totalProperty: 'totalCount',
		fields: ['name', 'url', 'author', 'imgurl', {name:'releasedat', type:'date', dateFormat:'U'}],
		baseParams: {artist:config.artist, fmt:'json', limit:10},
		listeners: {
			'load': {fn:function(store,records,options){
					if (store.getCount()>0) {
						var el = Ext.fly("newreleases");
						if (el) el.fadeIn({duration: 2});
					}
				}
			},
			scope:this
		}
	});
	
	// template
	var tpl = new Ext.XTemplate(
		'<tpl for=".">',
		'<div class="nr_item">',
			'<tpl if="imgurl">',
				'<div class="nr_thumbnail">',
					'<a href="{url}" title="{name}" target="_blank">',
						'<img src="{imgurl}"/>',
					'</a>',
				'</div>',
			'</tpl>',
			'<div class="nr_meta">',
				'<a href="{url}" title="{name}" target="_blank"><span class="nr_title">{name}</span></a></br>',
				'<span class="nr_author">{author}</span>',
				'<span class="nr_releasedat">{releasedat:date("Y/m/d")}</span>',
			'</div>',
			'<div class="nr_footer"></div>',
		'</div>',
		'</tpl>'
	);
	
	var formatData = function(data){
		return data;
	};
	
	this.view = new Ext.DataView({
		id:'newreleases',
		store: this.ds,
		//autoHeight:true,
		autoWidth:true,
		//autoScroll:false,
		overClass:'x-view-over',
		emptyText: '作品がみつかりませんでした',
		loadingText: '新作を探しています...',
		width:config.width,
		tpl:tpl,
		prepareData: formatData.createDelegate(this)
	});
	Ext.apply(config,{
		//layout:'fit',
		items:[this.view]
	});
	aTunes.Ext.NewReleasePanel.superclass.constructor.call(this, config);
};
Ext.extend(aTunes.Ext.NewReleasePanel, Ext.Panel, {
	doLoad: function() {
		this.ds.load();
	}
});

aTunes.MediaPlayer = {
	isInitialzed:false,
	playingVideoId:'',
	YouTubePlayerId: 'atunes_ytplayer',
	YouTubePlayState_Stopped: -1,
	YouTubePlayState_Ended: 0,
	YouTubePlayState_Playing: 1,
	YouTubePlayState_Paused: 2,
	YouTubePlayState_Buffering: 3,
	YouTubePlayState_Quing: 4,
	
	onPlayerReady: function(videoItem,flashPlayer) {},
	onPlayerEnded: function(videoid) {},
	onPlayerRequestList: function(index) {},
	
	doPlay: function(videoItem) {
		if (videoItem.id != this.playingVideoId) {
			this.playingVideoId = videoItem.id;;
			var html = this.createYouTubeFlashPlayer(videoItem.id,1,0);
			this.onPlayerReady(videoItem, html);
		}
	},
	
	doPlayByIndex: function(index) {
		var v = this.findVideoItemByIndex(index);
		if (v) this.doPlay(v);
		else {
			this.isInitialzed = false;
			this.onPlayerRequestList(index);
		}
	},
	
	doNext: function() {
		var index = this.indexOfVideoId(this.playingVideoId);
		if (index == -1) return; // TODO
		if (++index==this.totalCount) {
			// TODO: repeat settings
			this.doPlayByIndex(0);
		} else {
			this.doPlayByIndex(index);
		}
	},
	
	list: {},
	totalCount: 0,
	
	indexOfVideoId: function(videoid) {
		var index = 1;
		for (i in this.list) {
			if (this.list[i].id == videoid) {
				index = i;
				break;
			}
		}
		return index;
	},
	
	findVideoItemByIndex: function(index) {
		return this.list[index];
	},
	
	addVideoList: function(store, records, options) {
		var s = 0;
		if (options.params && options.params.start) s = options.params.start;
		var l = this.list;
		var c = records.length;
		for (var i=0; i<c; i++) {
			var r = records[i];
			if (r) l[i+s] = r.data;
		}
		this.totalCount = store.getTotalCount();
	},
	
	onYouTubePlayerReady: function(playerId) {
		this.ytplayer = document.getElementById(this.YouTubePlayerId);
		this.ytplayer.addEventListener(
			"onStateChange",
			"aTunes.MediaPlayer.onYouTubeStateChange"
			);
		this.isInitialzed = true;
	},
	
	onYouTubeStateChange: function(newState) {
		if (newState == this.YouTubePlayState_Ended) {
			this.doNext();
		}
	},
	
	createYouTubeFlashPlayer: function(videoid,autoplay,loop) {
		var html = '<div id="ytapiplayer">'
			+ ''
			+ '</div>'
			+ '<script type="text/javascript">'
			+ 'var params = { allowScriptAccess: "always", wmode: "transparent" };'
			+ 'var atts = { id: "'+this.YouTubePlayerId+'" };'
			+ 'swfobject.embedSWF("http://www.youtube.com/v/'+videoid+'&autoplay='+autoplay+'&loop='+loop+'&enablejsapi=1&playerapiid=ytplayer",'
			+ '"ytapiplayer", "425", "356", "8", null, null, params, atts);'
			+ '</script>'
		;
		//html = videoid;
		return html;
	}
}

// EventHandler from YouTube Javascript API
function onYouTubePlayerReady(playerId) {
	aTunes.MediaPlayer.onYouTubePlayerReady(playerId);
}

Ext.onReady(function(){
	Ext.QuickTips.init();
	
	var player = aTunes.MediaPlayer;
	var dlgLogin = new aTunes.Ext.OpenIdLoginDialog({
		url: _config.baseUrl+'/openid/login'
	});
	
	var dlgBookmark = new aTunes.Ext.BookmarkDialog({
		homeUrl:_config.baseUrl+'/atunes/index',
		listUrl:_config.baseUrl+'/userartist/list',
		removeUrl:_config.baseUrl+'/userartist/remove'
	});
	var contentHeight = 400;
	var searchPanel = new aTunes.Ext.SearchPanel({
		url: _config.baseUrl+'/atunes/history',
		artist: _config.artist,
		renderTo: 'atunes-search',
		width: 240
	});
	var relPanel = new aTunes.Ext.RelateArtistPanel({
		homeUrl: _config.baseUrl+'/atunes/ext',
		url: _config.baseUrl+'/atunes/relatedartists',
		artist: _config.artist,
		renderTo: 'atunes-relatedartist',
		//title:'Related Artist',
		//iconCls:'icon-artistlist',
		border: false,
		height: 85
	});
	var playerPanel = new aTunes.Ext.YoutubePlayerPanel({
		player: player,
		id:'yt_player',
		renderTo: 'atunes-player',
		title:'Player',
		iconCls:'icon-player',
		margins: '0 5 0 5',
		width:440,
		height:contentHeight
	});
	var detailPanel = new aTunes.Ext.ArtistDetailPanel({
		url: _config.baseUrl+'/atunes/detail',
		renderTo: 'atunes-detail',
		title:_config.artist,
		//iconCls:'icon-detail',
		autoScroll:true,
		height:contentHeight
	});
	var releasePanel = new aTunes.Ext.NewReleasePanel({
		url: _config.baseUrl+'/atunes/newrelease',
		artist: _config.artist,
		renderTo: 'atunes-newrelease',
		title:'New Release',
		//iconCls:'icon-release',
		width:230,
		margins: '0 5 0 5',
		autoScroll:true,
		height:contentHeight
	});
	var videolistPanel = new aTunes.Ext.VideoListPanel({
		player: player,
		renderTo: 'atunes-videolist',
		//title:'VideoList',
		//iconCls:'icon-videolist',
		url: _config.baseUrl+'/atunes/videolist',
		itemPerPage: 20,
		artist: _config.artist,
		border: false,
		margins: '5 5 5 5',
		height:450
	});
	
	var aritstmenus = [
		{
			text: 'ビデオリスト',
			iconCls: 'icon-podcast',
			tooltip: 'アーティストの関連動画リストのRSSを表示します',
			handler: function(){window.open(_config.baseUrl+"/atunes/videolist?artist="+_config.artist+"&fmt=rss20");},
			scope:this
		},
		{
			text: 'iTunesに登録',
			iconCls: 'icon-itunes',
			tooltip: 'RSSをiTunesに登録し、Podcastで動画をダウンロードできます',
			handler: function(){
				var url = _config.wwwBase;
				url = url.replace(/http/g,"itpc");
				url += "/atunes/videolist?artist="+_config.artist+"&fmt=rss20";
				window.open(url);
			},
			scope:this
		}
	];
	var usermenu = {};
	if (_config.isAuthenticated==1) {
		aritstmenus.unshift({
				text:'お気に入りに追加',
				iconCls: 'icon-addbookmark',
				handler: function(){
					Ext.Ajax.request({
						url: _config.baseUrl+'/userartist/add',
						params: {artist:_config.artist,fmt:'json'},
						success: function(response) {aTunes.Ext.msg(_config.artist,'お気に入りに追加しました')},
						failure:  function(response) {aTunes.Ext.msg(_config.artist,'お気に入りに追加できませんでした')},
						scope:this
					});
				},
				scope:this
		});
			usermenu = new Ext.Toolbar.MenuButton({
				text: 'ユーザメニュー',
				tooltip: 'ユーザメニューを表示します',
				iconCls: 'icon-usermenu',
				menu : {items: [
					{
						text:'お気に入り...',
						iconCls: 'icon-editbookmark',
						handler: function(){
							dlgBookmark.show();
							dlgBookmark.doLoad();
						},
						scope:this
					},
					'-',
					{
						text: 'ログアウト',
						iconCls: 'icon-logout',
						handler: function(){
							location.href = _config.baseUrl+"/user/logout";
						},
						scope:this
					}
				]}
			});
	} else {
		usermenu = new Ext.Toolbar.Button({
			text: 'ログイン',
			iconCls: 'icon-login',
			tooltip: 'ログインするとお気に入りアーティストを管理したりできます',
			handler: function(){dlgLogin.show();},
			scope:this
		});
	}
	aritstmenus.unshift(_config.artist);
	
	// toolbar
	var tb = new Ext.Toolbar({
		id: 'toolbar',
		renderTo: 'atunes-toolbar',
		items: [
			'<span id="atunes-logo">aTunes β</span>',
			'-',
			new Ext.Toolbar.MenuButton({
				text: 'アーティストメニュー',
				iconCls: 'icon-artistmenu',
				tooltip: _config.artist+'に対するメニューを表示します',
				menu : {items: aritstmenus}
			}),
			'-',
			usermenu,
			'-',
			new Ext.Toolbar.MenuButton({
				text: 'ヘルプ',
				iconCls: 'icon-help',
				menu : {items: [
					{text: '開発ブログ', iconCls:'icon-blog', handler: function(){window.open("http://blog.makotokw.com/software/xjukebox/");}}
					//{text: '不具合の報告', iconCls:'icon-bug', handler: function(){window.open("http://projects.makotokw.com/trac/arcadia/report/11");}},
					//{text: '更新履歴', iconCls:'icon-history',handler: function(){window.open(urlBase+"/help/history");}}
				]}
			}),
			'-'
		]
	});
	
	relPanel.doLoad();
	detailPanel.doLoad(_config.artist);
	releasePanel.doLoad();
	videolistPanel.doLoad(0);
	videolistPanel.on({
		'videoselected': {
			fn: function(source, data){
				player.doPlay(data);
			}
		}
	});
	player.onPlayerReady = function(videoItem, flashPlayer) {
		playerPanel.setTitle(videoItem.title);
		Ext.get('youtubeplayerpanel_content').update(flashPlayer,true);
		videolistPanel.updateSelection();
	}
	player.onPlayerRequestList = function(index) {
		videolistPanel.doLoad(index);
	}
	
	setTimeout(function(){
		Ext.get('loading').remove();
		Ext.get('loading-mask').fadeOut({remove:true});
	}, 2000);
}, null, {delay: 100}); // delay for Firefox3 in windows
