﻿/**
 * myspace music player v4.0
 * myspace 播放音乐播放器
 * ibio-develop
 * 2010-1-15 16:19
 */
var MyspaceMusicPlayer = function(aoConf){
	//static propertys
	//MyspaceMusicPlayer.BAND_PROFILE = "bandProfile";
	//protected propertys
	this.TYPE = "type";
	this.NAME = "name";
	this.BAND_ID = "bandID";
	this.SONG_ID = "songID";
	this.LOCATION = "location";
	this.UPDATE_INTERVAL = 100;
	this.musicCore = null;
	this.onUpdateCallBack = null;
	//0:stop 1:load 2:play 3:pause
	this.currentState = 0;
	this.currentNode = null;
	this.currentIndex = 0;
	this.items = null;
	this.hTimeUpdate = 0;
	
	//util methods
	MyspaceMusicPlayer.addEvent = function(aeTag, asEvt, afHandler){
		if (!aeTag) {
			return false;
		}
		if (navigator.userAgent.indexOf("IE") != -1) {
			aeTag.attachEvent("on" + asEvt, afHandler);
		} else {
			aeTag.addEventListener(asEvt, afHandler, false);
		}
	}
	
	MyspaceMusicPlayer.byClass = function(asClass, aeP, asTag){
		var lxNew = [];
		asClass = asClass == null ? "" : asClass;
		aeP = aeP == null ? document : aeP;
		asTag = asTag == null ? "*" : asTag;
		var lxTag = aeP.getElementsByTagName(asTag);
		for (var i = 0; i < lxTag.length; i++) {
			if ((" " + lxTag[i].className + " ").indexOf(" " + asClass + " ") != -1) {
				lxNew.push(lxTag[i]);
			}
		}
		return lxNew;
	}
};
MyspaceMusicPlayer.prototype = {
	/**
	 * 初始化
	 * @param	musicCore<MusicPlayerCore>：	当前播放音乐核心类
	 * @param	onUpdateCallBack<Function>：	数据更新回调函数，有 3 个形参
	 * position:		当前播放的毫秒数
	 * totalTimes:		当前音乐总时长（毫秒）
	 * loadProgress:	当前加载进度（0-1）
	 * @param	playListWrapper<String>：		播放列表节点 的 id
	 * @param	playListClass<String>：			播放列表节点中需要 render 的 class name
	 * @param	playListNode<String>：			播放列表节点中需要 render 的 node name
	 */
	init:function(musicCore, onUpdateCallBack, playListWrapper, playListClass, playListNode){
		this.musicCore = musicCore;
		this.onUpdateCallBack = onUpdateCallBack;
		if(playListWrapper){
			var wrapper = document.getElementById(playListWrapper);
			//要获取要添加 click 事件的 playList 的 items
			this.items = MyspaceMusicPlayer.byClass(playListClass, wrapper, playListNode);
		}
		//render
		if(this.items && (this.items.length > 0)){
			//这里帧听 render 的 ckick 事件
			for(var i = 0; i < this.items.length; i++){
				//这里用闭包结构将每一个 handle 保存下来
				MyspaceMusicPlayer.addEvent(this.items[i], "click", this.onItemClickHandler(this.items[i]));
			}
		}
		//更新当前时间
		this.onTimeUpdate(this.UPDATE_INTERVAL);
	},
	
	/**
	 * 播放或者暂停
	 * @param	nodeOrIndex<domNode/String>：	要操作的节点或者 index
	 */
	onPlayPause:function(nodeOrIndex){
		var targetNode = nodeOrIndex;
		//如果是 index，则找到当前的 node
		if(typeof(nodeOrIndex) == "number"){
			targetNode = this.items ? this.items[this.currentIndex] : null;
		}
		//如果当前是第一次点击，则首次加载并播放歌曲
		if(!this.currentNode){
			if(targetNode && this.musicCore){
				//更新当前 node
				this.currentNode = targetNode;
				this.musicCore.load({type:targetNode.getAttribute(this.TYPE), name:targetNode.getAttribute(this.NAME), bandID:targetNode.getAttribute(this.BAND_ID), 
									 songID:targetNode.getAttribute(this.SONG_ID), location:targetNode.getAttribute(this.LOCATION)}, true);
			}
		//如果当前点击的和之前点击的一样
		//注意：这里因为之前的 if 分支已经判断过 this.currentNode 不为空，
		//所以这里 this.currentNode 恒不为空
		}else if(this.currentNode == targetNode){
			//不响应加载状态
			if(this.musicCore && (this.currentState != 1)){
				//如果当前是播放状态，则暂停
				if (this.currentState == 2){
					this.musicCore.pause();
				}else{
					this.musicCore.play();
				}
			}
		//如果当前点击的和之前不一样
		}else{
			//先关闭之前的
			if(this.musicCore){
				this.musicCore.stop();
			}
			if(targetNode && this.musicCore){
				//更新当前 node
				this.currentNode = targetNode;
				this.musicCore.load({type:targetNode.getAttribute(this.TYPE), name:targetNode.getAttribute(this.NAME), bandID:targetNode.getAttribute(this.BAND_ID), 
									 songID:targetNode.getAttribute(this.SONG_ID), location:targetNode.getAttribute(this.LOCATION)}, true);
				
			}
		}
	},
	
	/**
	 * FLASH 当前状态的回调
	 * @param	flag<uint>：0:stop 1:load 2:play 3:pause 4:prev 5:next 6:init 7:playPause(skin)
	 */
	onStateChange:function(flag){
		//alert("FLASH 状态 " + flag);
		switch(flag){
			case 0:
				this.currentState = 0;
				break;
			case 1:
				this.currentState = 1;
				break;
			case 2:
				this.currentState = 2;
				break;
			case 3:
				this.currentState = 3;
				break;
			case 4:
				this.onPlayChange(0);
				break;
			case 5:
				this.onPlayChange(1);
				break;
		}
	},
	
	/**
	 * 上一首/下一首
	 * @param	flag<uint>：0 上一首；1 下一首
	 */
	onPlayChange:function(flag){
		//alert("FLASH 播放状态操作 " + flag);
		var totalIndices = (this.items && (this.items.length > 0)) ? this.items.length : 0;
		if(flag == 0){
			this.currentIndex--;
		}else if(flag == 1){
			this.currentIndex++;
		}
		if(this.currentIndex < 0){
			this.currentIndex = totalIndices - 1;
		}
		if(this.currentIndex >= totalIndices){
			this.currentIndex = 0;
		}
		//TODO 可以在这里控制是否自动播放下一曲
		this.onPlayPause(this.currentIndex);
	},
	
	//==================== protected methods ====================
	onTimeUpdate:function(interval){
		var self = this;
		clearTimeout(this.hTimeUpdate);
		if(this.onUpdateCallBack && this.musicCore){
			var position = musicCore.getPosition();
			var totalTimes = musicCore.getTotalTimes();
			var loadProgress = musicCore.getLoadProgress();
			this.onUpdateCallBack(position, totalTimes, loadProgress);
			//
			this.hTimeUpdate = setTimeout(function(){self.onTimeUpdate();}, interval, interval);
		}
	},
	
	onItemClickHandler:function(target){
		var self = this;
		return function(){
			//alert(target);
			self.onPlayPause(target);
		}
	}
}
/***********************************************************************************************/
/**
 * myspace music player core
 * 播放音乐核心类
 * ibio-develop
 * 2010-1-11 10:42
 */
var MusicPlayerCore = function(aoConf){
	//protected propertys
	this.playerSWF = null;
	this.debug = false;
};
MusicPlayerCore.prototype = {
	//初始化
	init:function(swfURL, container, width, height, bgColor, params, debug){
		//因为这里是 boolean，所以判空要注意
		if(debug != undefined){
			this.debug = debug;
		}
		//创建 swf
		if(container){
			this.playerSWF = this.createSWF(swfURL, container, width, height, bgColor, params);
		}
	},
	
	/**
	 * 加载音乐
	 * @param	indexOrTrack<uint/Ojbect/String>：	当前要播放的音乐标识
	 * @param	autoPlay<Boolean>：					是否自动播放
	 * @usage
	 * indexOrTrack 为 uint：预留，指是当前播放的 index
	 * indexOrTrack 为 string：预留，指的要播放的 id
	 * indexOrTrack 为 object：指加载要播放 track(type, name, bandID, songID, location)
	 */
	load:function (indexOrTrack, autoPlay){
		try{
			this.playerSWF.loadMusic(indexOrTrack, autoPlay);
		}catch(e){
			this.trace("MusicPlayerCore::load->" + e);
		}
	},
	
	play:function (position){
		if(position == undefined){
			position = -1;
		}
		try{
			this.playerSWF.playMusic(position);
		}catch(e){
			this.trace("MusicPlayerCore::play->" + e);
		}
	},
	
	pause:function (){
		try{
			this.playerSWF.pauseMusic();
		}catch(e){
			this.trace("MusicPlayerCore::pause->" + e);
		}
	},
	
	stop:function (){
		try{
			this.playerSWF.stopMusic();
		}catch(e){
			this.trace("MusicPlayerCore::stop->" + e);
		}
	},
	
	/**
	 * @return<uint>：当前播放的毫秒数
	 */
	getPosition:function (){
		var p;
		try{
			p = this.playerSWF.getPosition();
		}catch(e){
			this.trace("MusicPlayerCore::getPosition->" + e);
		}
		return p;
	},
	
	/**
	 * @return<uint>：当前音乐总时长（毫秒）
	 */
	getTotalTimes:function (){
		var t;
		try{
			t = this.playerSWF.getTotalTimes();
		}catch(e){
			this.trace("MusicPlayerCore::getTotalTimes->" + e);
		}
		return t;
	},
	
	/**
	 * @return<Number>：当前加载进度（0-1）
	 */
	getLoadProgress:function (){
		var p;
		try{
			p = this.playerSWF.getLoadProgress();
		}catch(e){
			this.trace("MusicPlayerCore::getLoadProgress->" + e);
		}
		return p;
	},
	
	//==================== protected methods ====================
	//当 JS 准备好以后，返回 true
	isReady:function(){
		//this.trace("AS 和 JS 已经准备完毕！");
		return true;
	},
	
	createSWF:function (swfURL, domID, width, height, bgColor, params){
		var swfDomID = domID + "_SWF";
		var so = new SWFObject(swfURL, swfDomID, width, height, "9.0.0", bgColor);
		so.addParam("allowNetworking", "all");
		so.addParam("allowScriptAccess", "always");
		so.addParam("wmode", "transparent");
		for(var str in params) {
			if(str && params[str]){
				so.addVariable(str, params[str]);
			}
		}
		//
		so.write(domID);
		return this.getSWF(swfDomID);
	},
	
	getSWF:function (asName) {
		if(navigator.userAgent.indexOf("IE") > -1) {
			return window[asName];
		}else{
			return document[asName];
		}
	},
	
	trace:function (str){
		if(this.debug){
			alert(str);
		}
	}
}
/***********************************************************************************************/
///
/// @ Windows Media Player Control Model
///
var WindowsMedia;
function initWindowsMediaPlayer(){
	WindowsMedia = new Object();
	WindowsMedia.control = new Object();
	//Windows Media Player
	if(document.getElementById("MediaPlayerObject")){
		WindowsMedia.player = document.getElementById("MediaPlayerObject"); 
	}else{
		WindowsMedia.player = new Object();
	}
	//
	WindowsMedia.control.setURL = function(value){
		WindowsMedia.player.URL = value;
	};
	WindowsMedia.control.clear = function(){
		//TODO: clear all media reference.
	};
	WindowsMedia.control.play = function(){
		if(WindowsMedia.player.controls && WindowsMedia.player.controls.isAvailable('Play')){
			WindowsMedia.player.controls.play();
		}
	};
	WindowsMedia.control.stop = function(){
		if(WindowsMedia.player.controls && WindowsMedia.player.controls.isAvailable('Stop')){
			WindowsMedia.player.controls.stop();
		}
	};
	WindowsMedia.control.pause = function(){
		if(WindowsMedia.player.controls && WindowsMedia.player.controls.isAvailable('Pause')){
			WindowsMedia.player.controls.pause();
		}
	};
	//返回当前播放进度(秒)
	WindowsMedia.control.getCurrentPosition = function(){
		var p;
		if(WindowsMedia.player.controls){
			p = WindowsMedia.player.controls.currentPosition;
		}
		return p;
	};
	//设置当前播放进度(秒)
	WindowsMedia.control.setCurrentPosition = function(value){
		if (WindowsMedia.player.controls && (!isNaN(value)) && (value != '')){
			WindowsMedia.player.controls.currentPosition = value;
		}
	};
	//0-100
	WindowsMedia.control.getVolume = function(){
		var v;
		if(WindowsMedia.player.settings){
			v = WindowsMedia.player.settings.volume;
		}
		return v;
	};
	//0-100
	WindowsMedia.control.setVolume = function(value){
		if (WindowsMedia.player.settings && (!isNaN(value)) && (value != '')){
			WindowsMedia.player.settings.volume = value;
		}
	};
	//Boolean
	WindowsMedia.control.mute = function(value){
		if(WindowsMedia.player.settings){
			WindowsMedia.player.settings.mute = value;
		}
	};
	//总时长(秒)
	WindowsMedia.control.getDuration = function(){
		var d;
		if(WindowsMedia.player.currentMedia){
			d = WindowsMedia.player.currentMedia.duration;
		}
		return d;
	};
	//当前加载百分比(0-100)
	WindowsMedia.control.getDownloadProgress = function(){
		var p;
		if(WindowsMedia.player.network){
			p = WindowsMedia.player.network.downloadProgress;
		}
		return p;
	};
}