
var queryString;
var rt;
var xmlHttp;
var tbody;
var container;
var songID;
var alternator=0;
var commentsOpen=0;

function ajaxManager()
        {
        var args = ajaxManager.arguments;
        
        switch (args[0])
                {
                case "load_page":
                if (document.getElementById) {
                        var x = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
                        }
                        if (x)
                               {
                        		x.onreadystatechange = function()
                                        {
                                if (x.readyState == 4 && x.status == 200)
                                                {
                                                el = document.getElementById(args[2]);
                                                el.innerHTML = x.responseText;
                                        }
                                        }
                                x.open("GET", args[1], true);
                                x.send(null);
                               }
                        break;
                case "reload_flash_player":
                        ajaxManager('load_page', args[1]+'flashimport.html', 'radioText');
                        break;

				case "narrow_selection":
						
                        ajaxManager('load_page', 'artistview.php?userID='+args[1]+'&'+args[3]+'='+args[2], 'genreContent');
                        break;

				case "show_songs":
                  		var radioDiv = document.getElementById("radioStation");
							
						//remove previous div content
			
						removeChildNodesFrom(radioDiv);
                        break;

				case "add_song":
						
                        ajaxManager('load_page', 'anotherSong.php', 'anotherSong');
                        break;
		}
		}

function flashmsg(msg) { 
	
	createXMLHttpRequest();
	incPlayCount(msg);
}

function createXMLHttpRequest() {

	   if(window.ActiveXObject) {
	      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	   }
	   else {
	      xmlHttp = new XMLHttpRequest();
	   }
};

	function createQueryString() {

	   queryString = 's=' + document.getElementById("s").value;

	}


	function doAjaxPostRequest(handler,url,parameters) {
		xmlHttp.open("POST", url, true);
	    xmlHttp.onreadystatechange = handler;
	    xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
	    xmlHttp.send(parameters);
	    
	}

	function changePlaylistGenre(formName) {
		doAjaxPostRequest(handlePlaylistChange,"createplaylist.php","genre="+document.getElementById(formName).value);
		
	}



	function incRating(e,user) {

		songID=e;
		doAjaxPostRequest(handleRateStateChange,"rating.php",'rating=' + '1' +'&' + 'songID=' + e +'&' + 'userID=' + user);
	}

	function decRating(e,user) {
				
		songID=e;
		doAjaxPostRequest(handleRateStateChange,"rating.php",'rating=' + '-1' +'&' + 'songID=' + e +'&' + 'userID=' + user);
	}

	function updateRating (sID, inc) {
	
		var div = 'rating' + sID;
		
		document.getElementById(div).style.background=(inc > 0) ? '#DAA976' : '#FFD9DA';		
		inc += Number(document.getElementById(div).innerHTML);
		document.getElementById(div).innerHTML=inc;	
		document.getElementById(div).style.color='Black';	
	}
	
	function incRating2(e,user) {

		songID=e;  
		doAjaxPostRequest(handleRateStateChange,"rating.php",'rating=' + '1' +'&' + 'songID=' + e +'&' + 'userID=' + user);
		updateRating (e, 1);		
	}

	function decRating2(e,user) {
				
		songID=e;
		doAjaxPostRequest(handleRateStateChange,"rating.php",'rating=' + '-1' +'&' + 'songID=' + e +'&' + 'userID=' + user);
		updateRating (e, -1);				
	}
	function incPlayCount(ID){ 
		doAjaxPostRequest(handlePlayStateChange,"playcount.php",'songID=' + ID);
	}

	function incBuyCount(ID){
		//urchinTracker("/buy" );
		doAjaxPostRequest(handlePlayStateChange,"buycount.php",'songID=' + ID);
	}


	function select_all()
	{
		var text_val=eval("document.textAreaForm.code");
		text_val.focus();
		text_val.select();
	}


	function checkFileType(form) {

		
		  var ext = form.userfile.value;
		  ext = ext.substring(ext.length-3,ext.length);
		  ext = ext.toLowerCase();
		  if(ext != 'mp3') {
			alert('You selected a .'+ext+
				  ' file; please select a .mp3 file instead!');
			return false; }
		  else
			return true; 
	}
	
	
	
	String.prototype.trim = function() {
		return this.replace(/^\s+|\s+$/g,"");
	}


	 function handlePlaylistChange() {
		
	   if(xmlHttp.readyState == 4) {
	      if(xmlHttp.status == 200) {
		
			var genre=xmlHttp.responseText
		    var radioDiv = document.getElementById("radioText");
			var bioText;

			genre = genre.substring(genre.indexOf('<br>') + 4);

			//remove previous div content
			
			removeChildNodesFrom(radioDiv);

            //create radio div
			
			ajaxManager('reload_flash_player',genre);

	      }
	   }
	}

	function ifAJAXDone (dothis)
	{
		if(xmlHttp.readyState == 4) {
	      if(xmlHttp.status == 200) {
		    dothis;

	      }
	   }
	}


	function handleRateStateChange() {
		
	   ifAJAXDone(parseRatingResults(songID));
	}

	function handleBioStateChange() {

	   ifAJAXDone(showBioResults());
	}

	function handleSendLinkReturn(){

		ifAJAXDone(showMessage("This song was successfully shared."));
		el = document.getElementById("overlay");
		el.style.visibility = "hidden";
	}

	
	function handlePlayStateChange() {
	  
		ifAJAXDone(parsePlayResults());
	}

	function handleStateChange() {
	  
		  ifAJAXDone(parseResults());
	}

		function validateName(form){

			if (form.name.value==""){
				form.errorName.value="Required";
				return false;
				}
			else
				form.errorName.value=" ";
          		return true;
		}

		function validatePreview(form){

			if (form.preview.value==""){
				form.errorPreview.value="Required";
				return false;
				}
			else
				form.errorPreview.value=" ";
          		return true;
		}

		function validateBuyLink(form){

			if (form.buyLink.value==""){
				form.errorBuyLink.value="Required";
				return false;
				}
			else
				form.errorBuyLink.value=" ";
          		return true;
		}

		function validateGenre(form){

			if (form.genre.value==""){
          			form.errorGenre.value="Required";
				return false;
				}
			else
				form.errorGenre.value=" ";
          		return true;
		}

		function isValidEmail(str) {

			return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
		}

		function validateEmail(form){

			if (!isValidEmail(form.email.value)){
          			form.errorEmail.value="Invalid";
				return false;
				}
			else
				form.errorEmail.value=" ";
          		return true;
		}

		function validatePass(form){

			if (form.password.value==""){
          		form.errorPass.value="Required";
				return false;
				}
			else
				form.errorPass.value=" ";
          		return true;
		}

		function validateUserName(form){

			if (form.username.value==""){
          		form.errorUserName.value="Required";
				return false;
				}
			else
				form.errorUserName.value=" ";
          		return true;
		}

		function validatePasswords(form){

			if (form.password.value==form.retypePassword.value){
				form.errorPass2.value="";
				return true;
				}
			else
				form.errorPass2.value="re-enter";
				form.errorPass.value="re-enter";
				return false;
		}

		function correctPersonalForm(formName){

			if (validateName(formName) && validatePasswords(formName) && validateUserName(formName) && validatePass(formName) && validateEmail(formName)) {
				return true;
			}
			else {
			 	alert('Please fill all required fields');
			 	return false;
			}
		}


		function formCorrect(formName){

			if (formName.agree.checked==true)
			{
						
				if ((validateName(formName)) && (validateGenre(formName)) && (checkFileType(formName)))
					return true;
				else {
					alert('Please fill all required fields');
					return false;
				}
			}else{
				alert('You must agree to the Private Submission Agreement before uploading.');
				return false;
			}
		}

		function removeChildNodesFrom(element){

			while (element.hasChildNodes())
			{
				element.removeChild(element.childNodes[0]);
			}
		}

var	tinyMCEno = 1000000;

		function saveBio(userID) {
			
			var bioTextArea = document.getElementById("bioEditor"+""+userID+tinyMCEno+"");
			var bio=bioTextArea.value;
			var bioDiv = document.getElementById("bio"+""+userID+"");


     bio = tinyMCE.get("bioEditor"+userID+tinyMCEno).getContent();
     
     bio = encodeURIComponent(bio.replace(/<p>&nbsp;<\/p>/g, "<br />"));    
     tinyMCE.execCommand('mceRemoveControl',false,'"bioEditor"+userID+tinyMCEno');
     tinyMCEno++;

			removeChildNodesFrom(bioDiv);
				
		doAjaxPostRequest(handleBioStateChange,"bioEdit.php",'userID=' + userID +'&'+'bio='+bio);
			editLinkDiv = document.createElement("div");
			var editLink = createLink("Edit Bio","Javascript:;","editBio("+userID+");","");
			editLinkDiv.appendChild(editLink);
			bioDiv.innerHTML = decodeURIComponent(bio);			
			bioDiv.appendChild(editLinkDiv);
		}

		function editBio(userID) {
			
			var bioTextArea = document.getElementById("bio"+""+userID+"");
			var bioText;
			var bio = bioTextArea.innerHTML;
            //create editor div

			if (bio.indexOf('<div>') > 0)
		  	   bio = bio.substring(0, bio.indexOf('<div>'));  	     
			if (bio.indexOf('<a') > 0)
		  	   bio = bio.substring(0, bio.indexOf('<a'));
		  	    
			bio = bio.replace(/</g, "&lt;");
			bio = bio.replace(/>/g, "&gt;");
			
			bioTextArea.innerHTML = bio;
			
			var editor = createElementID("textarea","bioEditor"+userID+tinyMCEno);
			editor.appendChild(bioTextArea.childNodes[0]);
			
			//remove previous div text
			removeChildNodesFrom(bioTextArea);
			
			saveLinkDiv = document.createElement("div");
			var saveLink = createLink("Save Bio","Javascript:;","createXMLHttpRequest();saveBio("+userID+");","");
			
			//add editordiv to page
			bioTextArea.appendChild(editor);
			saveLinkDiv.appendChild(saveLink);
			bioTextArea.appendChild(saveLinkDiv);
	tinyMCE.execCommand('mceAddControl',false,"bioEditor"+userID+tinyMCEno);	
	tinyMCE.execCommand('mceInsertContent',false, bio);
			
		}


		function parsePlayResults() {
			
		    var messageDiv = document.getElementById("message");
			removeChildNodesFrom(messageDiv);
			xmlToDiv("message",messageDiv);
			

		}

		function showBioResults() {			
			
		    var messageDiv = document.getElementById("message");
			removeChildNodesFrom(messageDiv);
			xmlToDiv("message",messageDiv);
			
		}

		

		function getElementText(pnode){
			return pnode.firstChild.nodeValue;
		};

