//=========================================================================================
    // Replaces all instances of the given substring.
        String.prototype.replaceAll = function( 
        strTarget, // The substring you want to replace
        strSubString // The string you want to replace in.
        ){
            var strText = this;
            var intIndexOfMatch = strText.indexOf( strTarget );
             

            // Keep looping while an instance of the target string
            // still exists in the string.
            while (intIndexOfMatch != -1){
            // Relace out the current instance.
            strText = strText.replace( strTarget, strSubString )
             

            // Get the index of any next matching substring.
            intIndexOfMatch = strText.indexOf( strTarget );
            }
             

            // Return the updated string with ALL the target strings
            // replaced out with the new substring.
            return( strText );
        }

function WMPlayer(){
	this.LOW_BITRATE=32;
	this.HI_BITRATE=103;
	this.currentBitRate = this.LOW_BITRATE;
	this.isInitiated = false;
	this.statusFlag = 0;
	this.mediaFlag = 0;	
	this.cur_media = 0;
	this.rdo_song_title = "";
	this.rdo_song_album = "";
	this.rdo_song_artist = "";
	this.rdo_song_thumbnail = "";
	this.rdo_song_company = "";
	this.rdo_song_nextsong = "";
	// Event
	this.eventStatusChange = WMPlayer_eventStatusChange;
	this.eventPlayStateChange = WMPlayer_eventPlayStateChange;
	this.eventMediaChange = WMPlayer_eventMediaChange;
	this.eventError = WMPlayer_eventError;

	// Behavior
	this.setPlayer = WMPlayer_setPlayer;
	this.statusArea = null;
	this.bitRateArea = null;
	this.debug = null;
	this.statusText ="";
	this.displayStatus = WMPlayer_displayStatus;
	this.displayBitRate = WMPlayer_displayBitRate;
	this.setStatusArea = WMPlayer_setStatusArea;
	this.setBitRateArea = WMPlayer_setBitRateArea;
	this.openPlaylistWindow  = WMPlayer_openPlaylistWindow;
	this.reset = WMPlayer_reset;
	this.redrawPlaylist = WMPlayer_redrawPlaylist;
	this.setPlaylistArea = WMPlayer_setPlaylistArea;
	this.setRadioStation = WMPlayer_setRadioStation;       //new
	
	// Control
	this.player = null;
	this.playCurrentItem = WMPlayer_playCurrentItem;
	//this.play = WMPlayer_Play;
	this.play = WMPlayer_PlayRdo;                                     //new
	//this.next = WMPlayer_Next;
	this.next = WMPlayer_Rnext;                                         //new
	this.test= getMetaDataInfo;                                            //new
	this.info= WMPlayer_MetaDataInfo;
	this.pause = WMPlayer_Pause;
	this.stop = WMPlayer_Stop;
	//this.changeBitRate = WMPlayer_changeBitRate;
	this.changeBitRate = WMPlayer_RchangeBitRate;          //new
	// Now Playing List
	this.playList = new WMPlayList("now playing");
	this.createPlayList = WMPlayer_createPlayList;
	this.addSong = WMPlayer_addSong;
	this.addSongAndPlay = WMPlayer_addSongAndPlay;
	this.isOwner = false;
}
function WMPlayer_changeBitRate(bitrate){
    	if(bitrate == 'low'  ||  bitrate == 'medium'){
		this.currentBitRate==this.LOW_BITRATE;
	} else if (bitrate == 'hight'){
		this.currentBitRate=this.HI_BITRATE;
	}
	/* var today = new Date();
	    var expires = new Date();
	    expires.setTime(today.getTime() + 1000*60*60*24*365);
	setCookie("wmplayer.bitrate",this.currentBitRate,expires);*/
	this.stop();
	this.playCurrentItem();
}
function WMPlayer_RchangeBitRate(bitrate){
    	if(bitrate == 'low'  ||  bitrate == 'medium'){
		this.currentBitRate==this.LOW_BITRATE;
	} else if (bitrate == 'hight'){
		this.currentBitRate=this.HI_BITRATE;
	}
	this.stop();
	this.play();
}
function WMPlayer_displayBitRate(){
	if(this.currentBitRate==this.LOW_BITRATE){
		this.bitRateArea.innerHTML = "<img src='http://www.truelife.com/images/mini/player/sp1.gif' alt='Change to hi speed' width='64' height='12'/>";
	}else{
		this.bitRateArea.innerHTML = "<img src='http://www.truelife.com/images/mini/player/sp2.gif'  alt='Change to low speed' width='64' height='12'/>";
	}
}
function WMPlayer_setBitRateArea(obj){
	//this.statusText ="Truelife Music";
	this.bitRateArea = obj;
	var bitrate = getCookie("wmplayer.bitrate");
	if(bitrate!=null){
		this.currentBitRate = bitrate;
	}
	//alert(bitrate);
	this.displayBitRate();
}
function WMPlayer_setPlaylistArea(div_obj,owner){
	this.isOwner=owner;
	this.playListArea = div_obj;
	this.redrawPlaylist();
}
function WMPlayer_redrawPlaylist(){
	var playList = this.playList.getMediaList();//alert("redrawPlaylist<==>item =>"+playList.length);
	if(this.playListArea){
		this.playListArea.innerHTML ="";
		for(i=0;i<playList.length;i++){
			if(this.isOwner){
				this.playListArea.innerHTML += "<a href='javascript:wmPlayer.play(" + i + ")' class='music_playlist'>" +  playList[i].getName() + "</a>";
			}else{
				this.playListArea.innerHTML += "<a href='javascript:alert(\"Only owner can do\");' class='music_playlist'>" +  playList[i].getName() + "</a>";
			}
		}	
		if(playList.length<=0){
			this.playListArea.innerHTML = "<div class='float_system_message'>No song available</div>";
		}
		//this.playListArea.style.height = playList.length * 12;
	}
}
function WMPlayer_createPlayList(name){
	return new WMPlayList(name);
}

function WMPlayer_reset(){
	//this.stop;
	//this.player.controls.currentItem = null;
	//this.playList.clear();
}

function WMPlayer_setStatusArea(div_obj){
	//this.statusText ="Truelife Music";
	this.statusArea = div_obj;
	this.displayStatus();
}

function WMPlayer_openPlaylistWindow(){
	window.open("mediaplayer/playlist.html","WMPlayList","width=300,height=300");
}

function WMPlayer_displayStatus(){
	try{
		if(this.statusArea){
			if(this.statusText== ""){
				this.statusArea.innerHTML = "<a href='http://itemmall.truelife.com/music' target='_blank'>TrueLife Music</a>";
			}else{
				this.statusArea.innerHTML = this.statusText;
			}
		}
		if(this.debug){
			this.debug.innerHTML += this.statusText + "<br/>";
		}
	}catch(e){
		//alert(e);
	}
}

function WMPlayer_eventMediaChange(item){
	//alert('eventMediaChange');
//	if(this.statusFlag==0){
//		if(this.playList.currentItem()){
//		this.statusText = "<marquee class='music_player_status_text'>" + this.playList.currentItem().getName() + "</marquee>" ;
//		}else{
//			this.statusText = "" ;
//		}
//	}
//	this.displayStatus();
//	this.statusFlag=1;
}

function WMPlayer_eventError(media){
	//alert('eventError');
//	var errItem
//	if(media){
//		errItem = media.error;
//	}else{
//		// Store the most recent error item number.
//		var max = this.player.error.errorCount - 1 
//
//		// Store the most recent error in an error item object.
//		errItem = this.player.error.item(max);
//	}
//	// Use the error item object to store the error info.
//	if(errItem){
//		errDesc = errItem.errorDescription;
//		errNum = errItem.errorCode;
//	}else{
//		errDesc = "Unknown Error";
//		errNum = "Unknown";
//	}
//
//	// Display the error info.
//	this.statusText= "Error <a href='javascript:alert(\""+escape(errDesc)+"\")'>" + errNum +"</a>";
//
//	this.displayStatus();
//	this.statusFlag=-1;
}

function WMPlayer_eventStatusChange(){
	//alert('eventStatusChange');
//	if(this.statusFlag>=0){
//		this.displayStatus();
//	}
//	this.statusFlag=0;
}

function WMPlayer_eventPlayStateChange(newState,event){
	//alert('eventPlayStateChange : '+newState);
			switch (newState){
				case 1:
					this.statusText = "Stopped";
					break;
				case 2:
					this.statusText = "Paused";
					break;
				case 3:
					this.statusText = "Playing";
					break;
				case 4:
					this.statusText = "ScanForward";
					break;
				case 5:
					this.statusText = "ScanReverse";
					break;
				case 6:
					this.statusText = "Buffering";
					break;
				case 7:
					this.statusText = "Waiting";
					break;
				case 8:
					this.statusText = "MediaEnded";
					//this.mediaFlag = window.setInterval("wmPlayer.next()",2000);
					break;
				case 9:
					this.statusText = "Transitioning";
					break;
				case 10:
					//this.statusText = "Ready";
					break;
				case 11:
					this.statusText = "Recinnecting";
					break;
				default:
					this.statusText = "STATUS NO."+newState;
			}
			this.statusText =this.statusText
			this.displayStatus();
			this.statusFlag=1;
			
			if ( newState == 3){
				this.info();	
				this.statusText = "<marquee class='music_player_status_text'>" + this.rdo_song_title+ "-"+this.rdo_song_artist+"</marquee>" ;
				this.displayStatus();
				this.statusFlag=1;
				
				//alert('rdo:hi1');
				/*ads web stat*/
				 if (control_music.document.getElementById('web_stat_bgmusic')){				 	
				 	//alert('rdo:hi2');
				 	var web_stat = control_music.document.getElementById('web_stat_bgmusic');
				 	 web_stat.src = "http://minihome.truelife.com/home/ads/webstat/minihome_BG/BG";
				 }
			}
			
}


function WMPlayer_addSong(id,url,author,title,duration){
	this.playList.appendItem(new WMMedia(id,url,author,title,duration));
}

function WMPlayer_addSongAndPlay(id,url,author,title,duration){
	var index = this.playList.appendItem(new WMMedia(id,url,author,title,duration));
	this.play(index);
}

function WMPlayer_setPlayer(player){
	this.player = player;
	this.isInitiated = true;
}

function WMPlayer_playCurrentItem(){
	if(this.playList.count>0){
				
		url = "";
		guid = this.playList.currentItem().id;
		data = "";
		var self = this;

		url = 'http://twsvc.truelife.com/StreamingPlaylistService/StreamManager.aspx?streamtype=singlecontent&scope=music&contentgroup=music&streamguid='+ guid +'&wmcontentbitrate=64000&referer=trueworld&channel=jukebox';
		
		self.player.URL = url;

		self.player.controls.play();

	}
}

function WMPlayer_Play(index){
	if(this.player.controls){		
		if(!isNaN(index)){
			this.playList.setCurrentItem(index);
			this.playCurrentItem();
		}else{
			if(this.player.controls.currentItem){
				this.player.controls.play();
			}else{
				this.playCurrentItem();
			}
		}
	}
}

function WMPlayer_Next(){
		
		url = "";
		guid =this.playList.nextItem().id;
		data = "";
		var self = this;

		url = 'http://twsvc.truelife.com/StreamingPlaylistService/StreamManager.aspx?streamtype=singlecontent&scope=music&contentgroup=music&streamguid='+ guid +'&wmcontentbitrate=64000&referer=trueworld&channel=jukebox';
		self.player.URL = url;
		self.player.controls.play();

		if(this.mediaFlag>0){
			window.clearInterval(this.mediaFlag);
			this.mediaFlag=0;
		}
}

function WMPlayer_Pause(){
	if (this.player.controls.isAvailable('Pause'))
		this.player.controls.pause();
	else{
		//alert("pause not support");
	}
}

function WMPlayer_Stop(){
	this.player.controls.stop();
}


//=========================================================================================
function WMPlayList(name){
	this.name = name;
	this.head = null;
	this.tail = null;
	this.count = 0;
	this.appendItem  = WMPlayList_appendItem;
	this.clear = WMPlayList_clear;
	this.item  = WMPlayList_item;
	this.moveItem =WMPlayList_moveItem;
	this.removeItem  = WMPlayList_removeItem ;
	this.getMediaList = WMPlayList_getMediaList;
	this.insertItem = WMPlayList_insertItem;
	this.addSong = WMPlayList_addSong;

	this.curItem = null;
	this.currentItem = WMPlayList_currentItem;
	this.setCurrentItem = WMPlayList_setCurrentItem;
	this.nextItem = WMPlayList_nextItem;
}


function WMPlayList_addSong(id,url,author,title,duration){
	this.appendItem(new WMMedia(id,url,author,title,duration));
}

function WMPlayList_currentItem(){
	if(this.curItem==null){
		this.curItem = this.head;
	}
	if(this.curItem==null){
		return null;
	}else{
		return this.curItem.media;
	}
}

function WMPlayList_nextItem(){
	if(this.curItem!=null){
		this.curItem = this.curItem.next;
	}
	if(this.curItem==null){
		this.curItem = this.head;	
	}
	return this.curItem.media;
}

function WMPlayList_moveItem(oldIndex, newIndex){
		var media = this.item(oldIndex);
		this.removeItem(oldIndex);
		this.insertItem(newIndex,media);
}

function WMPlayList_insertItem(index,media){
	if(index < 0){
		throw "Error";
	}
	var i = 0;
	var item = this.head;
	var newItem = new WMListItem(media);
	var lastItem = null;
	if(index>=this.count){
		this.appendItem(media);
	}else{
		while(i <=this.count){
			if(i==index){
				if(lastItem==null){
					this.head = newItem;
				}else{
					lastItem.next = newItem;
				}
				newItem.next = item;
				break;
			}
			lastItem = item;
			item = item.next;
			i++;
		}
		this.count++;
	}
}

function WMPlayList_setCurrentItem(index){
	var item = this.item(index,true);
	this.curItem = item;
}

function WMPlayList_item(index,internal){
	if(index>=0 && index<this.count){
		var item = this.head;
		var i=0;
		while(item!=null){
			if(i++ == index){
				if(internal){
					return item;
				}else{
					return item.media;
				}
			}
			item = item.next;
		}
	}
	throw "index out of bound";	
}

function WMPlayList_appendItem(media){
	var item = new WMListItem(media);
	var curItem;
	var lastItem;
	if(this.head==null){
		this.head = item;
	}else{
		this.tail.next = item;
	}
	this.tail = item;
	//this.count++;
	return this.count++;
}

function WMPlayList_clear(){
	var curItem = this.head;
	while(curItem !=null){
		prevItem = curItem;
		curItem = curItem.next;
		prevItem.clear();
	}
	this.head = null;
	this.count=0;
}

function WMPlayList_removeItem(index){
	if(this.count<=0){
		throw "Error";
	}
	var i = 0;
	var item = this.head;
	var lastItem = null;
	while(item !=null){
		if(i==index){
			if(lastItem==null){
				this.head = item.next;
			}else{
				lastItem.next = item.next;
				if(index==this.count-1){
					this.tail = lastItem;
				}
			}
			item.clear();
			break;
		}
		lastItem = item;
		item = item.next;
		i++;
	}

	this.count--;
}

function WMPlayList_getMediaList(){
	var list = new Array();
	var curItem = this.head;
	var i = 0;
	while(curItem !=null){
		list[i++] = curItem.media;
		curItem = curItem.next;
	}
	return list;
}
//=========================================================================================

function WMListItem(media){
	this.next = null;
	this.media = media;
	this.clear = function(){
		this.media = null;
		this.next = null;
	}
}

//=========================================================================================
function WMMedia(id,url,author,title,duration){
	this.id = (id)?id:null;
	this.url = url;
	this.author = (author)?author:"unknown";
	this.title = (title)?title:"unknown";
	this.duration = (duration)?duration:"??:??";
	//this.media = wmPlayer.player.newMedia(url);
	this.getName = WMMedia_getName;
}

function  WMMedia_getName(){
		return this.author + " - " + this.title;
}

//=========================================================================================
function  WMPlayer_setRadioStation(id){
	var self = this;
	var url = "";
	
	if (id) 
	{		
		this.player.controls.stop();
		//url = 'http://twsvc.trueworld.net/StreamingPlaylistService/streammanager.aspx?streamtype=playlist&scope=music&contentgroup=music&streamguid='+id+'&referer=musichome&channel=basicplayer';		
		url = 'http://twsvc.truelife.com/StreamingPlaylistService/streammanager.aspx?streamtype=playlist&scope=music&contentgroup=music&streamguid='+id+'&wmcontentbitrate=220000&referer=truelife&channel=basicplayer&ext=py_tl_nr&clientip=';
		self.player.URL = url;
		self.player.controls.play();
	}

}
function WMPlayer_Rnext(){
	if (this.player.controls.isAvailable('Next'))
	     this.player.controls.next();	
}
function WMPlayer_PlayRdo(){
	this.player.controls.play();
}
function WMPlayer_MetaDataInfo(){
	var metaData = null;
	try{	
		var asxTitleJsonEncoded = this.player.currentmedia.getiteminfo("asxTitle");		
		var asxTitleJson = asxTitleJsonEncoded.replaceAll("&quot;", "\"");
		//alert(asxTitleJson);
	           metaData = eval('(' + asxTitleJson + ')');
	   } catch (e){
		//alert(e);
	    }
	if ( metaData != null) 
	{				
		var title = metaData.title;
		var album = metaData.album;
		var artist = metaData.artist;
		var thumbnail = metaData.albumImageURL;
		var company = metaData.CP;
		var nextsong = metaData.nextContentTitle;
		
		if( this.cur_media == 1){
			if (content.document.getElementById('label_song_name')) {
				content.document.getElementById('label_song_name').innerHTML = title;
			}			
			if (content.document.getElementById('label_album')) {
				content.document.getElementById('label_album').innerHTML = album;
			}
			if (content.document.getElementById('label_artist')) {
				content.document.getElementById('label_artist').innerHTML = artist;
			}	
			if (content.document.getElementById('rdo_thumbnail')) {
				content.document.getElementById('rdo_thumbnail').innerHTML = "<img src='"+thumbnail+"' width='70' height='70' />";
			}
			if (content.document.getElementById('label_CP')) {
				content.document.getElementById('label_CP').innerHTML = company;
			}	
			if (content.document.getElementById('label_next_song')) {
				content.document.getElementById('label_next_song').innerHTML = nextsong;
			}				
		} else if ( this.cur_media == 2){
			if (content.document.getElementById('label_song_name2')) {
				content.document.getElementById('label_song_name2').innerHTML = title;
			}			
			if (content.document.getElementById('label_album2')) {
				content.document.getElementById('label_album2').innerHTML = album;
			}
			if (content.document.getElementById('label_artist2')) {
				content.document.getElementById('label_artist2').innerHTML = artist;
			}	
			if (content.document.getElementById('rdo_thumbnail2')) {
				content.document.getElementById('rdo_thumbnail2').innerHTML = "<img src='"+thumbnail+"' width='70' height='70' />";
			}
			if (content.document.getElementById('label_CP2')) {
				content.document.getElementById('label_CP2').innerHTML = company;
			}	
			if (content.document.getElementById('label_next_song2')) {
				content.document.getElementById('label_next_song2').innerHTML = nextsong;
			}				
		}
		
		this.rdo_song_title = title;
		this.rdo_song_album = album;
		this.rdo_song_artist = artist;
		this.rdo_song_thumbnail = thumbnail;
		this.rdo_song_company = company;
		this.rdo_song_nextsong = nextsong;		
	}		
}
function getMetaDataInfo(){
	var metaData = null;
	try{	
		var asxTitleJsonEncoded = this.player.currentmedia.getiteminfo("asxTitle");		
		var asxTitleJson = asxTitleJsonEncoded.replaceAll("&quot;", "\"");
		alert(asxTitleJson);
	   } catch (e){
		//alert(e);
	    }	
	
}

//=========================================================================================//

var rdoPlayer = new WMPlayer();



