// create namespace
Ext.namespace('libgt');
Ext.namespace('libgt.renderer');

libgt.renderer.PageStackGridRenderer = {
	render: function(el,response,updateManager,callback) {
		var html = response.responseText;
		if(typeof html == "undefined"){
            html = "";
        }
        var hd = document.getElementsByTagName("head")[0];
        var re = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig;
        var srcRe = /\ssrc=([\'\"])(.*?)\1/i;
        var typeRe = /\stype=([\'\"])(.*?)\1/i;

        var match;
        while(match = re.exec(html)){
            var attrs = match[1];
            var srcMatch = attrs ? attrs.match(srcRe) : false;
            if(srcMatch && srcMatch[2]){
               var s = document.createElement("script");
               s.src = srcMatch[2];
               var typeMatch = attrs.match(typeRe);
               if(typeMatch && typeMatch[2]){
                   s.type = typeMatch[2];
               }
               hd.appendChild(s);
            }else if(match[2] && match[2].length > 0){
                if(window.execScript) {
                   window.execScript(match[2]);
                } else {
                   window.eval(match[2]);
                }
            }
        }
        if(typeof callback == "function"){
            callback();
        }
	}
};

libgt.PageStack = function(config) {

//	var coreDivId = div;
//	var sPointer = 0;

	this.mainPanel = config.mainPanel;
//	this.gridPanel = config.gridPanel;
};

libgt.PageStack.prototype = {
	load: function(config) {
		var type = config.pageType;
		var pagePath = config.pagePath;
		var gridPath = config.gridPath;
		if (type == 'p') {
			this.loadPage(pagePath, config.pushStack);
		} else if (type == 'g') {
			this.loadGrid(gridPath, config.pushStack);
		} else if (type == 'h') {
			this.loadHybrid(pagePath,gridPath, config.pushStack);
		}
	},
	loadPage: function(aUrl,pushStack) {
		
		if(isDemoApp==true){
			if (aUrl && aUrl.indexOf('/news/detail?') > 0) {
				showDemoSubAlert();
				return;
			}			
		}
		
		
		
		var token = 'p' + ',' + aUrl + ',' + '';
		if (pushStack == undefined && Ext.History.getToken() != token) {
			Ext.History.add(token);
		} else {
			//
			showOrHideLyricByUrl(aUrl);
			this.beforePageLoad();
			var panel = this.mainPanel.getComponent('pagePanel');
			panel.load({
				url: aUrl,
				scope: this,
				scripts: true,
				text:'Loading',
				callback: function() {
					this.mainPanel.getLayout().setActiveItem('pagePanel');
					this.afterPageLoad();
				}
			});
		}
	},
	loadGrid: function(aUrl,pushStack) {
		var token = 'g' + ',' + '' + ',' + aUrl;
		if (pushStack == undefined && Ext.History.getToken() != token) {
			Ext.History.add(token);
		} else {
			showOrHideLyricByUrl(aUrl);			
			this.beforePageLoad();
			var panel = this.mainPanel.getComponent('gridPanel');
			// reset grid
			if (panel.getStore().recordType) panel.getStore().loadData([],false);
	//		panel.getStore().url
			panel.load({
				url:aUrl,
				scope: this,
				scripts:true,
				callback: function() {
					this.mainPanel.getLayout().setActiveItem('gridPanel');
					this.afterPageLoad();
				}
			});
		}
	},
	loadHybrid: function(pageUrl,gridDataUrl, pushStack) {
		if(isDemoApp){
			if ((pageUrl!=null && pageUrl.indexOf('/video/detail?') > 0) 
				|| (gridDataUrl!=null && gridDataUrl.indexOf('/video/artistVideo?') > 0)) {
				showDemoSubAlert();
				return;
			}			
		}
		
		
		
		var token = 'h' + ',' + pageUrl + ',' + gridDataUrl;
		if (pushStack == undefined && Ext.History.getToken() != token) {
			Ext.History.add(token);
		} else {
			if (pageUrl && pageUrl != ''
				&& gridDataUrl && gridDataUrl != '') {
				this.beforePageLoad();
			}
			if (pageUrl && pageUrl != '') {
				showOrHideLyricByUrl(pageUrl,false);				
				var pagePanel = this.mainPanel.getComponent('hybridPanel').getComponent('hybridPagePanel');
				pagePanel.load({
					url: pageUrl,
					scripts: true,
					scope: this
				});
			}
			if (gridDataUrl && gridDataUrl != '') {
				showOrHideLyricByUrl(gridDataUrl,false);			
				var gridPanel = this.mainPanel.getComponent('hybridPanel').getComponent('hybridGridPanel');				
				gridPanel.load({
					url:gridDataUrl,
					scripts:true,
					scope: this,
					callback: function() {					
						this.mainPanel.getLayout().setActiveItem('hybridPanel');
						//ie not this code will hide the hybridGridPanel
						var mysize=this.mainPanel.getComponent('hybridPanel').getComponent('hybridGridPanel').getSize();
						this.mainPanel.getComponent('hybridPanel').getComponent('hybridGridPanel').setSize(mysize.width,200);
						this.mainPanel.getComponent('hybridPanel').doLayout(true,true);
						//////
						
						this.afterPageLoad();
					}
				});
			}
		}
	},
	loadText: function(aText) {
		this.beforePageLoad();
		var panel = this.mainPanel.getComponent('pagePanel');
		panel.body.update('<div class="notice">' + aText + '</div>');
		this.mainPanel.getLayout().setActiveItem('pagePanel');
		this.afterPageLoad();
	},

	goBack: function() {
		Ext.History.back();
	},

	goForward: function() {
		Ext.History.forward();
	},
	beforePageLoad: function() {},
	afterPageLoad: function() {}
	// TODO: to be removed
	/*
	, msg: '',
	cnt: 0,
	log: function(message) {
		this.msg = '<p style="display:block;">' +(this.cnt++)+'. '+ message +'</p>'+this.msg;
		Ext.get(globalNotificationDiv).applyStyles('width:200px;height:400px;line-height:1em;margin:0;text-align:left;overflow:auto;position:absolute;right:0;top:0;').update(this.msg).show();
	}
	*/
};

// libgt.slider - a common slider effect implementation
/*
	config:
		sitems - items to be shown per page
		size - total size
		applyTo - the div's id of slider
		isBlocking - synchronize sliding action
		pageIndex - current page index (default 0)
		pageDistance - distance to be slided per page
*/

libgt.Slider = function(config) {
	this.slidingBlockFlag = false;
	this.config = config;
	this.animConfig = {
		callback: function() {
			this.slidingBlockFlag = false;
		},
		scope: this
	};

	this.pageSize = (config.sitems > 0)? Math.ceil(config.size / config.sitems) : 0;
	this.pageIndex = (config.pageIndex)? config.pageIndex : 0;

};

libgt.Slider.prototype = {
	slide: function(direction) {
		var ele = Ext.get(this.config.applyTo);
		var distance = this.config.pageDistance;
		if (!this.slidingBlockFlag) {
			if (this.config.isBlocking) {
				this.slidingBlockFlag = true;
			}
			switch (direction) {
				case 'l':
					if (this.pageIndex < this.pageSize - 1) {
						this.pageIndex++;
						ele.moveTo(ele.getX()-distance, ele.getY(), this.animConfig);
					} else {
						this.pageIndex = 0;
						ele.moveTo(ele.getX()+((this.pageSize-1)*distance), ele.getY(), this.animConfig);
					}
					break;
				case 'r':
					if (this.pageIndex > 0) {
						this.pageIndex--;
						ele.moveTo(ele.getX()+distance, ele.getY(), this.animConfig);
					} else {
						this.pageIndex = this.pageSize - 1;
						ele.moveTo(ele.getX()-((this.pageSize-1)*distance), ele.getY(), this.animConfig);
					}
					break;
				case 'u':
					if (this.pageIndex < this.pageSize - 1) {
						this.pageIndex++;
						ele.moveTo(ele.getX(), ele.getY()-distance, this.animConfig);
					} else {
						this.pageIndex = 0;
						ele.moveTo(ele.getX(), ele.getY()+ ((this.pageSize-1) * distance), this.animConfig);
					}
					break;
				case 'd':
					if (this.pageIndex > 0) {
						this.pageIndex--;
						ele.moveTo(ele.getX(), ele.getY()+distance, this.animConfig);
					} else {
						this.pageIndex = this.pageSize - 1;
						ele.moveTo(ele.getX(), ele.getY()-((this.pageSize-1) * distance), this.animConfig);
					}
					break;
			}
		}
	}
};

/*
	libgt.MediaController - a media playback controller which keep tracks user's playlist and current playing media
	configuration params:
	#onPlay - callback function for media playing
		param:onPlay
		type - media type
		mediaId - id value for the media (i.e. id)
	#onStop
	#onPause
	#onReset
	#onResume
	#mediaIdField - field name of unique identifier


*/
libgt.MediaController = function(config) {
	// constant
	this.STATUS_PLAY = 1;
	this.STATUS_PAUSE = 2;
	this.STATUS_STOP = 3;
	this.REPEAT_NONE = 1;
	this.REPEAT_ALL = 2;
	this.REPEAT_ONCE = 3;

	this.config = config;
	this.onPlay = config.onPlay;
	this.afterPlay = config.afterPlay;
	this.onStop = config.onStop;
	this.onPause = config.onPause;
	this.onReset = config.onReset;
	this.afterReset = config.afterReset;
	this.onResume = config.onResume;
	this.playlist = config.playlist; // optional
	this.shuffle = false;
	this.repeat = this.REPEAT_NONE;
	// declare playSequence
	/*
	this.playSequence = [];
	this.currentPlayIndex = 0;
	*/
	this.lastPlayStoreTypeHash = [];
};
//showLyricByMediaInfo(mediaInfo,isExpLrc,iscall);
libgt.MediaController.prototype = {
	/*
	msg: '',
	log: function(message) {
		this.msg = '<p style="display:block;">' + message +'</p>'+this.msg;
		Ext.get(globalNotificationDiv).applyStyles('width:200px;height:400px;line-height:1em;margin:0;text-align:left;overflow:auto;position:absolute;right:0;top:0;').update(this.msg).show();
	},
	*/
	play: function(config) {
		var mediaInfo;
		
		if(isDemoApp==true){
			if(checkdemoPreListen()==false){
				showDemoPreListenAlert();
				return;
			}
		}
		
		if (config) {
			if (config.store) {
				this.store = config.store;
				this.resetSequence();
				this.currentPlayIndex = 0;
			}
			if (config.index != undefined) {
				this.reset();
				this.resetSequence();
				this.currentPlayIndex = config.index;
				if (this.shuffle) {
					this.shuffleSequence(config.index);
				}
				try {
					mediaInfo = this.store.getAt(this.playSequence[this.currentPlayIndex]);
				} catch(ex) {
				}
				//alert(config.index+','+this.currentPlayIndex+','+this.playSequence[this.currentPlayIndex]);
			}
			if (config.currentPlayIndex != undefined) {
				//this.log('play(): '+this.currentPlayIndex+','+config.currentPlayIndex);

				this.currentPlayIndex = config.currentPlayIndex;
				mediaInfo = this.store.getAt(this.playSequence[this.currentPlayIndex]);
				/*
				var tmp = this.playSequence[this.currentPlayIndex]+','+this.currentPlayIndex+',[';
				for (var i = 0; i < this.playSequence.length; i++) {
					if (i != 0) tmp += ',';
					tmp += this.playSequence[i];
				}
				tmp += ']';
				this.log('play(): '+tmp);
				*/
			}
		}
		if (this.nowPlayingMediaInfo && this.nowPlayingMediaInfo.get('type') != this.config.type) {
		}
		if (!mediaInfo) {
			if (this.nowPlayingMediaInfo && this.nowPlayingMediaInfo.get('type') == this.config.type) {
				mediaInfo = this.nowPlayingMediaInfo;
				//alert("mediaInfo 00000"+this.currentPlayIndex);
			} else {
				mediaInfo = this.store.getAt(this.playSequence[this.currentPlayIndex]);
				//alert("mediaInfo reset"+this.currentPlayIndex);
			}
		}
		if (mediaInfo && this.store) {
			this.lastPlayStoreTypeHash[mediaInfo.get('type')] = this.store;
		}
		// stop now Playing
		if (this.playBackStatus == this.STATUS_PLAY) {
			try {
				if (this.nowPlayingMediaInfo != mediaInfo && this.nowPlayingMediaInfo.get('type') != mediaInfo.get('type')) {
					this.pause({'type':this.nowPlayingMediaInfo.get('type')});
				}
			} catch (e) {
				//alert(e);
			}
		}
 
		if (this.onPlay(mediaInfo)) {
			if(mediaInfo.get('type') != 'video'){
				showLyricByMediaInfo(mediaInfo,false,true);
			}
			
			
			this.playBackStatus = this.STATUS_PLAY;
			this.nowPlayingMediaInfo = mediaInfo;
			if (this.afterPlay) {this.afterPlay(mediaInfo);}
		}
	},
	pause: function(config) {
		if (this.onPause) this.onPause(config);
		this.playBackStatus = this.STATUS_PAUSE;
	},
	resume: function(config) {
		if (this.onResume) this.onResume(config);
		this.playBackStatus = this.STATUS_PLAY;
	},
	stop: function(config) {
		if (this.onStop) this.onStop(config);
		//this.log('stop(): reset');
		this.reset();
	},
	togglePlay: function() {
		switch (this.playBackStatus) {
			case this.STATUS_PAUSE:
				this.resume();
				break;
			case this.STATUS_PLAY:
				this.pause();
				break;
		}
	},
	playNext: function() {
		var plength = this.store? this.store.getCount() : 0;
		this.reset();
		if (plength <= 0) {
			//this.log('playNext(): reset plength');
			return;
		}
		if (this.repeat == this.REPEAT_ONCE) {
			//this.log('playNext(): play_once'+(this.repeat == this.REPEAT_ONCE)+','+this.currentPlayIndex);
			//this.log('repeat once[next],'+infoId+','+this.currentPlayIndex);
			this.play({'currentPlayIndex':this.currentPlayIndex});
		} else if (this.currentPlayIndex == plength-1 && this.repeat != this.REPEAT_ALL) {
			//this.log('playNext(): reset');
		} else {
			this.play({'currentPlayIndex':(this.currentPlayIndex+1)%plength});
		}
	},
	playPrev: function() {
		var plength = this.store? this.store.getCount() : 0;
		this.reset();
		if (plength <= 0) {
			//this.log('playPrev(): reset plength');
			return;
		}
		if (this.repeat == this.REPEAT_ONCE) {
			//this.log('playPrev(): play_once'+(this.repeat == this.REPEAT_ONCE)+','+this.currentPlayIndex);
			//this.log('repeat once[prev],'+infoId+','+this.currentPlayIndex);
			this.play({'currentPlayIndex':this.currentPlayIndex});
		} else if (this.currentPlayIndex == 0 && this.repeat != this.REPEAT_ALL) {
			//this.log('playPrev(): reset');
		} else {
			this.play({'currentPlayIndex':(this.currentPlayIndex+plength-1)%plength});
		}
	},
	reset: function() { // reset the controller to initial state
		//this.log('reset(): '+this.currentPlayIndex);
		try {
			if (this.onReset) this.onReset();
			this.playBackStatus = this.STATUS_STOP;
			this.nowPlayingMediaInfo = undefined;
			if (this.afterReset) this.afterReset();
		} catch (e) {
			//this.log('reset(): '+e);
		}
	},
	isPlaying: function() {
		return (this.playBackStatus == this.STATUS_PLAY);
	},
	toggleShuffle: function() {
		this.shuffle = !this.shuffle;
		// shuffle or reset playSequence
		if (this.shuffle) {
			this.shuffleSequence(this.currentPlayIndex);
		} else {
			this.currentPlayIndex = this.playSequence[this.currentPlayIndex];
			this.resetSequence();
		}
		return this.shuffle;
	},
	toggleRepeat: function() {
		switch (this.repeat) {
			case this.REPEAT_NONE:
				this.repeat = this.REPEAT_ALL;
				break;
			case this.REPEAT_ALL:
				this.repeat = this.REPEAT_ONCE;
				break;
			case this.REPEAT_ONCE:
				this.repeat = this.REPEAT_NONE;
				break;
		}
		return this.repeat;
	},
	// playSequence functions
	resetSequence: function() {
		var len = (this.store && this.store.getCount ? this.store.getCount(): 0);
		this.playSequence = new Array(len);
		for (var i = 0; i < this.playSequence.length; i++) {
			this.playSequence[i] = i;
		}
	},
	shuffleSequence: function(firstIndex) {
		this.resetSequence();
		var i = this.playSequence.length;
		if ( i == 0 ) return;
		while ( --i ) {
			var j = Math.floor( Math.random() * ( i + 1 ) );
			var tempi = this.playSequence[i];
			var tempj = this.playSequence[j];
			this.playSequence[i] = tempj;
			this.playSequence[j] = tempi;
		}
		if (firstIndex >= 0) {
			//alert('after shuffle: '+firstIndex);
			// put selected play item to first shuffle item
			for (i = 0; i < this.playSequence.length; i++) {
				if (this.playSequence[i] == firstIndex) {
					var tmp = this.playSequence[0];
					this.playSequence[0] = this.playSequence[i];
					this.playSequence[i] = tmp;
					break;
				}
			}
			this.currentPlayIndex = 0;
		}
	},
	getLastPlayStoreByType: function(type) {
		return this.lastPlayStoreTypeHash[type];
	}
};

libgt.Bookshelf = function(config) {
	var bs; // bookshelf
	var content;
	var sb; // scrollbar
	var sbt; // scrollbar-track
	try {
		bs = Ext.get(config.shelf);
		content = bs.child('.content');
		sb = bs.child('.scrollbar');
		sbt = sb.child('.scrollbar-track');
		this.bs = bs;
		this.content = content;
		this.sb = sb;
		this.sbt = sbt;
		this.itemCount = config.itemCount;
		this.itemWidth = config.itemWidth;
		this.shelfHeight = config.shelfHeight;
		this.scrollbarHeight = config.scrollbarHeight;
		this.init = config;
		this.refresh();
	} catch(ex) {
		//alert('Bookshelf: '+ex);
		return; 
	}
	var self = this;
	sb.on('click', function(e, t){
	    if((t.id == sb.id) && !e.within(t, true)){
		    var sbtX = e.getPageX()-sbt.getWidth()/2;
		    if (sbtX < sb.getX()) {
		    	sbtX = sb.getX();
		    } else if (sbtX > sb.getX()+sb.getWidth()-sbt.getWidth()) {
		    	sbtX = sb.getX()+sb.getWidth()-sbt.getWidth();
		    }
		    var contentX = -(content.getWidth()-sb.getWidth())*(sbtX-sb.getX())/(sb.getWidth()-sbt.getWidth())+sb.getX();
			self.move({
		    	sbtX: sbtX, 
		    	contentX: contentX
			});
	    } else {
	    }
	});
	var sbtDD = new Ext.dd.DD(sbt.id, '', {
		moveOnly: true, 
		scroll: false
	});
	this.sbtDD = sbtDD;
	sbtDD.setYConstraint(0, 0);
	sbtDD.constrainTo(sb);
	sbtDD.onDrag = function(e) {
		/*
        var left = -1*content.getWidth()*(sbt.getX()-sb.getX())/sb.getWidth();
	    if (left < (content.getWidth()-sb.getWidth())*-1) {
		    left = (content.getWidth()-sb.getWidth())*-1;
	    } else if (left > 0) {
		    left = 0;
	    }
	    */
        var left = -(content.getWidth()-sb.getWidth())*(sbt.getX()-sb.getX())/(sb.getWidth()-sbt.getWidth());
		content.setLeft(left);
		sbt.setTop(0);
		self.updateTrackX(sbt.getX());
	};
	sbtDD.endDrag = function(e) {
		self.updateTrackX(sbt.getX());
	};
	if (Ext.isIE6) {
		var sbR = this.bs.child('.scrollbar-bg-right');
		sbR.update('<div class="scrollbar-bg-right-fake"></div>');
	}
}
libgt.Bookshelf.prototype = {
	trackWidth: 65, 
	updateTrackX: function(newSbtX) {
		this.trackPcent = (this.sbt.getX()-this.sb.getX())/(this.sb.getWidth()-this.sbt.getWidth()); 
	}, 
	move: function(config) {
		var self = this;
		this.sbt.shift({
	    	x: config.sbtX, 
	    	callback: function() {
				self.updateTrackX(self.sbt.getX());
			}
	    });
    	this.content.shift({
        	x: config.contentX
        });
	}, 
	resize: function(config) {
		if (config.shelfHeight) {
			this.shelfHeight = config.shelfHeight;
		}
		/*
		if (config.shelfWidth && config.oldShelfWidth) {
			alert(config.oldShelfWidth+","+config.shelfWidth+","+(config.shelfWidth/config.oldShelfWidth));
			var sbtX = this.sb.getX()+this.sbt.getLeft(true)*(config.shelfWidth/config.oldShelfWidth);
			if (sbtX > this.sb.getX()+this.sb.getComputedWidth()-this.sbt.getComputedWidth()) {
				alert(sbtX);
				sbtX = this.sb.getX()+this.sb.getComputedWidth()-this.sbt.getComputedWidth();
			}
			this.sbt.setX(sbtX);
			this.sbtDD.constrainTo(this.sb);
		}
		*/
		this.refresh();
	}, 
	refresh: function(isCallback) {
		if (this.shelfHeight < 230) {
			this.shelfHeight = 230;
		}
		var self = this;
		this.trackPcent = (this.sbt.getX()-this.sb.getX())/(this.sb.getWidth()-this.sbt.getWidth()); 
		var trackPcent = this.trackPcent;
		var sbWidth = this.sb.getComputedWidth();
		this.itemWidth = this.init.itemWidth*this.shelfHeight/this.init.shelfHeight;
		this.sb.setHeight(this.scrollbarHeight);
		this.content.setHeight(this.shelfHeight-1-this.sb.getComputedHeight());
		this.bs.applyStyles("width:100%;");
		this.bs.setHeight(this.shelfHeight-1);
		this.content.setWidth(this.itemWidth*this.itemCount);
		this.content.select('.album-wrap').setWidth(this.itemWidth);
		this.content.select('.album-img').setWidth(this.itemWidth-this.trackWidth);
		this.bs.child('.content-wrap').setHeight(this.shelfHeight-this.sb.getComputedHeight());
		this.bs.child('.content-wrap').setWidth(this.sb.getComputedWidth());
		this.bs.child('.scrollbar-bg-left').setWidth(Math.round(this.sb.getComputedWidth()*0.01));
		this.bs.child('.scrollbar-bg-right').setWidth(Math.round(this.sb.getComputedWidth()*0.99));
		if (this.sbtDD) {
			this.sbtDD.clearConstraints();
			this.sbtDD.resetConstraints(false);
			this.sbtDD.constrainTo(this.sb);
		}
		if (this.trackPcent) {
			var left = -(this.content.getWidth()-this.sb.getWidth())*trackPcent;
			this.content.setLeft(left);
		}
		if (false && isCallback != true) {
			setTimeout(function() {
				self.refresh(true);
				setTimeout(function() {
					self.refresh(true);
				}, 500);
			}, 50);
		} else {
			
		}
		/*
		setTimeout(function() {
			try {
				if (bs) {
				}
			} catch(ex) {}
		}, 0);
		try {
		alert(this.bs.child('.scrollbar-bg-right').getWidth()
				+","+this.bs.child('.scrollbar-bg-left').getWidth()
				+","+this.sb.getWidth()
				+","+this.bs.child('.scrollbar-bg-right-fake').getWidth());
		} catch(e) {}
		*/
	}
};
