google.load("jquery", "1.4.2");
google.load("jqueryui", "1.8.0");

google.setOnLoadCallback(ready);

//shortcut
var d = document;

//songs played array will function like stack
var SONGS_PLAYED = Array();

var g_duration;

function ready()
{	
	$("#btnPlayPause").bind("click", function(){playOrPause();});
	$("#btnNext").bind("click", function(){playNextSong();});
	$("#btnPrevious").bind("click", function(){playPreviousSong();});
	
	$("#spanUser").addClass("showClick");
	
	$("#spanUser").click(function(){
		var id = $(this).text();
		
		if(id != "")
		{
			showProfile(id, "profile");
		}
	});
	
	$("#spanPts").addClass("showClick");
	
	$("#spanPts").click(function(){
		var id = $("#spanUser").text();
		
		if(id != "")
		{
			showProfile(id, "streetcred");
		}
	});
	
	$("#spanSaySomething").bind("click", function(){ 
		//if the user is not logged in... show the login dialog with the 'skip' option
		makeComment();
	});
	
	$("#dialogConfirmation").dialog({
		autoOpen: false, 
		resizable: false, 
		height: 250,
		modal: true,
		title: "registration almost complete...",
		buttons: {"ok": function(){$(this).dialog("close");}}
	});
	
	$("#dialogPermalink").dialog({
		autoOpen: false, 
		resizable: false, 
		modal: true,
		title: "permalink...",
		buttons: {"ok": function(){$(this).dialog("close");}}
	});
	
	$("#spanPermalink").bind("click", function(){openDialog("permalink");});
	
	$("#dialogSuggest").dialog({
		autoOpen: false, 
		resizable: false, 
		height: 350,
		width: 300,
		modal: true,
		title: "suggest a song...",
		buttons: {"ok": function(){suggestSong();}, "cancel": function(){$(this).dialog("close");}}
	});
	
	$("#spanSuggest").bind("click", function(){openDialog("suggest");});
	
	$("#dialogLeaderboard").dialog({
		autoOpen: false, 
		resizable: false, 
		height: 350,
		width: 300,
		modal: true,
		title: "leaderboard...",
		buttons: {"ok": function(){$(this).dialog("close");}}
	});
	
	$("#spanLeaderboard").bind("click", function(){openDialog("leaderboard");});
	
	$("#tblLeaderboard tr:odd").addClass("trOdd");
	$("#tblLeaderboard tr:even").addClass("trEven");
	
	$("#tblLeaderboard tbody tr").bind("click", function()
		{	
			//make ajax call to get user specific stuff
			var id = $(this).find("td:first-child").text();
		
			$.ajax({
		    	type: "POST",
		    	url: "php/action.php",
		    	data: "action=getBreakdown&id=" + escape(this.id),
		    	success: function(msg)
		    	{
		    		$("#dialogBreakdown #divInfo").html(msg);
		    		$("#dialogBreakdown #tblBreakdown tr:odd").addClass("trOdd");
		    		$("#dialogBreakdown #tblBreakdown tr:even").addClass("trEven");
		    		
		    		$("#tblBreakdown tr").bind("click", function()
		    		{
		    			alert($(this).attr("song"));
		    			songSelected(d.getElementById($(this).attr("song")));
	    			});
		    		
		    		//alert(id);
		    		showProfile(id, "streetcred");
		    		//openDialog("breakdown");
		    	}
		    });
		});
	
	$("#dialogBreakdown").dialog({
		autoOpen: false, 
		resizable: false, 
		height: 350,
		width: 500,
		modal: true,
		title: "user...",
		buttons: {"ok": function(){$(this).dialog("close");}}
	});
	
	$("#divProgressBar").click(function(e){
		//alert("progress clicked!");
		//need to figure out relative position of the click within the div
		var x = e.pageX - this.offsetLeft;
		
		//x/200 needs to equat to POS/song_length
		//get song proportion
		var prop = x/200;
		//get new position
		var pos = prop * g_duration;
		soundManager.setPosition("sotd_mp3", pos);
	});
	
	initStars($("#hidRating").val());
	
	//set the width of the table headers
	var spans = $("#tbodySongs tr td");
	
	$("#albumArt").hover(function(){
		//only do this if the song is currently paused!! and not already fading (global var)
		if(isPlaying() == false)
		{
			$("#albumArt").fadeTo('slow', 1);
		}
	}, function(){
		if(isPlaying() == false)
		{
			$("#albumArt").fadeTo('slow', 0.2);
		}
	});
	
	$("#tblSongs tbody tr:odd").addClass("trOdd");
	
	$("#tblSongs").tableDnD({
		onDragClass: "dragged",
		scrollAmount: "100px",
		onDrop: function(table, row)
		{
			resetSongsTable(table, row);
		}
	});
	
	//run check for html to convert comment text-links to links
	$(".spanCommentText").each(function(){
		$(this).html(checkForHTML(replaceSpecialChars($(this).html())));
	});
	
	$("#divPostedComments").css("visibility", "visible");
	
	$(".spanAuthor").live("click", function()
	{
		var id = $(this).text();	
		showProfile(id, "comments");
	});
	
	$("#tblSongs").tablesorter({cancelSelection : true});
	
	$("#spanRatingInfo").click(function()
	{
		//get the song id
		var id = getSongId($("#hidSongId").val());
		
		$.ajax({
			type: "POST",
	    	url: "php/action.php",
	    	data: "action=getRatingInfo&id=" + escape(id),
	    	success: function(msg)
	    	{
				$("#dialogRatingInfo #divPlaceholder").html(msg);
				$("#tblRatings tr:odd").addClass("trOdd");
				$("#tblRatings tr:even").addClass("trEven");
				
				$("#tblRatings tr").bind("click", function()
				{
					//make ajax call to get user specific stuff
					var id = $(this).find("td:first-child").text();
					showProfile(id, "ratings");
				});
				
				openDialog("ratingInfo");
	    	}
		});
		
	});
	
	$("#dialogRatingInfo").dialog({
		autoOpen: false, 
		resizable: false, 
		height: 350,
		width: 500,
		modal: true,
		title: "rating breakdown...",
		buttons: {"ok": function(){$(this).dialog("close");}}
	});
	
	$(".bestOf").bind("click", function(){
		songSelected(document.getElementById("song_" + $(this).attr("song")));
	});
}

function showProfile(id, showState)
{	
	$("#dialogProfile #divPlaceholder").html("<div id='divPlaceholder' align='center'>loading...</div>");
	
	$(".userNav").removeClass("userNavCurrent");
	
	if(showState == "comments")
	{
		$("#divUserNavigation #spanComments").addClass("userNavCurrent");
	}
	else if(showState == "ratings")
	{
		$("#divUserNavigation #spanRatings").addClass("userNavCurrent");
	}
	else if(showState == "streetcred")
	{
		$("#divUserNavigation #spanStreetCred").addClass("userNavCurrent");
	}
	else if(showState == "profile")
	{
		$("#divUserNavigation #spanProfile").addClass("userNavCurrent");
	}
	
	$.ajax({
    	type: "POST",
    	url: "php/action.php",
    	data: "action=getUserProfile&id=" + escape(id),
    	success: function(msg)
    	{
    		$("#dialogProfile #divPlaceholder").html(msg);
    		$("#dialogProfile #divPlaceholder").each(function()
    		{
    			$(this).html(checkForHTML(replaceSpecialChars($(this).html())));
    		});
    		
    		$("#dialogProfile #tblUserComments tr:odd").addClass("trOdd");
    		$("#dialogProfile #tblUserComments tr:even").addClass("trEven");
    		
    		$("#dialogProfile #tblUserRatings tr:odd").addClass("trOdd");
    		$("#dialogProfile #tblUserRatings tr:even").addClass("trEven");
    		
    		$("#dialogProfile #tblBreakdown tr:odd").addClass("trOdd");
    		$("#dialogProfile #tblBreakdown tr:even").addClass("trEven");
    		
    		$("#dialogProfile #tblProfile tr:odd").addClass("trOdd");
    		$("#dialogProfile #tblProfile tr:even").addClass("trEven");
    		
    		$("#dialogProfile #tblUserComments tr").bind("click", function()
    		{
    			songSelected(d.getElementById("song_" + $(this).attr("song")));
			});
    		
    		$("#dialogProfile #tblBreakdown tr").bind("click", function()
    		{
    			var id = $(this).attr("song");
    			if(id != null && id != "")
    			{
    				songSelected(d.getElementById("song_" + $(this).attr("song")));
    			}
			});
    		
    		$("#dialogProfile #tblUserRatings tbody tr").bind("click", function()
    		{
    			songSelected(d.getElementById("song_" + $(this).attr("song")));
			});
    		
    		$("#dialogProfile #tblUserStreetCred tr").bind("click", function()
    		{
    			songSelected(d.getElementById("song_" + $(this).attr("song")));
			});
    		
    		$("#tblUserRatings").tablesorter({cancelSelection : true});
    		$("#tblBreakdown").tablesorter({cancelSelection : true});
    		$("#tblUserComments").tablesorter({cancelSelection : true});
    		$("#tblProfile").tablesorter({cancelSelection : true});
    		
    		if(showState == "comments")
    		{
    			$("#divUserProfile").hide();
    			$("#divUserRatings").hide();
    			$("#divUserStreetCred").hide();
    		}
    		else if(showState == "ratings")
    		{
    			$("#divUserProfile").hide();
    			$("#divUserComments").hide();
    			$("#divUserStreetCred").hide();
    		}
    		else if(showState == "streetcred")
    		{
    			$("#divUserProfile").hide();
    			$("#divUserRatings").hide();
    			$("#divUserComments").hide();
    		}
    		else if(showState == "profile")
    		{
    			$("#divUserStreetCred").hide();
    			$("#divUserRatings").hide();
    			$("#divUserComments").hide();
    		}
    		
    		$("#divUserNavigation #spanProfile").click(function(){$(".userNav").removeClass("userNavCurrent"); $(this).addClass("userNavCurrent"); $("#divUserRatings").hide(); $("#divUserComments").hide(); $("#divUserStreetCred").hide(); $("#divUserProfile").show();});
    		$("#divUserNavigation #spanComments").click(function(){$(".userNav").removeClass("userNavCurrent"); $(this).addClass("userNavCurrent"); $("#divUserRatings").hide(); $("#divUserProfile").hide(); $("#divUserStreetCred").hide(); $("#divUserComments").show();});
    		$("#divUserNavigation #spanRatings").click(function(){$(".userNav").removeClass("userNavCurrent"); $(this).addClass("userNavCurrent"); $("#divUserProfile").hide(); $("#divUserComments").hide(); $("#divUserStreetCred").hide(); $("#divUserRatings").show();});
    		$("#divUserNavigation #spanStreetCred").click(function(){$(".userNav").removeClass("userNavCurrent"); $(this).addClass("userNavCurrent"); $("#divUserProfile").hide(); $("#divUserComments").hide(); $("#divUserRatings").hide(); $("#divUserStreetCred").show(); });
    	}
    });
	
	$("#dialogProfile").dialog({
		autoOpen: false, 
		resizable: false, 
		width:700,
		height: 400,
		modal: true,
		title: id + "...",
		buttons: {"ok": function(){$(this).dialog("close");}}
	});
	
	$("#dialogProfile").dialog("open");
}

function openDialog(dialog, arg)
{
	if(dialog == "login")
	{
		$("#dialogLogin").dialog("enable");
		$("#divMessageLogin").text("");
		
		$("#dialogLogin input[type=text]").bind("focus", function(){$("#divMessageLogin").hide();});
		$("#dialogLogin input[type=password]").bind("focus", function(){$("#divMessageLogin").hide();});
	
		if(arg == true)
		{
			$("#dialogLogin").dialog({ 
				autoOpen: false, 
				resizable: false, 
				modal: true,
				title: "login...",
				buttons: {"ok": function(){ doLogin();}, "skip": function(){closeDialog("login"); createCookie("isc_key", "anonymous", 1); openDialog("anonymousComment");}, "cancel": function(){$(this).dialog("close");}}
			});
			//open the login dialog with the skip button
			$("#dialogLogin").dialog("open");
		}
		else
		{
			$("#dialogLogin").dialog({ 
				autoOpen: false, 
				resizable: false, 
				modal: true,
				title: "login...",
				buttons: {"ok": function(){ doLogin();}, "cancel": function(){$(this).dialog("close");}}
			});
			
			$("#dialogLogin").dialog("open");
		}
	
		$("#divRegister").click(function()
		{
			$("#dialogLogin").dialog("close");
			openDialog("register");
		});
	
		$("#txtUserId").focus(function()
		{
			clearErrorMsg();
		});
	
		$("#txtPassword").focus(function()
		{
			clearErrorMsg();
		});
	}
	else if(dialog == "lyrics")
	{
		$("#dialogLyrics").dialog({ 
			autoOpen: false, 
			resizable: false, 
			width: 400,
			height: 500,
			modal: true,
			title: "upload lyrics...",
			buttons: {"upload":function(){uploadLyrics();}, "cancel":function(){$(this).dialog("close");}}
		});
		
		$("#dialogLyrics #txtLyrics").bind("focus", function(){$("#divMessageUpload").hide();});
	    
		$("#dialogLyrics #txtLyrics").val("");
		
		$("#divMessageUpload").hide();
		$("#divMessageUpload").css("color", "red");
		
		$("#dialogLyrics").dialog("enable");
		$("#dialogLyrics").dialog("open");
	}
	else if(dialog == "register")
	{
		$("#dialogRegister").dialog({
			autoOpen: false, 
			resizable: false, 
			height: 250,
			modal: true,
			title: "register...",
			buttons: {"ok": function(){doRegister();}, "cancel": function(){$(this).dialog("close");}}
		});
		
		$("#dialogRegister input[type=text]").bind("focus", function(){$("#divMessageRegister").hide();});
		$("#dialogRegister input[type=password]").bind("focus", function(){$("#divMessageRegister").hide();});
		
		//clear any previous entries
		$("#dialogRegister input[type=text]").val("");
		$("#dialogRegister input[type=password]").val("");
		
		$("#divMessageRegister").hide();
		
		$("#dialogRegister").dialog("open");
		$("#dialogRegister").dialog("enable");
	}
	else if(dialog == "comment" || dialog=="anonymousComment")
	{
		$("#dialogComment").dialog({
			autoOpen: false, 
			resizable: false, 
			height: 250,
			width: 350,
			modal: true,
			title: "comment...",
			buttons: {"ok": function(){var song_id = getSongId($("#hidSongId").val()); addComment(song_id); }, "cancel": function(){$(this).dialog("close");}}
		});
		
		$("#dialogComment #txtCommentName").bind("focus", function(){$("#divMessageComment").hide();});
		$("#dialogComment #txtComment").bind("focus", function(){$("#divMessageComment").hide();});
		
		$("#txtComment").val("");
		$("#dialogComment #divMessageComment").hide();
		
		if(dialog == "comment")
		{
			//set the text of the user-name
			$("#txtCommentName").val($("#spanUser").text());
		}
		else
		{
			$("#txtCommentName").val("anonymous");
		}
		
		if(dialog == "anonymousComment")
		{
			$("#dialogLoginAnonymous").dialog("close");
		}
		
		$("#dialogComment").dialog("open");
	}
	else if(dialog == "suggest")
	{
		$("#divMessageSuggest").hide();
		
		var user_name = getUserName();
		var email = $("#hidEmail").val();
		
		if(user_name != null && user_name != "")
		{
			//set the user name
			$("#txtSuggestName").attr("disabled", true);
			$("#txtSuggestName").val(getUserName());
		}
		
		if(email != null && email != "")
		{
			$("#txtSuggestEmail").attr("disabled", true);
			$("#txtSuggestEmail").val(email);
		}
		
		$("#dialogSuggest").dialog("open");
	}
	else if(dialog == "permalink")
	{
		//get the id of the previously selected row
	    var row = $("#hidSelected").val();
	    var tr = d.getElementById(row);
	    var tds = tr.getElementsByTagName("td");
	    var date = tds[3].innerText;

	    if (!date || date == null) 
	    {
	        date = tds[3].textContent;
	    }

		$("#divMessagePermalink").text("http://www.indiestreetcred.com/?day=" + date);
		
		$("#dialogPermalink").dialog("open");
	}
	else if(dialog == "leaderboard")
	{
		$("#dialogLeaderboard #tblLeaderboard").tablesorter({cancelSelection : true});
		$("#dialogLeaderboard").dialog("open");
	}
	else if(dialog == "breakdown")
	{
		$("#dialogBreakdown").dialog("open");
	}
	else if(dialog == "ratingInfo")
	{
		$("#tblRatings").tablesorter({cancelSelection : true});
		$("#dialogRatingInfo").dialog("open");
	}
}

function closeDialog(dialog)
{
	if(dialog == "login")
	{
		//reenable buttons... etc
		$("#btnOk").attr("disabled", false);
		$("#btnCancel").attr("disabled", false);
		
		$("#dialogLogin").dialog("close");
	}	
	else if(dialog == "lyrics")
	{
		//hide message
		//remove lyrics
		$("#txtLyrics").val("");
		
		//enable buttons
		$("#divMessage").css("visibility", "hidden");
		
		//disable the buttons
		$("#btnUpload").attr("disabled", false);
		$("#btnCancelUpload").attr("disabled", false);
		
		//remove dialog
		$("#dialogLyrics").dialog("close");
	}
	else if(dialog == "comment")
	{
		//clear the name and comment fields
		$("#dialogComment #txtCommentName").val("");
		$("#dialogComment #txtComment").val("");
		$("#dialogComment #divMessageComment").text("");
		$("#dialogComment #divMessageComment").css("color", "red");
		
		$("#dialogComment").dialog("close");
	}
	else if(dialog == "suggest")
	{
		$("#txtSuggestName").val("");
		$("#txtSuggestEmail").val("");
		$("#txtSuggestArtist").val("");
		$("#txtSuggestSong").val("");
		$("#txtSuggestComment").val("");
		
		$("#divMessageSuggest").hide();
		
		$("#dialogSuggest").dialog("close");
	}
}

function resetSongsTable(table, row)
{
	$("#tblSongs tbody tr").removeClass("trOdd");
	$("#tblSongs tbody tr").removeClass("trEven");
	$("#tblSongs tbody tr").removeClass("dragged");
	
	$("#tblSongs tbody tr:even").addClass("trEven");
	$("#tblSongs tbody tr:odd").addClass("trOdd");
}

function resetTableCss($table)
{
	$table.find("tr").removeClass("trOdd");
	$table.find("tr").removeClass("trEven");
	$table.find("tr").removeClass("dragged");
	
	$table.find("tr:even").addClass("trEven");
	$table.find("tr:odd").addClass("trOdd");
}

function sotdLoad()
{
	//get the hidden song id
	var song_id = $("#hidSongId").val();

	//use that to get the song path
	var tr = d.getElementById(song_id);
	tr.className = "trSelected";
	//get the actual path to the previous song of the day
    var song_src = tr.getElementsByTagName("input")[0].value;
    
    soundManager.play("sotd_mp3", song_src);
    
    SONGS_PLAYED.push(song_id);
}

function updateSocialNetworking(song, artist, date)
{
	var url = "http://www.indiestreetcred.com/?day=" + date;
	var text = artist + " - " + song + " ... on %23indiestreetcred ";
	
	var twitter_link = "http://twitter.com/home?status=" + text + url;
	var buzz_link = "http://www.google.com/buzz/post?message=" + text + "&url=" + url;
	
    $("#lnkTwitter").attr("href", twitter_link);   
    
    //remove facebook iframe.. and re-add it
    $("#spanFacebook").html("<iframe id=\"lnkFacebook\" src=\"http://www.facebook.com/plugins/like.php?href=" + url + "&amp;layout=button_count&amp;show-faces=false&amp;width=450&amp;action=like&amp;colorscheme=light\" scrolling=\"no\" frameborder=\"0\" allowTransparency=\"true\" style=\"border:none; overflow:hidden; diplay:inline; width:100px; height:22px\"></iframe>");
    //$("#lnkFacebook").attr("src", "http://www.facebook.com/plugins/like.php?href=" + url + "&amp;layout=button_count&amp;width=100&amp;action=like&amp;colorscheme=light");
    
    //alert("here!");
    //var f = document.getElementById("#lnkFacebook");
    //f.contentWindow.location.reload(true);
    
    //alert("reloaded!");
    
    //$("#lnkFacebook").attr("src", "http://www.facebook.com/plugins/like.php?href=" + url + "&amp;layout=button_count&amp;width=100&amp;action=like&amp;colorscheme=light");
      
    $("#lnkBuzz").attr("href", buzz_link);
}

function load_art(src, album, year)
{
	 var img = d.getElementById("albumArt");
	 var img_array = 
	 
	 //use jquery to fade out
	 $("#albumArt").fadeTo('slow', 0, function(){
		 img.src = src;
		 img.onload = function(){$("#albumArt").fadeTo('slow', 1);};
		 
	 });
	
	 img.title = album + " [" + year + "]";
} 

function play() 
{
    soundManager.play("sotd_mp3");
    
}

function isPlaying()
{
	var img = d.getElementById("imgPlayPause");
	
	if (img.src.match(/pause_button/)) 
    {
		return true;
    }
	
	return false;
}

function playOrPause() 
{
    //change the imgPlayPause
	var img = d.getElementById("imgPlayPause");

    if (img.src.match(/play_button/)) 
    {
        //call play and switch to pause img
        play();
        img.src = "img/pause_button.png";
      //make sure the album art is opaque
        $("#albumArt").fadeTo('slow', 1);
    }
    else if (img.src.match(/pause_button/)) 
    {
        //call pause and switch to play img
        pause();
        img.src = "img/play_button.png";
      //make sure the album art is opaque
        $("#albumArt").fadeTo('slow', 0.2);
    }
}

function pause() 
{
    soundManager.pause("sotd_mp3");
}

function stop() 
{
    soundManager.stop("sotd_mp3");

    //change the imgPlayPause to play
    var img = d.getElementById("imgPlayPause");
    img.src = "img/play_button.png";
}

function addProgress(position, duration) 
{
    var divProgress = d.getElementById("divProgress");
    divProgress.style.width = Math.round((position / duration) * 200) + "px";
}

function addLoad(bytes, bytesTotal, duration) 
{
	g_duration = duration;
	
    var divLoaded = d.getElementById("divLoaded");
    divLoaded.style.width = Math.round((bytes / bytesTotal) * 200) + "px";
}

function songFinish() 
{
    //reset progress bar
    var divProgress = d.getElementById("divProgress");
    divProgress.style.width = 0 + "px";

    //check for continuous play
    var hidContinuous = d.getElementById("hidContinuous");
    var hidRandom = d.getElementById("hidRandom");

    if (hidContinuous.value == "true" || hidRandom.value == "true")
    {
        showComments();
        playNextSong();
    }
    else if (hidContinuous.value == "1") 
    {
        //no need to kill sotd_mp3 and start from scratch.. just play
        soundManager.play("sotd_mp3");
    }
    else 
    {
        //return button to play button
        //change the imgPlayPause to play
        var img = d.getElementById("imgPlayPause");
        img.src = "img/play_button.png";
    }
}

function playNextSong() 
{
    var hid = d.getElementById("hidRandom");

    var tbl = d.getElementById("tblSongs");

    if (tbl.rows.length == 0) 
    {
        alert("rows length = 0");
        return;
    }

    var nextSong;

    if (hid.value == "true")
     {
        //if not random play the next row
        var songId = d.getElementById("hidSelected").value;

        if (songId == null) 
        {
            songId = d.getElementById("hidSongId").value;
        }

        nextSong = songId;

        while (nextSong == songId) 
        {
            //get random number btwn 0 and array.length - 1
            var random = Math.random() * tbl.rows.length;
            nextSong = Math.floor(random);
        }
    }
    else 
    {
        //check to see if repeat one is on
        hid = d.getElementById("hidContinuous");

        if (hid.value == "1") 
        {
            //just replay the current song
            soundManager.play("sotd_mp3");
            return;
        }
        else 
        {
            //if not random play the next row
            var songId = d.getElementById("hidSelected").value;

            if (songId == null) 
            {
                songId = d.getElementById("hidSongId").value;
            }

            var currentTr = d.getElementById(songId).rowIndex;

            if (currentTr == null || currentTr == "undefined" || isNaN(currentTr)) 
            {
                currentTr = tbl.rows.length - 4;
            }

            var nextSong = parseInt(currentTr) + 1;

            if (nextSong > tbl.rows.length - 1) 
            {
                nextSong = 0;
            }
        }
    }

    var tr = tbl.rows[nextSong];
    
    //scroll to selected song
    var divOldSotd = d.getElementById("divOldSotd");
    var scrollHeight = nextSong * tbl.rows[0].offsetHeight;

    divOldSotd.scrollTop = scrollHeight - 20;

    songSelected(tr);
}

function playPreviousSong() {
    /*
    //used for debugging!
    var strIds = "";
    
    for(var i = 0; i < SONGS_PLAYED.length; i++)
    {
    strIds += SONGS_PLAYED[i] + ", ";
    }
    
    alert(strIds);*/

    var tbl = d.getElementById("tblSongs");

    if (tbl.rows.length == 0) 
    {
        return;
    }

    if (SONGS_PLAYED.length == 0) 
    {
        return;
    }

    if (SONGS_PLAYED.length > 1) 
    {
        //play the last song in the array (at index length - 1)
        SONGS_PLAYED.pop();
        var row_id = SONGS_PLAYED.pop();

        var tr = d.getElementById(row_id);

        songSelected(tr);
    }
    else 
    {
        //assert that the length is 1?
        var row_id = SONGS_PLAYED.pop();

        var tr = d.getElementById(row_id);

        songSelected(tr);
    }
}

function addComment(song_id)
{
    var raw_txt = $("#txtComment").val();
    
    //TODO - redo html
    var txt = replaceLineBreaks(raw_txt);
    
    txt = escapeSpecialChars(txt);
    
    var name = escapeSpecialChars($("#txtCommentName").val());

    if (!song_id) 
    {
        var id = getSongId($("#hidSongId").val());
    }
    else 
    {
        var id = song_id;
    }
    
    //make sure the comment name and comment text are present
    if(name == null || name == "" || txt == null || txt == "")
    {
    	$("#divMessageComment").text("all fields are required.");
    	$("#divMessageComment").show();
    	return;
    }
    
    $("#divMessageComment").text("posting...");
    $("#divMessageComment").css("color", "black");
    $("#divMessageComment").show();
    
    $.ajax({
    	type: "POST",
    	url: "php/action.php",
    	data: "action=addComment&id=" + escape(id) + "&comment=" + escape(txt),
    	success: function(msg)
    	{
    		comment_callback(msg);
    	}
    });
}

function comment_callback(xml)
{
    //only need to draw out the comment if the comments are showing (and not lyrics)
    if (d.getElementById("divPostedComments"))
    {
    	var xmlDoc = xml;

        //get the message
        var m = getXmlNode(xmlDoc, "statusId");
        var txt = getXmlNode(xmlDoc, "comment");
        var author = getXmlNode(xmlDoc, "author");
        var date = getXmlNode(xmlDoc, "datePosted");

        txt = replaceSpecialChars(txt);
        author = replaceSpecialChars(author);

        //add comment to the table
        var tbl = d.getElementById("tbodyComments");

        var tr = d.createElement("tr");
        var td = tr.appendChild(d.createElement("td"));
        td.className = "sotdText";

        var div = d.createElement("div");
        div.className = "divComment";

        var divAuthor = div.appendChild(d.createElement("div"));
        divAuthor.className = "divAuthor";

        var img = d.createElement("img");
        img.src = "img/comment.png";
        img.className = "imgComment";

        divAuthor.appendChild(img);

        var spanAuthor = divAuthor.appendChild(d.createElement("span"));
        spanAuthor.className = "spanAuthor";
        spanAuthor.appendChild(d.createTextNode(author));

        var spanDash = divAuthor.appendChild(d.createElement("span"));
        spanDash.className = "spanDash";
        spanDash.appendChild(d.createTextNode(" - "));

        var spanCommentDate = divAuthor.appendChild(d.createElement("span"));
        spanCommentDate.className = "spanCommentDate";
        spanCommentDate.appendChild(d.createTextNode(date));

        var divComment = div.appendChild(d.createElement("div"));

        var spanCommentText = divComment.appendChild(d.createElement("span"));
        spanCommentText.className = "spanCommentText";

        spanCommentText.innerHTML = checkForHTML(replaceLineBreaks(txt));

        td.appendChild(div);

        tbl.appendChild(tr);

        var divPostedComments = d.getElementById("divPostedComments");

        divPostedComments.scrollTop = divPostedComments.scrollHeight;

        closeDialog("comment");
    }
}

function formatComment(str)
{
    if (str.match(/http:\/\/[\w\.]+/))
    {
        var comment = "";
        
        var words = str.split(" ");

        for (var i = 0; i < words.length; i++)
        {
            //check for the href
            if (words[i].match(/^href/))
            {
                //some urls may be case-sensitive
                comment += words[i] + " ";
            }
            else
            {
                comment += words[i] + " ";
            }
        }

        return comment;
    }
    else
    {
        return str;
    }
}

function allowComment(str)
{
    var re = /(.)*<object(.)*/;
    var re1 = /(.)*<div(.)*/;
    var re2 = /(.)*<span(.)*/;
    var re3 = /(.)*<marquee(.)*/;
    var re4 = /(.)*<html(.)*/;
    var re5 = /(.)*<head(.)*/;
    var re6 = /(.)*<embed(.)*/;
    var re7 = /(.)*<b>(.)*/;
    var re8 = /(.)*<h(.)*/;
    var re9 = /(.)*<p(.)*/;
    var re10 = /(.)*<img(.)*/;
    var re11 = /(.)*<body(.)*/;
    var re12 = /(.)*<h(.)*/;
    var re13 = /(.)*<input(.)*/;
    var re14 = /(.)*<script(.)*/;
    var re15 = /(.)*<table(.)*/;
    var re16 = /(.)*<tr(.)*/;
    var re17 = /(.)*<td(.)*/;
    var re18 = /(.)*<tbody(.)*/;
    var re19 = /(.)*<style(.)*/;
    var re20 = /(.)*<link(.)*/;
    var re21 = /(.)*<meta(.)*/;
    var re22 = /(.)*<title(.)*/;
    var re23 = /(.)*<font(.)*/;
    var re24 = /(.)*<a(.)*/;

    var return_val = re.test(str) || re1.test(str) || re2.test(str) || re3.test(str) && re4.test(str) || re5.test(str) || re6.test(str) || re7.test(str) || re8.test(str) || re9.test(str) || re10.test(str) || re11.test(str) || re12.test(str) || re13.test(str) || re14.test(str) || re15.test(str) || re16.test(str) || re17.test(str) || re18.test(str) || re19.test(str) || re20.test(str) || re21.test(str) || re22.test(str) || re23.test(str) || re24.test(str);

    return !return_val;
}

function addComments(arrComments) 
{
    var tbl = d.getElementById("tbodyComments");

    for (var i = 0; i < arrComments.length; i++) 
    {
        var tr = tbl.appendChild(d.createElement("tr"));
        var td = tr.appendChild(d.createElement("td"));
        td.className = "sotdText";

        var text = arrComments[i].getElementsByTagName("text")[0].firstChild.nodeValue;
        var authorTag = arrComments[i].getElementsByTagName("author")[0];

        var author = "";

        if (authorTag && authorTag.firstChild && authorTag.firstChild.nodeValue) 
        {
            author = authorTag.firstChild.nodeValue;
        }

        var pointsTag = arrComments[i].getElementsByTagName("points")[0];

        var points = "";

        if (pointsTag && pointsTag.firstChild && pointsTag.firstChild.nodeValue) 
        {
            points = pointsTag.firstChild.nodeValue;
        }

        var date = arrComments[i].getElementsByTagName("date")[0].firstChild.nodeValue;

        text = replaceSpecialChars(text);
        author = replaceSpecialChars(author);

        var div = d.createElement("div");
        div.className = "divComment";

        var divAuthor = div.appendChild(d.createElement("div"));

        divAuthor.className = "divAuthor";
        var img = d.createElement("img");
        img.src = "img/comment.png";
        img.className = "imgComment";

        divAuthor.appendChild(img);

        var spanAuthor = divAuthor.appendChild(d.createElement("span"));
        spanAuthor.className = "spanAuthor";
        spanAuthor.appendChild(d.createTextNode(author));

        if (points != null && points != "") 
        {
            spanAuthor.title = "(" + points + ")";
        }

        var spanDash = divAuthor.appendChild(d.createElement("span"));
        spanDash.className = "spanDash";
        spanDash.appendChild(d.createTextNode(" - "));

        var spanCommentDate = divAuthor.appendChild(d.createElement("span"));
        spanCommentDate.className = "spanCommentDate";
        spanCommentDate.appendChild(d.createTextNode(date));

        var divComment = div.appendChild(d.createElement("div"));

        var spanCommentText = divComment.appendChild(d.createElement("span"));
        spanCommentText.className = "spanCommentText";
        //spanCommentText.innerHTML = formatComment(text);
        spanCommentText.innerHTML = checkForHTML(replaceLineBreaks(text));

        td.appendChild(div);
    }
}

function showOldSongs() 
{
    if (d.getElementById("divOldSotd").style.display == "none") 
    {
        d.getElementById("divOldSotd").style.display = "";
        d.getElementById("divOldSongsHeader").style.display = "";
        d.getElementById("divControls").style.display = "";

        //change link text to read 'hide old sotds'
        d.getElementById("lnkOldSotds").firstChild.nodeValue = "hide all sotds";
    }
    else 
    {
        d.getElementById("divOldSotd").style.display = "none";
        d.getElementById("divOldSongsHeader").style.display = "none";
        d.getElementById("divControls").style.display = "none";

        //change link text to read 'show old sotds'
        d.getElementById("lnkOldSotds").firstChild.nodeValue = "show all sotds";
    }
}

function songSelected(tr) 
{
    //get the id of the previously selected row
    var row = d.getElementById("hidSelected").value;

    if (row != "") 
    {
        var rowIndex = d.getElementById(row).rowIndex;

        if (rowIndex % 2 == 0) 
        {
            d.getElementById(row).className = "trEven";
        }
        else 
        {
            d.getElementById(row).className = "trOdd";
        }
    }
    else 
    {
        var row = d.getElementById("hidSongId").value;

        var rowIndex = d.getElementById(row).rowIndex;

        if (rowIndex != "") 
        {
            if (rowIndex % 2 == 0) 
            {
                d.getElementById(row).className = "trEven";
            }
            else
            {
                d.getElementById(row).className = "trOdd";
            }
        }
        else if (rowIndex == "0")
        {
        if (rowIndex % 2 == 0) 
            {
                d.getElementById(row).className = "trEven";
            }
            else 
            {
                d.getElementById(row).className = "trOdd";
            }
        }
        else 
        {
            alert("how?");
        }
    }

    tr.className = "trSelected";

    //reset previously selected
    d.getElementById("hidSelected").value = tr.id;

    SONGS_PLAYED.push(tr.id);

    //get the actual path to the previous song of the day
    var song_src = tr.getElementsByTagName("input")[0].value;

    //call stop to make sure nothing is playing
    if (soundManager && soundManager.isPlaying("sotd_mp3") == 1) 
    {
        soundManager.stop("sotd_mp3");
    }

    soundManager.destroySound("sotd_mp3");
    soundManager.play("sotd_mp3", song_src);

    //show the pause button
    var img = d.getElementById("imgPlayPause");
    img.src = "img/pause_button.png";

    setSongInfo(tr);
}

function setSongInfo(tr) 
{
    var art_src = tr.getElementsByTagName("input")[1].value;
    var id = tr.getElementsByTagName("input")[2].value;
    var year = tr.getElementsByTagName("input")[3].value;

    //get the song name/artist/album
    var spans = tr.getElementsByTagName("span");

    var name = spans[0].firstChild.nodeValue;
    var artist = spans[1].firstChild.nodeValue;
    var album = spans[2].firstChild.nodeValue;
    var air_date = spans[3].firstChild.nodeValue;

    //if the last three characters are '...' use the title property
    var fullName = spans[0].title;
    var fullArtist = spans[1].title;
    var fullAlbum = spans[2].title;

    if (fullName == null || fullName == "") 
    {
        fullName = name;
    }

    if (fullArtist == null || fullArtist == "") 
    {
        fullArtist = artist;
    }

    if (fullAlbum == null || fullAlbum == "") 
    {
        fullAlbum = album;
    }

    d.getElementById("divSongName").firstChild.nodeValue = fullName;
    d.getElementById("divArtistName").firstChild.nodeValue = fullArtist;
    d.getElementById("divAlbumName").firstChild.nodeValue = fullAlbum + " [" + year + "]";

    //reset the selected song id
    d.getElementById("hidSongId").value = id;

    //fade in new album art, etc.
    load_art(art_src, fullAlbum, year);
    
    //need to get the air date
    updateSocialNetworking(fullName, fullArtist, air_date);
    
    $.ajax({
    	type: "POST",
    	url: "php/action.php",
    	data: "action=getComments&id=" + id,
    	success: function(msg)
    	{
    		getComments(msg);
    	}
    });
}

function getComments(xml) 
{
	var xmlDoc = xml;
	
    var arrComments = $(xmlDoc).find("comment");
    showComments();

    clearTable("tbodyComments");
    addComments(arrComments);

    var stars = getXmlNode(xmlDoc, "rating");
    
    initStars(stars);

    var avg = getXmlNode(xmlDoc, "avg");
    var votes = getXmlNode(xmlDoc, "votes");

    setStats(avg, votes);
}

function commentClick() 
{
    var txt = d.getElementById("txtComment");

    if (txt.value == "comment...") 
    {
        txt.value = "";
    }
}

function commentNameClick() 
{
    var txt = d.getElementById("txtCommentName");

    if (txt.value == "your name...") 
    {
        txt.value = "";
    }
}

function getUserName()
{
    var userName;

    if (d.getElementById("spanUser").firstChild)
    {
        userName = d.getElementById("spanUser").firstChild.nodeValue;

        if (userName == "")
        {
            userName = "anonymous";
        }
    }
    else
    {
        userName = "anonymous";
    }

    return userName;
}

function suggestSong() 
{
    //ensure that all values are set
    var name = $("#txtSuggestName").val();
    var email = $("#txtSuggestEmail").val();
    var artist = $("#txtSuggestArtist").val();
    var song = $("#txtSuggestSong").val();
    var comment = $("#txtSuggestComment").val();

    var $divMessage = $("#divMessageSuggest");

    if (name == "" || email == "" || artist == "" || song == "") 
    {
        //all fields are required
    	$divMessage.text("all fields are required.");
    	$divMessage.show();
        return;
    }

    var validPath = /^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9])+(\.[a-zA-Z0-9_-]+)+$/

    if (!email.match(validPath)) 
    {
        //all fields are required
    	$divMessage.text("enter a valid email address.");
    	$divMessage.show();
        return;
    }
    
    $divMessage.text("sending suggestion...");
    $divMessage.css("color", "black");
    $divMessage.show();
    
    $.ajax({
    	type: "POST",
    	url: "php/action.php",
    	data: "action=suggest&name=" + escape(name) + "&email=" + escape(email) + "&artist=" + escape(artist) + "&song_name=" + escape(song) + "&comment=" + escape(comment),
    	success: function(msg)
    	{
    		suggest_callback(msg);
    	}
    });
}

function suggest_callback(xml) 
{
    //get the status message
    var msg = getXmlNode(xml, "statusId");

    if (msg == "success") 
    {
        closeDialog("suggest");
    }
    else 
    {
        alert(xml);
    }
}

function clearErrorMsg(id) 
{
	/*if(id == null || id == "")
	{
		d.getElementById("divMessage").style.visibility = "hidden";
	}
	else
	{
		d.getElementById(id).style.visibility = "hidden";
	}*/
}

function subscribe_callback(xml) 
{
	var xmlDoc = xml;
	
    //get the status message
    var msg = getXmlNode(xmlDoc, "statusId");

    if (msg == "success") 
    {
        //remove the translucent cover div
        removeCoverDiv();
    }
    else 
    {
        alert(xml);
    }
}

function sort(type) 
{
	if(type == "name")
	{
		$("#thName").click();
	}
	else if(type == "artist")
	{
		$("#thArtist").click();
	}
	else if(type == "album")
	{
		$("#thAlbum").click();
	}
	else if(type == "date")
	{
		$("#thAirDate").click();
	}
	else if(type == "rating")
	{
		$("#thUserRating").click();
	}
}

function randomPlay() 
{
    //change the link to be selected
    var hid = d.getElementById("hidRandom");

    if (hid.value == "") 
    {
        d.getElementById("spanRandom").className = "selected";
        d.getElementById("spanRandom").title = "turn off random play";
        hid.value = "true";

        //uncheck the continuous
        d.getElementById("spanContinuous").className = "unselected";
        d.getElementById("spanContinuous").title = "turn on continuous play";
        d.getElementById("hidContinuous").value = "";
    }
    else 
    {
        d.getElementById("spanRandom").className = "unselected";
        d.getElementById("spanRandom").title = "turn on random play";
        hid.value = "";
    }
}

function continuousPlay() 
{
    //change the link to be selected
    var hid = d.getElementById("hidContinuous");

    if (hid.value == "") 
    {
        d.getElementById("spanContinuous").className = "selected";
        d.getElementById("spanContinuous").title = "turn on repeat x 1 play";
        hid.value = "true";

        //uncheck the random
        d.getElementById("spanRandom").className = "unselected";
        d.getElementById("spanRandom").title = "turn on random play";
        d.getElementById("hidRandom").value = "";
    }
    else if (hid.value == "true") 
    {
        d.getElementById("spanContinuous").className = "selected";
        d.getElementById("spanContinuous").title = "turn off repeat play";
        d.getElementById("spanContinuous").firstChild.nodeValue = "repeat x 1";
        hid.value = "1";

        //uncheck the random
        d.getElementById("spanRandom").className = "unselected";
        d.getElementById("spanRandom").title = "turn on random play";
        d.getElementById("hidRandom").value = "";
    }
    else 
    {
        d.getElementById("spanContinuous").className = "unselected";
        d.getElementById("spanContinuous").title = "turn on repeat play";
        d.getElementById("spanContinuous").firstChild.nodeValue = "repeat";
        hid.value = "";
    }
}

function makeComment() 
{
    var song_id = getSongId(d.getElementById("hidSelected").value);

    var isc_key = readCookie("isc_key");

    if (!isc_key || isc_key == "anonymous") 
    {
    	openDialog("login", true);
        //showLogin(true);
        return;
    }
    
    openDialog("comment");
}

function getSongId(row)
{
	if(!isNaN(row))
	{
		return row;
	}
	else
	{
		//assume its of the form song_nnn
		var parts = row.split("_");
		return parts[1];
	}
}

function mapMonth(val) 
{
    var months = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
    return months[val];
}

function setDate(userName) 
{
    var date = new Date();
    var strDate = mapMonth(date.getMonth()) + " " + date.getDate() + ", " + date.getFullYear();

    var spanDate = d.getElementById("spanDate");

    if (spanDate.childNodes.length == 0) 
    {
        spanDate.appendChild(d.createTextNode(strDate));
    }
    else
    {
        spanDate.firstChild.nodeValue = strDate;
    }

    //check for the user cookie, and if its there, set the spanUser text
    //var userName = readCookie("isc_key");
    var isc_key = readCookie("isc_key");

    //TODO - get userName

    if (userName) 
    {
        var spanUser = d.getElementById("spanUser");

        if (spanUser.childNodes.length == 0) 
        {
            spanUser.appendChild(d.createTextNode(userName));
        }
        else 
        {
            spanUser.firstChild.nodeValue = userName;
        }
    }
    else if (isc_key) 
    {
        //ajax to get the users login name
    }
    else 
    {
        d.getElementById("spanLogout").firstChild.nodeValue = "login";
    }

}

function registerButtonFunctionality(show_skip)
{
	$("#btnOk").click(function()
	{
		doLogin(show_skip);
	});
	
	$("#btnCancel").click(function()
	{
		//call remove cover div
        removeCoverDiv();
	});
	
	$("#btnSkip").click(function()
	{
		//not sure if want to create this cookie here
        createCookie("isc_key", "anonymous", 1);
        removeCoverDiv();
        makeComment(true);
	});
	
	$("#divRegister").click(function()
	{
		removeCoverDiv();
	    showRegister();
	});
	
	$("#txtUserId").focus(function()
	{
		clearErrorMsg();
	});
	
	$("#txtPassword").focus(function()
	{
		clearErrorMsg();
	});
}

function showRegister() 
{
    var divCover = createCoverDiv();

    var br = d.createElement("br");

    var divRegister = d.createElement("div");
    divRegister.id = "divDrag";
    divRegister.className = "popup";

    divRegister.appendChild(getTitleDiv("register"));

    var tbl = divRegister.appendChild(d.createElement("table"));
    var tbody = tbl.appendChild(d.createElement("tbody"));

    //id
    var tr = tbody.appendChild(d.createElement("tr"));
    var td = tr.appendChild(d.createElement("td"));
    td.appendChild(d.createTextNode("user id: "));

    var input = d.createElement("input");
    input.id = "txtUserId";
    input.onfocus = clearErrorMsg;
    input.maxLength = 32;

    td = tr.appendChild(d.createElement("td"));
    td.appendChild(input);

    //password
    tr = tbody.appendChild(d.createElement("tr"));
    td = tr.appendChild(d.createElement("td"));
    td.appendChild(d.createTextNode("password: "));

    var input = d.createElement("input");
    input.id = "txtPassword";
    input.type = "password";
    input.onfocus = clearErrorMsg;
    input.maxLength = 32;

    td = tr.appendChild(d.createElement("td"));
    td.appendChild(input);

    //password 2
    tr = tbody.appendChild(d.createElement("tr"));
    td = tr.appendChild(d.createElement("td"));
    td.appendChild(d.createTextNode("confirm password: "));

    var input = d.createElement("input");
    input.id = "txtPassword2";
    input.type = "password";
    input.onfocus = clearErrorMsg;
    input.maxLength = 32;

    td = tr.appendChild(d.createElement("td"));
    td.appendChild(input);

    //email
    tr = tbody.appendChild(d.createElement("tr"));
    td = tr.appendChild(d.createElement("td"));
    td.appendChild(d.createTextNode("email: "));

    var input = d.createElement("input");
    input.id = "txtEmail";
    input.onfocus = clearErrorMsg;
    input.maxLength = 64;

    td = tr.appendChild(d.createElement("td"));
    td.appendChild(input);

    var divBtns = d.createElement("div");

    var btnOk = createButton("btnOk", "ok");
    btnOk.className = "btnPlainSotd";
    divBtns.appendChild(btnOk);

    btnOk.onclick = function() 
    {
        doRegister();
        //removeCoverDiv();
    }

    var btnCancel = createButton("btnCancel", "cancel");
    btnCancel.className = "btnPlainSotd";
    divBtns.appendChild(btnCancel);

    btnCancel.onclick = function() 
    {
        //call remove cover div
        removeCoverDiv();
    }

    divBtns.align = "center";
    divRegister.appendChild(br);
    divRegister.appendChild(divBtns);

    var divMessage = d.createElement("div");
    divMessage.align = "center";
    divMessage.id = "divMessage";
    divMessage.appendChild(d.createTextNode("posting comment..."));
    divMessage.style.visibility = "hidden";

    divRegister.appendChild(divMessage);

    //for ie
    divRegister.style.width = "300px";

    divCover.appendChild(divRegister);
    centerObject(divRegister);
}

function doLogin(blnPost) 
{
    var user_name = $("#dialogLogin #txtUserId").val();
    var password = $("#dialogLogin #txtPassword").val();

    //TODO - jquery
    var $divMessage = $("#divMessageLogin");

    if (user_name == "" || password == "") 
    {

        $divMessage.text("all fields are required.");
        $divMessage.css("color", "red");
        $divMessage.show();
        return;
    }

    var song_id = getSongId($("#hidSelected").val());

    //blnPost indicates whether or not the user was trying to post a comment
    var type = "";
    
    if (blnPost == true) 
    {
        type = "post";
    }
    else 
    {
        type = "other";
    }

    $divMessage.text("logging in...");
	$divMessage.css("color", "black");
	$divMessage.show();

    $("#dialogLogin").dialog("disable");
    
    $.ajax({
    	type: "POST",
    	url: "php/action.php",
    	data: "action=login&user_name=" + escape(user_name) + "&password=" + escape(password) + "&song_id=" + escape(song_id) + "&type=" + escape(type),
    	success: function(msg)
    	{
    		//msg = makeXML(msg);
    		login_callback(msg);
    	}
    });
}

function makeXML(xmlString)
{
    var xmlDoc = null;

    if( ! window.DOMParser )
    {
        // the xml string cannot be directly manipulated by browsers 
        // such as Internet Explorer because they rely on an external 
        // DOM parsing framework...
        // create and load an XML document object through the DOM 
        // ActiveXObject that it can deal with
        xmlDoc = new ActiveXObject( "Microsoft.XMLDOM" );
        xmlDoc.async = false;
        xmlDoc.loadXML( xmlString );
    }
    else
    {
        // the current browser is capable of creating its own DOM parser
        parser = new DOMParser();
        xmlDoc = parser.parseFromString( xmlString, "text/xml" ) ;
    }

    return xmlDoc;
}

function login_callback(xml)
{
	var xmlDoc = xml;
	//var xmlDoc = makeXML(xml);

    var blnAllow = $(xmlDoc).find("allow").text();
	//var blnAllow = getXmlNode(xmlDoc, "allow");

    //alert(blnAllow);
    if (blnAllow == "true") 
    {
        //get the user name
        var user_name = $(xmlDoc).find("userName").text();
        var user_email = $(xmlDoc).find("userEmail").text();

        $("#hidEmail").val(user_email);

        var isc_key = getXmlNode(xmlDoc, "iscKey");

        //set logout span
        d.getElementById("spanLogout").firstChild.nodeValue = "logout";

        //write the user name cookie
        createCookie("isc_key", isc_key, 7);
        setDate(user_name);

        //remove the login popup div
        //removePopupDiv("divDrag");

        var rating = getXmlNode(xmlDoc, "rating");
        initStars(rating);

        //get points
        var points = getXmlNode(xmlDoc, "points");
        showPoints(points);

        var type = getXmlNode(xmlDoc, "type");

        if (type == "post") 
        {
            //only call this if the user pressed say something then had to login
            //and allow the user to say something
            makeComment();
        }
        else 
        {
            //remove the cover
            //removeCoverDiv();
        	closeDialog("login");
        }
        
        var one_star = "<img src='img/dark_gray.gif'/>";
        var two_star = one_star + one_star;
        var three_star = two_star + one_star;
        var four_star = three_star + one_star;
        var five_star = four_star + one_star;
        
        //update the ratings
        var $ratings = $(xmlDoc).find("song").each(function(){
        	var id = $(this).attr("id");
        	var rating = $(this).attr("rating");
        	
        	var stars = one_star;
        	
        	if(rating == 2)
        	{
        		stars = two_star;
        	}
        	else if(rating == 3)
        	{
        		stars = three_star;
        	}
        	else if(rating == 4)
        	{
        		stars = four_star;
        	}
        	else if(rating == 5)
        	{
        		stars = five_star;
        	}
        	
        	$("#" + id).find("td:nth-child(5)").html(stars);	
        });
        
        
    }
    else 
    {
    	$("#dialogLogin").dialog("enable");
    	
    	var $divMessage = $("#divMessageLogin");
    	
    	$divMessage.text("invalid user id/password combination.");
    	$divMessage.css("color", "red");
    	$divMessage.show();
    }
}

function doRegister() 
{
    var user_name = $("#dialogRegister #txtUserId").val();
    var password = $("#dialogRegister #txtPassword").val();
    var password2 = $("#dialogRegister #txtPassword2").val();
    var email = $("#dialogRegister #txtEmail").val();

    var $divMessage = $("#divMessageRegister");

    //error checking
    if (user_name == "" || password == "" || password2 == "" || email == "") 
    {
        //all fields are required
    	$divMessage.text("all fields are required.");
    	$divMessage.show();
        
        return;
    }

    if (password != password2) 
    {
        //all fields are required
    	$divMessage.text("your passwords must match.");
    	$divMessage.show();
        return;
    }

    var validPath = /^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9])+(\.[a-zA-Z0-9_-]+)+$/

    if (!email.match(validPath)) 
    {
        //all fields are required
    	$divMessage.text("enter a valid email address.");
    	$divMessage.show();
        return;
    }
    
    //disable register dialog
    $("#dialogRegister").dialog("disable"); 
    $divMessage.hide();
    
    $.ajax({
    	type: "POST",
    	url: "php/action.php",
    	data: "action=register&user_name=" + escape(user_name) + "&password=" + escape(password) + "&email=" + escape(email),
    	success: function(msg)
    	{
    		register_callback(msg);
    	}
    });
}

function register_callback(xml) 
{
	var xmlDoc = xml;

    var blnStatus = $(xmlDoc).find("allow").text();
    var msg = $(xmlDoc).find("msg").text();
    
    if (blnStatus == "true") 
    {
    	$("#dialogRegister").dialog("close"); 
    	
    	$("#dialogConfirmation").dialog("open");

    	var $divMessage = $("#divMessageConfirmation");
        $divMessage.text(msg);
        $divMessage.show();
    }
    else 
    {
    	$("#dialogRegister").dialog("enable");
    	
    	var $divMessage = $("#divMessageRegister");
    	$divMessage.text(msg);
    	$divMessage.show();
    }
}

function setMessage(val, id) 
{
	var divMessage;
	
	if(id == null || id == "")
	{
	    divMessage = d.getElementById("divMessage");
	    
	}
	else
	{
		divMessage = d.getElementById(id);
	}
	
	divMessage.firstChild.nodeValue = val;
    divMessage.style.visibility = "visible";
}

function logout() 
{
    if (d.getElementById("spanLogout").firstChild.nodeValue == "login") 
    {
        //alert("do login");
        //showLogin();
    	openDialog("login");
    }
    else 
    {
        //delete the user cookie.. and update the welcome.. and update the logout to say login
        removeCookie("isc_key");

        if (d.getElementById("spanUser").firstChild) 
        {
            d.getElementById("spanUser").firstChild.nodeValue = "";
        }

        if (d.getElementById("spanPts").firstChild) 
        {
            d.getElementById("spanPts").firstChild.nodeValue = "";
        }

        d.getElementById("spanLogout").firstChild.nodeValue = "login";

        //reset email hidden field
        d.getElementById("hidEmail").value = "";

        //reset stars to 0
        initStars(0);
        
        $.ajax({
        	type: "POST",
        	url: "php/action.php",
        	data: "action=logout",
        	success: function(msg)
        	{
        		//alert("logged out!");
        		//remove all the stars
	        	$("#tbodySongs tr").each(function(){
	        		$(this).find("td:nth-child(5)").html("--");
	        	});
        	}
        });
    }
}



function showPoints(points) 
{
    if (d.getElementById("spanPts").firstChild) 
    {
        d.getElementById("spanPts").firstChild.nodeValue = "(" + points + ")";
    }
    else 
    {
        d.getElementById("spanPts").appendChild(d.createTextNode("(" + points + ")"));
    }
}

function setStats(avg, votes) 
{
    if (avg == "" || avg == "0") 
    {
        d.getElementById("spanAvg").firstChild.nodeValue = "--";
    }
    else 
    {
        d.getElementById("spanAvg").firstChild.nodeValue = roundAvg(avg);
    }

    var ratings = "ratings";

    if (votes == "1") 
    {
        ratings = "rating";
    }

    d.getElementById("spanVotes").firstChild.nodeValue = votes + " " + ratings;
}

function showComments()
{
    d.getElementById("spanLyrics").firstChild.nodeValue = "lyrics";
    d.getElementById("divPostedComments").style.display = "";
    d.getElementById("divLyrics").style.display = "none";
}

function showLyrics()
{
    //if user clicked 'lyrics' show lyrics view
    if (d.getElementById("spanLyrics").firstChild.nodeValue == "lyrics")
    {
        d.getElementById("spanLyrics").firstChild.nodeValue = "comments";
        //d.getElementById("spanSaySomething").firstChild.nodeValue = " ";
        d.getElementById("divPostedComments").style.display = "none";
        d.getElementById("divLyrics").style.display = "";

        getLyrics();
    }
    //'if user clicked 'comments' return to comments view
    else
    {
        //d.getElementById("spanSaySomething").firstChild.nodeValue = "say something...";
        d.getElementById("spanLyrics").firstChild.nodeValue = "lyrics";
        d.getElementById("divPostedComments").style.display = "";
        d.getElementById("divLyrics").style.display = "none";
    }
}

function getLyrics()
{
    var song_id = getSongId($("#hidSongId").val());
    
    $.ajax({
    	type: "POST",
    	url: "php/action.php",
    	data: "action=getLyrics&song_id=" + song_id,
    	success: function(msg)
    	{
    		getLyrics_callback(msg);
    	}
    });
}

function getLyrics_callback(xml)
{
	var xmlDoc = xml;
	//alert(xmlDoc);
    var lyrics = $(xmlDoc).find("lyrics").contents().text();
    //alert(lyrics);
    lyrics = replaceSpecialChars(lyrics);
    
    //alert("lyrics-->" + lyrics);
    
    var user = getXmlNode(xmlDoc, "user");
    var date = getXmlNode(xmlDoc, "date_uploaded");
    
    var blnLyrics = true;

    if (lyrics == "")
    {
    	blnLyrics = false;
    	lyrics = "<span>no lyrics posted! click <span id='spanAddLyrics' class='clickable' onclick='openDialog(\"lyrics\");'>here</span> to upload.";
    }
    
    var tbl = d.getElementById("tbodyLyrics");

    clearTable("tbodyLyrics");
    
    var tr = tbl.appendChild(d.createElement("tr"));
    var td = tr.appendChild(d.createElement("td"));
    td.className = "sotdText";

    var div = d.createElement("div");
    div.className = "divComment";

    var divAuthor = div.appendChild(d.createElement("div"));
    divAuthor.className = "divLyrics";

    var img = d.createElement("img");
    img.src = "img/comment.png";
    img.className = "imgComment";

    divAuthor.appendChild(img);

    var spanAuthor = divAuthor.appendChild(d.createElement("span"));
    spanAuthor.className = "spanAuthor";
    spanAuthor.appendChild(d.createTextNode("..lyrics.."));
    
    var divLyrics = div.appendChild(d.createElement("div"));
    
    //draw the lyrics in the comment box
    var spanLyrics = divLyrics.appendChild(d.createElement("div"));
    spanLyrics.className = "spanCommentText";
    
    spanLyrics.innerHTML = lyrics;
    
    if(user != "")
    {
    	divLyrics.appendChild(d.createElement("br"));
    	
	    var divNotes = div.appendChild(d.createElement("div"));
	    divNotes.className = "divLyrics";
	    
	    var spanUser = divNotes.appendChild(d.createElement("span"));
	    spanUser.className = "spanNotes";
	    spanUser.appendChild(d.createTextNode("uploaded by: " + user));
	    
	    var spanDate = divNotes.appendChild(d.createElement("span"));
	    spanDate.className = "spanNotes";
	    spanDate.appendChild(d.createTextNode(" - " + date));
    }
    
    td.appendChild(div);
}

function uploadLyrics()
{
	var $divMessage = $("#divMessageUpload");
	//error check.. make sure the user entered something
	//make sure the user is logged in
	var isc_key = readCookie("isc_key");
	
	if(isc_key == null || isc_key == "" || isc_key == "anonymous")
	{
		//$divMessage.text("you must be logged in...");
		//$divMessage.show();
		openDialog("login");
		return;
	}
	
	//get the current song_id
	var song_id = getSongId($("#hidSongId").val());
	
	var lyrics = $("#txtLyrics").val();
	
	lyrics = replaceLineBreaks(lyrics);

	if(lyrics == "")
	{
		$divMessage.text("you must enter the lyrics...");
		$divMessage.show();
		return;
	}
	
	$divMessage.text("uploading lyrics...");
	$divMessage.css("color", "black");
	$divMessage.show();
	
	$("#dialogLyrics").dialog("disable");
	//make sure user is actually logged in... etc
	
	$.ajax({
		type: "POST",
		url: "php/action.php",
		data: "action=postLyrics&song_id=" + escape(song_id) + "&lyrics=" + escape(lyrics),
		success: function(msg)
		{	
			var $msg = $(msg);
			
			var error = $msg.find("error").text();
			
			if(error != "")
			{
				alert("error --> " + error);
			}
			
			var lyrics = $msg.find("lyrics").text();
			var user_name = $msg.find("userName").text();
			var date = $msg.find("date").text();
			
			var html = "<span>" + lyrics + "</span><br /><br />";
			html += "<div class='divLyrics'>";
			html += "<span class='spanNotes'>uploaded by: " + user_name + "</span>";
			html += "<span class='spanNotes'> - " + date + "</span>";
			html += "</div>"
			
			$("#tblLyrics .spanCommentText").html(html);
			
			closeDialog("lyrics");
		}
	});
}

//////////////
///UTILS.JS
//////////////

function getXmlNode(xml, name)
{
    var value = "";
    
    if(xml)
    {
        var nodes = $(xml).find(name);
        
        if(nodes && nodes.length > 0 && nodes[0].firstChild)
        {
            value = nodes[0].firstChild.nodeValue;
        }
    }
    return value;
}

function clearTable(tbodyId)
{
	var tbody = d.getElementById(tbodyId);

    	var element;

    	while(element = tbody.firstChild)
    	{
        	tbody.removeChild(element);
    	}
}

function escapeSpecialChars(str)
{
    var index = 0;

    //replace ampersand
    while(index < str.length && str.indexOf("&", index) >= 0)
    {
        index = str.indexOf("&", index);
        
        //split the string at the index
        var str1 = str.substr(0, index + 1);
        var str2 = str.substring(index + 1, str.length)
        
        str = str1 + "amp;" + str2;
        index = index + 4;
    }
    
    //replace >
    while(str.indexOf(">") >= 0)
    {
        str = str.replace(">", "&gt;");
    }
    
    //replace <
    while(str.indexOf("<") >= 0)
    {
        str = str.replace("<", "&lt;");
    }
    
    //replace %
    while(str.indexOf("%") >= 0)
    {
        str = str.replace("%", "&#37;");
    }
    
    //replace '
    while(str.indexOf("'") >= 0)
    {
        str = str.replace("'", "&apos;");
    }
    
    //replace \
    while(str.indexOf("\"") >= 0)
    {
        str = str.replace("\"", "&quot;");
    }
    
    //alert(str);
    return str;
}

function escapeforXML(str)
{
	var re = new RegExp("&", "g");
	str = str.replace(re, "&amp;");
    
	var re1 = new RegExp(">", "g");
	str = str.replace(re1, "&gt;");
    
	var re2 = new RegExp("<", "g");
	str = str.replace(re2, "&lt;");
    
	var re3 = new RegExp("'", "g");
	str = str.replace(re3, "&apos;");
    
	var re4 = new RegExp("\"", "g");
	str = str.replace(re4, "&quot;");
    
    return str;
}

function replaceSpecialChars(str)
{
    var index = 0;
	
    while(str.indexOf("&gt;") >= 0)
    {
        str = str.replace("&gt;", ">");
    }
	//str.replace(/&gt;/g, ">");
    
    while(str.indexOf("&lt;") >= 0)
    {
        str = str.replace("&lt;", "<");
    }
	//str.replace(/&lt;/g, "<");
	
    while(str.indexOf("&#37;") >= 0)
    {
        str = str.replace("&#37;", "%");
    }
    //str.replace(/&#37;/g, "%");
	
    while(str.indexOf("&apos;") >= 0)
    {
        str = str.replace("&apos;", "'");
    }
    //str.replace(/&apos;/g, "'");
	
    while(str.indexOf("&quot;") >= 0)
    {
        str = str.replace("&quot;", "\"");
    }
    //str.replace(/&#37;/g, "%");
	
    str = replaceAmps(str);
    
    return str;
}

function replaceAmps(str)
{
    while(str.indexOf("&amp;") >= 0)
    {
        str = str.replace("&amp;", "&");
    }
    
    return str;
}

function checkForHTML(str) 
{
	//URLs starting with http://, https://, or ftp://
    var replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
    var replacedText = str.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');

    //URLs starting with www. (without // before it, or it'd re-link the ones done above)
    var replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
    var replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');

    //Change email addresses to mailto:: links
    var replacePattern3 = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;
    var replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');

    return replacedText;
}

function getWindowSize()
{
    var myWidth = 0, myHeight = 0;
    
    if( typeof( window.innerWidth ) == "number" ) 
    {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } 
    else if(d.documentElement && (d.documentElement.clientWidth || d.documentElement.clientHeight)) 
    {
        //IE 6+ in 'standards compliant mode'
        myWidth = d.documentElement.clientWidth;
        myHeight = d.documentElement.clientHeight;
    } 
    else if(d.body && (d.body.clientWidth || d.body.clientHeight)) 
    {
        //IE 4 compatible
        myWidth = d.body.clientWidth;
        myHeight = d.body.clientHeight;
    }
    
    return [myWidth, myHeight];
}

function createCookie(name,value,days) 
{
	if (days) 
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else
	{   
	    var expires = "";
	}
	
	d.cookie = name+"="+value+expires+"; path=/";
}

function removeCookie(name) 
{
	///createCookie(name, "", -1);
}

function readCookie(name) 
{
	var nameEQ = name + "=";
	var ca = d.cookie.split(';');
	
	for(var i=0;i < ca.length;i++) 
	{
		var c = ca[i];
		while (c.charAt(0)==' ')
		{ 
		    c = c.substring(1,c.length);
		}
		
		if (c.indexOf(nameEQ) == 0)
		{ 
		    return c.substring(nameEQ.length,c.length);
		}
	}
	
	return null;
}

function getDomain()
{
    //look at the current domain
    if(document.domain == "grant.blacklightnewmedia.com")
    {
        return "grant.blacklightnewmedia.com/sotd";
    }
    else
    {   
    	if(document.domain == "localhost")
    	{
    		return "localhost/indiestreetcred";
    	}
    	
    	return document.domain;
    }
}

function findPos(obj) 
{
	var curleft = curtop = 0;
	if (obj.offsetParent) 
	{
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		
		while (obj = obj.offsetParent) 
		{
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	
	return [curleft,curtop];
}

function roundAvg(avg)
{
    return Math.round(avg*10)/10;
}

function getAlbumArt(id)
{
    var tr = d.getElementById(id);
    
    if(tr == null)
    {
        return "";
    }
    
    var hiddens = tr.getElementsByTagName("input");
    
    //albumart is the second
    return hiddens[1].value;
}

function getFullAlbumText(id)
{
    var tr = d.getElementById(id);
    
    if(tr == null)
    {
        return "";
    }
    
    var spans = tr.getElementsByTagName("span");
    
    var artist = spans[1].firstChild.nodeValue;
    var album = spans[2].firstChild.nodeValue;
    
    return artist + " - " + album;
}

function replaceLineBreaks(text)
{
	return text.replace(/(\r\n|\n|\r)/gm, " <br>");
}


/////////
//RATE.JS
/////////
var img;
var opacity;
var points;

function initStars(star)
{
	setStars(star);
}

function fade()
{   
	if(opacity < .1)
	{
		//img.style.opacity = 0;
		//img.style.filter = "alpha(opacity=" + 0 + ")";
		d.body.removeChild(img);
		
		//show the updated points here?
		if(points != "--")
        {
            showPoints(points);
        }
		return;
	}
	
	img.style.opacity = opacity;
	img.style.filter = "alpha(opacity=" + opacity * 100 + ")";
	opacity = opacity - .03;
	img.style.top = (img.style.top.substring(0,img.style.top.length - 2) - 3) + "px";
	setTimeout(fade, 15);
}

function addRating(rating)
{
    var song_id = getSongId($("#hidSongId").val());
    
    //get user id
    var isc_key = readCookie("isc_key");
    
    if(!isc_key)
    {
        initStars(0);
        openDialog("login");
        return;
    }
    
    $.ajax({
        type: "POST",
        url: "php/action.php",
        data: "action=addRating&isc_key=" + isc_key + "&song_id=" + song_id + "&rating=" + rating,
        success: function(msg)
        {
            rating_callback(msg);
        }
    });
}

function updateRatings(song_id, rating)
{
	var one_star = "<img src='img/dark_gray.gif'/>";
    var two_star = one_star + one_star;
    var three_star = two_star + one_star;
    var four_star = three_star + one_star;
    var five_star = four_star + one_star;
    	
	var stars = one_star;
	
	if(rating == 2)
	{
		stars = two_star;
	}
	else if(rating == 3)
	{
		stars = three_star;
	}
	else if(rating == 4)
	{
		stars = four_star;
	}
	else if(rating == 5)
	{
		stars = five_star;
	}
	
	$("#" + song_id).find("td:nth-child(5)").html(stars);
	
	$("#tblSongs").tablesorter();
}

function rating_callback(xml)
{
	var xmlDoc = xml;
    
    var avg = xmlDoc.getElementsByTagName("avg")[0];
    var votes = xmlDoc.getElementsByTagName("votes")[0];
    
    var rating = $(xmlDoc).find("rating").text();
    var song_id = $(xmlDoc).find("id").text();
    
    updateRatings(song_id, rating);
    
    avg = avg.firstChild.nodeValue;
    
    d.getElementById("spanAvg").firstChild.nodeValue = roundAvg(avg);
    
    var votes_text = votes.firstChild.nodeValue;
    
    var ratings = "ratings";
    
    if(votes_text == "1")
    {
        ratings = "rating";
    }
    
    d.getElementById("spanVotes").firstChild.nodeValue = votes_text + " " + ratings;
    
    var iscp = getXmlNode(xmlDoc, "iscp");
    points = getXmlNode(xmlDoc, "points");
    
    if(iscp == "true")
	{
	    if(d.getElementById("img"))
	    {
		    d.body.removeChild(document.body.removeChild(document.getElementById("img")));
	    }
	    
	    //create the image
	    img = document.createElement("img");
	    img.id = "img";
	    img.src = "img/plus_1.png";
	    img.style.position = "absolute";
	    img.onload = animatePoint();
	}
}

function animatePoint()
{
    var coords = findPos(d.getElementById("spanRating"));

    img.style.top = coords[1] - 20 + "px";
    img.style.left = coords[0] + 70 + "px";
	
    d.body.appendChild(img);
    opacity = 1;
    fade();
}

var sMax; // Isthe maximum number of stars
var holder; // Is the holding pattern for clicked state
var preSet; // Is the PreSet value onces a selection has been made
var rated;

function rating(num)
{
     sMax = 0; // Isthe maximum number of stars
     for(n=0; n<num.parentNode.childNodes.length; n++)
     {
         if(num.parentNode.childNodes[n].nodeName.toLowerCase() == "a")
         {
            sMax++;
         }
     }
     
     s = num.id.replace("_", ''); // Get the selected star
     a = 0;
     for(i=1; i<=sMax; i++)
     {
         if(i<=s)
         {
             document.getElementById("_"+i).className = "on";
             holder = a+1;
             a++;
        }
        else
        {
            document.getElementById("_"+i).className = "";
        }
    }
}

function off(me)
{
     if(!preSet)
     {
         for(i=1; i<=sMax; i++)
         {
            document.getElementById("_"+i).className = "";
         }
     }
     else
     {
         rating(preSet);
     }
}

// When you actually rate something
function rateIt(me)
{
    preSet = me;
    sendRate(me);
    rating(me);
}

function sendRate(sel)
{
    var s = sel.id.replace("_", ''); // Get the selected star
    addRating(s);
}

function setNewStar(val)
{
    var star = document.getElementById("_" + val);
    rating(star);
}

function setStars(val)
{
    if(val == 0)
    {
        var star = d.getElementById("_1");
        rating(star);
        
        //now set the class of the first star
        star.className = "";
    }
    else
    {
        var star = document.getElementById("_" + val);
        rating(star);
    }
}