var	currentState; 
var	previousState;
var setFlash;
var playingVideoAudio = 0;//value to check if the player is playing video or audio
var flashText = 0;
var theWaveTime=null;
var theNumberNofWave=0;//length of wave text
var currentVolume;
var bufferFlag = true;
var player = null;
var setPlayer;
var setPlayer;
var searchDigit =0;
function playerReady(obj) {
	//alert('the videoplayer '+obj['id']+' has been instantiated');
	player = document.getElementById(obj['id']);
	addListeners();
	//allowBuffering();
}
var setClearOverlay;
function clearOverlay(){
	clearTimeout(setClearOverlay);
	document.getElementById("overlay").style.display = 'none';
}
function allowBuffering(){
	if(player){ 
		player.addModelListener('TIME', 'timeMonitor');
	}else{
		setTimeout("allowBuffering1()", 100);
	}
}
function timeMonitor(obj){//This function lets the player buffer before starting to play
	if((obj.position > 0) && (bufferFlag)){
		player.sendEvent('PLAY', 'false');
		bufferFlag = false;
		setPlayer = setTimeout("play()",3000);
	}
}
function addListeners() {
	if (player){ 
		player.addModelListener("STATE", "stateListener");
	}else{
		setTimeout("addListeners1()",100);
	}
}
function stateListener(obj) { //IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED
	currentState = obj.newstate; 
	previousState = obj.oldstate; 
	var tmp = document.getElementById("stat");
	if (tmp) { 
		tmp.innerHTML = "current state: " + currentState + 
		"<br>previous state: " + previousState; 
	}
	if ((currentState == "COMPLETED")&&(previousState == "PLAYING")){
		nextSong();
	}
	if ((currentState == "COMPLETED")&&(previousState == "PAUSED")){
		nextSong();
	}
	if ((currentState == "PAUSED")&&(previousState == "COMPLETED")){
		nextSong();
	}
	if((currentState == "PLAYING")||(currentState == "BUFFERING")){
		flashText = 1;
	}
	if ((currentState == "PAUSED")||(currentState == "COMPLETED")){
		flashText = 0;
	}
}
function loadMusic(song){
	var newSong = '18d6769919266cd0bd6cd78aa405d5d0';
	newSong += '/';
	newSong += 'e38cfb4ea686546cba31cce3320f4a82';
	newSong +=song;
	flashText = 1;
	//bufferFlag = true;//set to true allow buffering 
	player.sendEvent('STOP');
	player.sendEvent('LOAD',newSong);
	player.sendEvent('PLAY','true');
	//allowBuffering();
}
function createPlayer(theLogo, go, icons) {
	var s0 = new SWFObject('player-licensed2.swf','mediaplayer','320','240','9','#ffffff');
	s0.addParam("allowfullscreen","true");
	s0.addParam("allowscriptaccess","always");
	s0.addParam("wmode","opaque");
	s0.addVariable("usefullscreen", "false");
	//s0.addVariable("showeq", "true");
	s0.addVariable('abouttext', 'Rusumo Player');
	s0.addVariable('aboutlink', 'http://www.rusumo.com/');
	//s1.addVariable("file", theFile);
	s0.addVariable('id','mediaplayer');
	s0.addVariable("width", "300");
	s0.addVariable("height", "320");
	s0.addVariable("displayheight", "230");
	s0.addVariable("overstretch", "fit");
	s0.addVariable("shuffle", "false");
	s0.addVariable('file','http://www.youtube.com/watch?v=04bg9IC9N6w');  
	s0.addVariable("repeat", "false");
	//s0.addVariable('skin', 'modieus/modieus.swf');
	s0.addVariable('skin', 'dangdang/dangdang.swf');
	s0.addVariable("enablejs","true");
	s0.addVariable("backcolor","0x000000");
	s0.addVariable("frontcolor","0xCCCCCC");
	s0.addVariable("lightcolor","0xFFFFFF");
	s0.addVariable("logo", theLogo); 
	s0.write("playerholder"); 
	//document.getElementById("audiovideo").value="Audios";
	setFlash = setInterval("flashtext()",20);
}
function changeZindex1(){
	document.getElementById("txt").style.zIndex='1';
	document.getElementById("playerholder").style.zIndex='2';
}
function changeZindex2(){
	document.getElementById("txt").style.zIndex='2';
	document.getElementById("playerholder").style.zIndex='1';
}

function detect_browser(){
	var browser_name = navigator.userAgent.toLowerCase();
	// We have to check for Opera first because
	// at the beginning of the userAgent variable
	// Opera claims it is MSIE.	
	if (browser_name.indexOf("opera")!= -1){
		browser_name = "opera";
	}else if (browser_name.indexOf("firefox")!= -1){
		browser_name = "firefox";
	}else if (browser_name.indexOf("msie")!= -1){
		browser_name = "msie";
	}else if (browser_name.indexOf("netscape")!= -1){
		browser_name = "netscape";
	}else if (browser_name.indexOf("safari")!= -1){
		browser_name = "safari";
	}	
	return browser_name;	

} // end function detect_browser()
function closeSearch(){
	var show = document.getElementById("searchMySong").style;
	document.getElementById('searchSong').value = "";
	//document.getElementById('playlist2').value = "";//set the value for this playlist to none.
	document.getElementById('favourite').innerHTML = "";
	show.display = 'none';
}
function putCenter(){//gets the length of the  page or we can say the length of the body
	if(window.innerWidth){
		var width = document.body.clientWidth;		
	}else{
      var width=window.innerWidth;
	}
	return width;
}
function getBodyWidth(thebody){
	if(document.getElementById){
		return parseInt(document.getElementById(thebody).offsetWidth);
	}else if(document.all){
		return parseInt(document.all[thebody].offsetWidth);
	}else if(document.layers){
		return parseInt(document.layers[thebody].clip.width);
	}
} 
function getBodyHeight(layerID){
	if(document.getElementById){
		return parseInt(document.getElementById(thebody).offsetHeight);
	}else if(document.all){
		return parseInt(document.all[thebody].offsetHeight);
	}else if(document.layers){
		return parseInt(document.layers[thebody].clip.height);
	}
}
function accessCssOfLayer(id){
	if(document.getElementById){
		  return document.getElementById(id).style;
	}else if(document.all){
		  return document.all[id].style;
	}else if(document.layers){
		  return document.layers[id];
	}
} 
var cX = 0; var cY = 0; var rX = 0; var rY = 0;
var type;//tiget type of colour

function UpdateCursorPosition(e){
	cX = e.pageX; cY = e.pageY;
}
function UpdateCursorPositionDocAll(e){
	cX = event.clientX; cY = event.clientY;
}
if(document.all){
	document.onmousemove = UpdateCursorPositionDocAll;
}else{
	document.onmousemove = UpdateCursorPosition; 
}
function AssignPosition(d,mainPlayList,mediaplayer) {

	if(self.pageYOffset) {
		rX = self.pageXOffset;	rY = self.pageYOffset;
	}else if(document.documentElement && document.documentElement.scrollTop) {
		rX = document.documentElement.scrollLeft;	rY = document.documentElement.scrollTop;
	}else if(document.body){
		rX = document.body.scrollLeft;
		rY = document.body.scrollTop;
	}
	if(document.all){
		cX += rX;
		cY += rY;
	}
	d.style.left = leftMargin(mainPlayList);d.style.top = topMargin(mediaplayer);

}
function hideContent(d){
	if(d.length < 1) {
		return;
	}
	document.getElementById(d).style.display = "none";
	}
function showContent(d,mainPlayList,mediaplayer) {
	if(d.length < 1){
		return;
	}
	var dd = document.getElementById(d);
	AssignPosition(dd,mainPlayList,mediaplayer);
	if(dd.style.display == "none"){
		dd.style.display = "block"
	}else{
		dd.style.display = "none"
	}
}
function ReverseContentDisplay(d) {
	if(d.length < 1) {
		return; 
	}
	var dd = document.getElementById(d);AssignPosition(dd);if(dd.style.display == "none") {
	dd.style.display = "block";
	}else{
		dd.style.display = "none";
	}
}
function getPositionY(mediaplayer){
	var offsetTrail = document.getElementById(mediaplayer);
	var offsetTop = 0;
	while (offsetTrail!=null){
		offsetTop += offsetTrail.offsetTop;
		offsetTrail = offsetTrail.offsetParent;
	}
	if (navigator.userAgent.indexOf('Mac') != -1 && typeof document.body.leftMargin != 'undefined'){
		offsetTop += document.body.topMargin;
	}
	return offsetTop;
}
function getPositionX(mainPlayList){
	var offsetTrail = document.getElementById(mainPlayList);
	var offsetLeft = 0;
	while (offsetTrail!=null){
		offsetLeft += offsetTrail.offsetLeft;
		offsetTrail = offsetTrail.offsetParent;
	}
	if (navigator.userAgent.indexOf('Mac') != -1 && typeof document.body.leftMargin != 'undefined'){
		offsetLeft += document.body.leftMargin;
	}
	return offsetLeft;
}
function topMargin(mediaplayer){
	//return eval((screen.height - getBodyHeight("thecalenderTable"))/2+(0.2*screen.height))+"px";
	return eval(getPositionY(mediaplayer))+"px";
}
function leftMargin(mainPlayList){
	//return eval((screen.width - getBodyWidth("thecalenderTable"))/2+(0.125*screen.width))+"px";
	return eval(getPositionX(mainPlayList)+getBodyWidth("mainPlayList")+5)+"px";
}	
function centerLayer(){
	accessCssOfLayer("content").marginLeft = (screen.width - getBodyWidth("content"))/2+"px";
}
/*
function playSelected(song){
	var found = 0;
	//var song = document.getElementById("playlist2").value;
	for(x=0;x<document.getElementById('playlist').length;x++){
		document.getElementById('playlist').selectedIndex = x;
		if(document.getElementById('playlist').value == song){
			loadMusic(document.getElementById('playlist').value);
			found = 1;
			break;
		}
	}
	if(found == 0){
		loadMusic(document.getElementById("playlist2").value);
	}
}
*/

function playSelected(song){
	loadMusic(song);//Load the selected song
	$('#playlist').val(song);//select the song to be played on the playlist.
}	

function nextSong(){
	var nextSongNumber=parseInt(document.getElementById('playlist').selectedIndex)+1;		
	if(nextSongNumber==document.getElementById('playlist').length){
		nextSongNumber=0;				
	}
	document.getElementById('playlist').selectedIndex=nextSongNumber;
	setTimeout("loadMusic(document.getElementById('playlist').value)",3000);
}

//start of key detector
function alertkey(e){
	if( document.captureEvents && Event.KEYUP ) {
		//remove this part if you do not need Netscape 4 to work
		document.captureEvents( Event.KEYUP );
	}
	/* this next line tells the browser to detect a keyup
	event over the whole document and when it detects it,
	it should run the event handler function 'alertkey' */
	//now create the event handler function to process the event
	if( !e ){
		//if the browser did not pass the event information to the
		//function, we will have to obtain it from the event register
		if( window.event ){
			//Internet Explorer
			e = window.event;
		}else{
			//total failure, we have no way of referencing the event
			return;
		}
	}
	if( typeof( e.keyCode ) == 'number'  ){
		//DOM
		e = e.keyCode;
	}else if( typeof( e.which ) == 'number' ){
		//NS 4 compatible
		e = e.which;
	} else if( typeof( e.charCode ) == 'number'  ){
		//also NS 6+, Mozilla 0.9+
		e = e.charCode;
	} else{
		//total failure, we have no way of obtaining the key code
		return;
	}
	if(e==17){
		searchLibrary();
	}
	if(e==13){
		var display = document.getElementById("searchMySong").style.display;
		
		if(display=='block'){
			//check if search window is open and active element is either text field or selection box active searchLibrary funct.
			var selection = document.getElementById("searchFor").value;
			var txtField = document.getElementById("searchSong").value;
			if((getActiveElement()==selection)||(getActiveElement()==txtField)){
				searchDigit = 1;
				//Give focus to the search button to play the first song a song when pressed.
				document.getElementById("searchButton").focus();
				if(getActiveElement()!="Search the song"){//if searchButton is not activated then call getsongs
					getsongs();
				}
			}
		}
		if(searchDigit == 0){
			if(((getActiveElement()==null)||(getActiveElement()=="Search the song"))&&(display=='block')){
				document.getElementById("searchSong").focus();//give focus to searchSong prevent message by firefox
			//play from playlist2 when is displayed and no active element
				if(document.getElementById("playlist2")){
					if(document.getElementById("playlist2").length>0){
						var selectedIndex = document.getElementById("playlist2").selectedIndex;
						playSelected(document.getElementById("playlist2").options[selectedIndex].value);
					}
				}
			}else if(getActiveElement() == document.getElementById("searchSong").value){
				playSelected(document.getElementById("playlist2").options[0].value);
			}else if(getActiveElement() == document.getElementById("playlist").value){
				loadMusic(document.getElementById("playlist").value);
			}else if(getActiveElement() == document.getElementById("playlist2").value){
				playSelected(document.getElementById("playlist2").value);//Play the song from the search box
			}	
			closeSearch();
		}
		searchDigit = 0;
	}	
	if(e==40){
		if(document.getElementById('playlist2')){
			document.getElementById('playlist2').focus();
		}
	}
}
function clearSearchBox(){
	if(document.getElementById('searchSong').value == "Type song or artist"){
		document.getElementById('searchSong').value = "";
		document.getElementById('searchSong').style.color = "#000000";
		document.getElementById('searchSong').focus();
	}	
}
function searchLibrary(){
	var show = document.getElementById("searchMySong").style;
	if(show.display == 'block'){
		//do nothing at all
	}else{
		showContent("searchMySong","mainPlayList","media");
		//document.getElementById("hideValueOfSong").value = document.getElementById('searchSong').value;
		show.display = 'block';	
		document.getElementById('searchSong').value = "Type song or artist";
		document.getElementById('searchSong').style.color = "#999999";		
	}		
}
//get active element	
function getActiveElement() {
    var element = document.activeElement.value;
	return element;
}	
document.onkeydown = alertkey;
//end of key detector
//start of ajax
var xmlHttp;
function stateChanged(){ 
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 
		document.getElementById("favourite").innerHTML=xmlHttp.responseText; 
		if(document.getElementById("playlist2").length == 0){
			var loader = '<div align="center" style=" float:left;width:300px; height:100px; padding-top:100px;">';
			loader += '<span style="font-size:16px;color:#FFFFF0">';
			loader += 'Sorry, no results found for '+document.getElementById("searchSong").value;
			loader += '</span>';
			loader += '</div>';
			document.getElementById('favourite').innerHTML = loader;
		}
 	} 
}

function typeChanged(){ 
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 
		document.getElementById("mainPlayList").innerHTML=xmlHttp.responseText; 
 	} 
}

function GetXmlHttpObject(){
	var xmlHttp=null;
	try{
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}catch (e){
		//Internet Explorer
		try{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}catch(e){
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}

function getsongs(){ 
	if(verifySearch()){
		var song = document.getElementById('searchSong').value;
		var loader = '<div align="center" style=" float:left;width:300px; height:100px; padding-top:100px;">';
		loader += '<img src = "ajax-loader.gif"><br />';
		loader += '<span style="font-size:16px;color:#FFFFF0">';
		loader += 'Searching for '+song+'...';
		loader += '</span>';
		loader += '</div>';
		document.getElementById('favourite').innerHTML = loader;
		
		var type = document.getElementById('searchFor').value;
		xmlHttp=GetXmlHttpObject();
		if (xmlHttp==null){
			alert ("Browser does not support HTTP Request");
			return;
		}
		var url="getsong.php";
		url=url+"?song="+song;
		url=url+"&type="+type;
		url=url+"&sid="+Math.random();
		xmlHttp.onreadystatechange=stateChanged;
		xmlHttp.open("GET",url,true);
		xmlHttp.send(null);
	}	
}
function gettype(type){ 
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null){
 		alert ("Browser does not support HTTP Request");
 		return;
 	}
	var loader = '<div align="center" style="width:320px; height:386px; padding-top:100px;">';
	loader += '<img src = "ajax-loader.gif"><br />';
	loader += '<span style="font-size:16px;color:#FFFFF0">';
	loader += 'Loading '+type+' playlist....';
	loader += '</span>';
	loader += '</div>';
	document.getElementById('mainPlayList').innerHTML = loader;
	var url="getmusictype.php";
	url=url+"?type="+type;
	url=url+"&sid="+Math.random();
	xmlHttp.onreadystatechange=typeChanged;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
	document.getElementById("mainPlayList").focus();
}
//end of ajax
//start of drag script
   var selObj = null;
   function moveHandler(e){
      if (e == null) { e = window.event } 
      if (e.button<=1&&dragOK){
         selObj.style.left=e.clientX-dragXoffset+'px';
         selObj.style.top=e.clientY-dragYoffset+'px';
         return false;
      }
   }
function cleanup(e) {
  document.onmousemove=null;
  document.onmouseup=null;
  selObj.style.cursor=orgCursor;
  dragOK=false;
}

function dragHandler(e){
  var htype='-moz-grabbing';
  if (e == null) { e = window.event; htype='move';} 
  var target = e.target != null ? e.target : e.srcElement;
  selObj=target;
  orgCursor=target.style.cursor;
  if (target.className=="playlistShow") {
	 target.style.cursor=htype;
	 dragOK=true;
	 dragXoffset=e.clientX-parseInt(selObj.style.left);
	 dragYoffset=e.clientY-parseInt(selObj.style.top);
	 document.onmousemove=moveHandler;
	 document.onmouseup=cleanup;
	 return false;
  }
}
//-----------------------------
//start of flash text functions
//------------------------------
function flashtext(){
	var textcolours = Array( "#F00000", "#FF0000", "#FFF000", "#FFFF00", "#FFFFF0", "#FFFFFF");	
   	if(flashText == 1){	
		if(theWaveTime == null && detect_browser()!='msie'){					
			doWave(theNumberNofWave);//Make wave if theWaveTime is null
		}
		document.getElementById("swfaudio").style.display = 'block';
		document.getElementById("hamsterani").style.display = 'block';
		var colour = Math.round(textcolours.length * Math.random() );
		$(".flash").css({color:textcolours[ colour ]}); 		
	}else{
		if(theWaveTime != null){
			clearTimeout(theWaveTime);// if theWaveTime not null clear
			theWaveTime=null;// make theWaveTime null
		}
		document.getElementById("swfaudio").style.display = 'none';
		//document.getElementById("equalizer").style.display = 'none';
		document.getElementById("hamsterani").style.display = 'none';
		$(".flash").css({color:"#FFFF00"}); 
	}
}
//Start thnks message wave
function nextSize(i,incMethod,textLength){
	if (incMethod == 1){ 
		return (15*Math.abs(Math.sin(i/(textLength/3.14))) );
	}
	if (incMethod == 2){ 
		return (200*Math.abs(Math.cos(i/(textLength/3.14))));
	}
	return(0);
}
function sizeCycle(text,method,dis){
	var output = "";
	for (i = 0; i < text.length; i++){
		size = parseInt(nextSize(i +dis,method,text.length));
		output += "<span style='font-family:Arial, Helvetica,";
		output += "sans-serif; font-size:"+size+"px;'>" +text.substring(i,i+1)+ "</span>";					
	}
	if(document.getElementById("ad2")){
		document.getElementById("ad2").innerHTML = output;
	}	
}
function doWave(n) {
	var theText = 'THANK YOU FOR VISITING RUSUMO.COM THE BEST MUSIC ENTERTAINER!';
	sizeCycle(theText,1,n);
	if (n > theText.length) {
		n=0
	}
	theNumberNofWave = n;
	theWaveTime = setTimeout("doWave(" + (n+1) + ")", 50);
}
//End of thanks message wave
//Start of IE version checker
function checkIeBrowserVersion(){//This function changes the height of exchangeHeader for IE6
	if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
		var ieversion=new Number(RegExp.$1); // capture x.x portion and store as a number
		return ieversion;
	}
}	
//End of IE version checker
function verifySearch(){
	if(document.getElementById('searchFor').value == "none"){
		alert('Please select what you want to search for!');
		return false;
	} 
	var searchBox = document.getElementById('searchSong').value;
	if((searchBox == "Type song or artist")||(searchBox == "")){
		alert('Please type a song or artist you want to search!');
		return false;
	}
	return true;
}

