//nowplaying popup
function popUp() {
	window.open("wwwplayer.php", "WWW Player", "status = 0, height = 150, width = 150, resizable = 1");
}
	
$(document).ready(function() {
		$("#wwwPlayer").click(function() {
				popUp();
		});
});

//default 'isLoggedIn' to 0
var isLoggedIn = 0;

//generate stars for reviews
function generateStars(number, songId) {
	//output an image with the correct number of stars
	var totalStars = 5;
	var yellowStars = number;
	var greyStars = totalStars-yellowStars;
	var image = $('<span></span>');
	for (abc = 0; abc < yellowStars; abc++) {
		image.append($('<img>').attr("src","assets/images/star.gif").attr("id",songId + "_avgRating_" + abc));
	}
	for (abc = 0; abc < greyStars; abc++) {
		image.append($('<img>').attr("src","assets/images/stargrey.gif").attr("id",songId + "_avgRating_" + abc));
	}
	return image;
}

//do highlighting, submit user rating, etc
function userRate(theId) {
	var exploded = theId.split('_');
	var songId = exploded["0"];
	var starNum = exploded["2"];
	//update the stars
	for (var abc = 1; abc <= starNum; abc++) {
		$("#" + songId + "_starNum_" + abc + "").attr("src","assets/images/star.gif");
	}
	while (abc < 6) {
		$("#" + songId + "_starNum_" + abc + "").attr("src","assets/images/stargrey.gif");
		abc++;
	}
	//submit the rating for the star the user clicked on
	$.getJSON("/assets/php/serverside/submitSongRating.php", { songId: songId, starNum: starNum }, function(data) {
			//update the avg rating
			for (var i = 0; i < 5; i++) {
				var totalStars = 5;
				var yellowStars = data.avgRating;
				var greyStars = totalStars-yellowStars;
				for (var abc = 0; abc < yellowStars; abc++) {
					$("#" + songId + "_avgRating_" + abc + "").attr("src","assets/images/star.gif");
				}
				while (abc < 5) {
					$("#" + songId + "_avgRating_" + abc + "").attr("src","assets/images/stargrey.gif");
					abc++;
				}
			}
	});
}

function userRating(number, songId) {
	//output an image with the correct number of stars for the existing rating, they can also highlight the stars/click to submit a new rating
	var totalStars = 5;
	var yellowStars = number;
	var greyStars = totalStars-yellowStars;
	var image = $('<span></span>');
	var starNum = "0";
	for (var abc = 0; abc < yellowStars; abc++) {
		starNum++;
		image.append($('<img>').addClass("stars").attr("src","assets/images/star.gif").attr("id",songId + "_starNum_" + starNum).click(function() { userRate($(this).attr("id")); }));
	}
	for (var abc = 0; abc < greyStars; abc++) {
		starNum++;
		image.append($('<img>').addClass("stars").attr("src","assets/images/stargrey.gif").attr("id",songId + "_starNum_" + starNum).click(function() { userRate($(this).attr("id")); }));
	}
	return image;
}

//function to add an album to wishlist
function addToWishList(albumId) {
	var exploded = albumId.split('_');
	var albumId = exploded["1"];
	$.getJSON("/assets/php/serverside/addToWishlist.php", { albumId: albumId }, function(data) {
			$("#dialog").empty();
			$("#dialog").append(data.message);
			popModal("My Wishlist");
			//$("#" + albumId + "").removeClass("addToWishlistOff");
			//$("#" + albumId + "").addClass("addToWishlist");
	});
}

//refresh 'now playing', 'song history'
function updateFrontPage() {
		var artist = $("#nowPlayingArtist").text();
		var currentSongTitle = $("#nowPlayingSong").text();
		$.getJSON("/assets/php/serverside/nowPlayingLookup.php", { currentSongTitle: currentSongTitle }, function(data) {
			if (data.trigger == "yes") {
				//If the trigger is yes, then pull the data and update it on the page
				//fade out image
				$("#nowPlayingImg").fadeOut("normal", function() {
						$("#nowPlayingImg").attr("src","cdcovers/" + data.albumImg + "");
				});
				$("#nowPlayingImg").fadeIn("normal");
				$("#nowPlayingText").fadeOut("normal", function() {
						$("#nowPlayingArtist").empty();
						$("#nowPlayingSong").empty();
						$("#nowPlayingArtist").append(data.artist);
						$("#nowPlayingSong").append(data.song);
				});
				$("#nowPlayingText").fadeIn("normal");
				//update the link
				$(".nowPlayingLink").attr("id","nowPlayingLink_" + data.artist + "");
				$(".nowPlayingLink").unbind();
				$(".nowPlayingLink").click(function() { showArtistsUnderscore($(this).attr("id")); });
				//Now, update the song history!
				for (var i = 1; i < 6; i++) {
					var artist = data["x" + i]["artist"];
					var song = data["x" + i]["song"];
					var album = data["x" + i]["album"];
					var albumURL = data["x" + i]["albumURL"];
					$("#songHistory" + i + "").empty();
					var attachment = ($('<div></div>').append(artist + ' - ' + song).append($('<BR>')).append($('<span></span>').addClass("albumString").append("From the album ").append($('<a></a>').attr("href","#").attr("id","songHistory_" + artist + "").append(album).click(function() { showArtistsUnderscore($(this).attr("id")); }))));
					$("#songHistory" + i + "").append(attachment);
					//$("#songHistory" + i + "").append(artist + ' - ' + song + '<BR><span class=\"albumString\">From the album <a href=\"#\">' + album + '</a></span>');
				}
				//finally, check to see if the 'request queued' piece should be updated
				$.getJSON("/assets/php/serverside/updateRequest.php", {  }, function(requestData) {
						if (requestData.result) {
							$("#requestDisplay").empty();
							$("#requestDisplay").append(requestData.result);
						}
				});
			}
		});
}

//new request function for musicDb
function submitRequest(songId) {
	var exploded = songId.split('_');
	var songId = exploded["1"];
	if (songId) {
		$.getJSON("/assets/php/serverside/requestCheck.php", { songId: songId }, function(data) {
				$("#dialog").empty();
				if (data.valid == "no") {
					$("#dialog").append(data.message);
					popModal();
				}
				if (data.valid == "yes") {
					$("#dialog").append('Your request has been queued and will be played some time in the next few hours. Stay tuned in!');
					popModal();
					$("#requestDisplay").empty();
					$("#requestDisplay").append("Queued request: <B>" + data.song + "</B>");
				}
		});
	}
}

//function to popup a dialog box with the contents of div
function popModal(title) {
	if (!title) {
		title = "Request System";
	}
	$("#dialog").dialog({
			close: function() {
				$(this).dialog('destroy');
			},
			bgiframe: true,
			modal: true,
			draggable: false,
			resizable: false,
			title: title,
			zIndex: 3999
	});
}

//refresh the now playing/song history etc
$(document).ready(function(){
	setInterval ( "updateFrontPage()", 60000 );
});

//submit comment on an album
function submitComment(e) {
	var error;
	var albumId = $(e).attr("id");
	var exploded = albumId.split('_');
	var albumId = exploded["1"];
	var comment = $("#albumComment_" + albumId + "").val();
	//check to see it wasn't blank
	if (!comment) {
		error = "You must enter a comment!";
	}
	if (error) {
		//show the error
		$("#commentError").empty();
		$("#commentError").append(error);
	}
	else {
		//submit the comment
		$("#commentError").empty();
		$.getJSON("/assets/php/serverside/submitComment.php", { albumId: albumId, comment: comment }, function(data) {
				if (data.result == "error") {
					$("#commentError").empty();
					$("#commentError").append(data.message);
				}
				if (data.result == "success") {
					var review = $('<div></div>').addClass("reviews").append(data.message + '<BR><span class="reviewer">Posted by ' + data.username + '</span>');
					$("#reviews_" + albumId + "").prepend(review);
				}
		});

	}	
}

//show comments on musicdb
function showComments(e) {
	//function to show comments on albums
	var albumId = $(e).attr("id");
	var exploded = albumId.split('_');
	var albumId = exploded["1"];
	$(".reviewBox").hide();
	$("#reviews_" + albumId + "").fadeIn();
}

//page changer
var activeId = "listen_body";

$(document).ready(function(){
		$(".navbutton").click(function(){	
				var buttonId = $(this).attr("id");
				//get the first part of the id
				var exploded = buttonId.split('_');
				newActiveId = exploded["0"] + "_body";
				if (newActiveId != activeId) {
					$("#" + activeId + "").hide();
					$("#" + newActiveId + "").fadeIn("normal");
					activeId = newActiveId;
				}
				
		});
});

$(document).ready(function() {
	$('a.albumTip').cluetip({
			splitTitle: '|',
			hoverIntent: {    
				    sensitivity:  3,
				    interval:     50,
				    timeout:      0
				    
			}

	});
});



//flip t-shirt
$(document).ready(function(){
		$("#tshirt").click(function(){
				var current = $(this).attr("src");
				if (current == "assets/images/v5_shirt_front.png") {
					current = "assets/images/v5_shirt_back.png";
				}
				else {
					current = "assets/images/v5_shirt_front.png";
				}
				$(this).attr("src",current);
		});
});

//function to show list of artists on musicdb.php
$(document).ready(function(){
		//check if the user is logged in
		$.getJSON("/assets/php/serverside/checkUser.php", { }, function(userCheck) {
				if (userCheck["isLoggedIn"] == 1) {
					isLoggedIn = 1;
				}
				if (userCheck["isLoggedIn"] == 0) {
					isLoggedIn = 0;	
				}
		});
		$(".musicDbSorter").click(function(){
				var id = $(this).attr("id");
				$("#artistDetails").hide();
				$(".artists_hidden").hide();
				$("#artists_" + id + "").show();
		});
});

//if showArtistPage is attached to an element, it should show the artist page
$(document).ready(function(){
		$(".showArtistPage").click(function(){
				var artist = $(this).attr("id");
				var exploded = artist.split('_');
				var artist = exploded["1"];
				showArtists(artist);
		});
});
//attach it to the latest additions also
$(document).ready(function(){
		$(".albumTip").click(function(){
				var artist = $(this).attr("id");
				var exploded = artist.split('_');
				var artist = exploded["1"];
				showArtists(artist);
		});
});

//and now playing image
$(document).ready(function(){
		$(".nowPlayingLink").click(function(){
				var artist = $(this).attr("id");
				var exploded = artist.split('_');
				var artist = exploded["1"];
				showArtists(artist);
		});
});

//function to run showArtists if you need to pass an _ id
function showArtistsUnderscore(artist) {
	var exploded = artist.split('_');
	var artist = exploded["1"];
	showArtists(artist);
}

//function to show list of artists albums in musicDb
function showArtists(artist) {
	if (activeId != "musicdb_body") {
		$("#" + activeId + "").hide();
		$("#musicdb_body").fadeIn("normal");
		activeId = "musicdb_body";
	}
	//var artist = $(this).text();
	var songList;
	$("#artistDetails").empty();
	$("#artistDetails").append("Listing all albums by <B>" + artist + "</b> played on Digital Gunfire");
	//get the albums
	$.getJSON("/assets/php/serverside/getAlbumList.php", { artist: artist }, function(data) {
		for (i = 0; i < data.num; i++) {
		//show album img, name, buy links etc
		var albumId = data["x" + i]["id"];
		var wrapper = $('<div></div>').addClass("artistDetailsWrapper");
		var artistDetails = $('<div></div>').attr("id", "albumDetails_" + albumId + "").append($('<div></div>').addClass("musicDbAlbumDetails").append($('<div></div>').addClass("floatLeft").append('<img src="cdcovers/' + data["x" + i]["img"] + '" class="albumCover">')).append($('<div></div>').addClass("floatLeft").append($('<div></div>').addClass("pad12Left").append($('<div></div>').addClass("albumTitle").append(data["x" + i]["album"])).append($('<a></a>').attr("href",data["x" + i]["url"]).attr("target","_blank").addClass("smallText").text("Buy this album")).append($('<BR>')).append($('<a></a>').addClass("smallText").attr("href","#").attr("id","albumId_" + albumId + "").text("Add to wishlist").click(function() { addToWishList($(this).attr("id")); })).append($('<P></P>')).append($('<img>').attr("src","assets/images/comment.png").addClass("comments").attr("id","comments_" + albumId + "").click(function(){ showComments(this); })))));
		artistDetails.append($('<div></div>').addClass("clear").append('<!-- -->'));
		//'<div id="albumDetails' + albumId + '"><div class="musicDbAlbumDetails"><div class="floatLeft"><img class="albumCover" src="cdcovers/' + data["x" + i]["img"] + '"></div><div class="floatLeft"><div class="pad12Left"><div class="albumTitle">' + data["x" + i]["album"] + '</div><a href="' + data["x" + i]["url"] + '" target="_blank" class="smallText">Buy this album</A><BR><a href="#" class="smallText">Add to wishlist</a><p><img src="assets/images/comment.png" class="comments" id="comments_' + albumId + '"></div></div><div class="clear"><!-- --></div></div>';
		//create the 'review box'
		var reviewBox = $('<div></div>').addClass("reviewBox").attr("id", "reviews_" + albumId + "");
		//list the reviews in a hidden div
		for (o = 0; o < data["x" + i][albumId]["reviews"]; o++) {
			var review = data[albumId]["x" + o]["review"];
			var reviewer = data[albumId]["x" + o]["reviewer"];
			reviewBox.append($('<div></div>').addClass("reviews").append(review + '<BR><span class="reviewer">Posted by ' + reviewer + '</span>'));
		}
		//add the box for reviews to be posted if the user is logged in
		if (isLoggedIn == 1) {
			reviewBox.append($('<div></div>').append($('<textarea></textarea>').attr("rows", "6").attr("cols","34").addClass("textarea").attr("id","albumComment_" + albumId + "")));
			reviewBox.append($('<button></button>').text('Submit Comment').addClass("submitAlbumComment").attr("id","submitAlbumComment_" + albumId + "").click(function() { submitComment(this); }));
			reviewBox.append($('<div></div>').addClass("error").attr("id","commentError"));
		}
		if (isLoggedIn == 0) {
			reviewBox.append($('<div></div>').text('You must be logged in to post a comment.'));
		}
		//reset songList
		delete songList;
		var songList = ($('<div></div>'));
		//list the tracks
		for (x = 0; x < data["x" + i][albumId]["songs"]; x++) {
			var song = data[albumId]["song" + x];
			var songId = data[albumId]["songId" + x];
			//build the play button
			var playButton = '<span class="flash"><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,47,0" width="20" height="20" id="song' + songId + '"><param name="movie" value="assets/flash/wimpy/wimpy_button.swf" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="high" /><param name="bgcolor" value="#000000" /><param name="wmode" value="transparent" /><param name="flashvars" value="theFile=clips/' + songId + '.mp3&autoplay=no&loopMe=no&playingColor=362A45&arrowColor=00FF00" /><embed src="assets/flash/wimpy/wimpy_button.swf" flashvars="theFile=clips/' + songId + '.mp3&wmode=transparent&buttonStyle=square&autoplay=no&loopMe=no&playingColor=362A45&arrowColor=00FF00&wimpyReg=N21jMXNpJTJBUDIlODAlM0ZpVUFjViU3QlYlMkNxVCUzRUVaJTQwVSUzRW0lM0NTJTVEJTdEJTQwcGElN0I5" width="20" height="20" bgcolor="#FFFFFF" loop="false" menu="false" quality="high" name="song' + songId + '" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object></span>';
			if (x % 2 == 0) {
				var divClass = "songList1";
			}
			else {
				var divClass = "songList2";
			}
			songListAddition = ($('<div></div>').addClass(divClass));       
			songListAddition.append($('<div></div>').addClass("playButton").append(playButton));
			songListAddition.append($('<div></div>').addClass("floatLeftPad2").append($('<div></div>').text(song).addClass("requestSubmit").attr("id", "songId_" + songId).click(function() { submitRequest($(this).attr("id")); })));
			
			//figure out the number of stars to show per rating
			songListAddition.append($('<div></div>').addClass("floatRightPad2").append(generateStars(data[albumId]["songRating" + x],data[albumId]["songId" + x])));
			if (data[albumId]["rated" + x] == "1" && isLoggedIn == "1") {
				songListAddition.append($('<div></div>').addClass("floatRightPad2").append(userRating(data[albumId]["userRating" + x],data[albumId]["songId" + x])));
			}
			if (data[albumId]["rated" + x] == "0" && isLoggedIn == "1") {
				songListAddition.append($('<div></div>').addClass("floatRightPad2").append(userRating("0",data[albumId]["songId" + x])));
			}
			songListAddition.append($('<div></div>').addClass("clear").append("<!-- -->"));
			songList.append(songListAddition);
		}	
		artistDetails.append(reviewBox);
		//build a header
		var header = $('<div></div>').append($('<div></div>').addClass("floatLeftPad2").append("<B>Song Title</B>")).append($('<div></div>').addClass("floatRightPad2").append("&nbsp;&nbsp;<B>Average</B>&nbsp;&nbsp;")).append($('<div></div>').addClass("floatRightPad2").append("<B>Your Rating</B>")).append($('<div></div>').addClass("clear").append("<!-- -->"));
		artistDetails.append(header);
		artistDetails.append(songList);
		wrapper.append(artistDetails);
		$("#artistDetails").append(wrapper);					
		}
	});
	$(".artists_hidden").hide();
	$("#artistDetails").show();
}


//function to show artist details
$(document).ready(function(){
		$(".artistClick").click(function(){
				var artist = $(this).text();
				showArtists(artist);
		});
});				

//function to show wishlist
$(document).ready(function(){
		$("#myWishlist").click(function(){
				//get the wishlist info
				$.getJSON("/assets/php/serverside/getWishlist.php", { }, function(data) {
						$("#dialog").empty();
						if (data.status == "error") {
							$("#dialog").append(data.message);
						}
						else {
							if (data.num != 0) {
								var appendIt = $('<div></div>').addClass("wishList1Header").text("ALBUM");
								var appendIt2 = $('<div></div>').addClass("wishList2Header").text("LINK TO BUY");
								var appendIt3 = $('<div></div>').addClass("wishList2Header").text("DATE ADDED");
								var appendIt4 = $('<div></div>').addClass("clear");
								var finalAppend = $('<div></div>');
								appendIt.appendTo(finalAppend);
								appendIt2.appendTo(finalAppend);
								appendIt3.appendTo(finalAppend);
								appendIt4.appendTo(finalAppend);
								finalAppend.appendTo("#dialog");
								for (var i = 0; i < data.num; i++) {
									//set albumId to pass in delete function
									var albumId = data["x" + i]["albumId"];
									if (i % 2) {
										var alternate = "b";
									}
									else {
										var alternate = "a";
									}
									//$("#dialog").append(data["x" + i]["artist"] + ' - ' + data["x" + i]["album"] + ' (<a href="' + data["x" + i]["url"] + '">Buy this album</a>) ' + data["x" + i]["date"] + '<BR>');
									var appendIt = $('<div></div>').addClass("wishList1").append($('<a></a>').text(data["x" + i]["artist"] + ' - ' + data["x" + i]["album"]));
									var appendIt2 = $('<div></div>').addClass("wishList2").append($('<A></a>').attr("href",data["x" + i]["url"]).text("Buy this album"));
									var appendIt3 = $('<div></div>').addClass("wishList2").text(data["x" + i]["date"]);
									var appendIt4 = $('<div></div>').addClass("clear");
									//added later
									var appendIt5 = $('<Div></div>').addClass("wishList3").append($('<img/>').attr("src","assets/images/cancel.gif").addClass('deleteWishlist').attr("deleteAlbum", data["x" + i]["albumId"]).click(function(){ 
										var albumId = $(this).attr("deleteAlbum"); 
										$("#wishListLine_" + albumId + "").remove(); 
										$.getJSON("/assets/php/serverside/deleteFromWishlist.php", { albumId: albumId }, function(data) {
											//no return		
										});
									}));
									var finalAppend = $('<div></div>').attr("id","wishListLine_" + data["x" + i]["albumId"] + "");
									appendIt.appendTo(finalAppend);
									appendIt2.appendTo(finalAppend);
									appendIt3.appendTo(finalAppend);
									appendIt5.appendTo(finalAppend);
									appendIt4.appendTo(finalAppend);
									finalAppend.appendTo("#dialog");
								}
							}
							else {
								$("#dialog").append('You do not have any albums in your wishlist.');
							}
						}
						$("#dialog").dialog({
								close: function() {
									$(this).dialog('destroy');
								},
								bgiframe: true,
								modal: true,
								draggable: true,
								resizable: true,
								width: 600,
								minWidth: 600,
								title: 'My Wishlist',
								zIndex: 3999
						});
				});
		});
});

//function to search the musicDb
$(document).ready(function(){
		$("#musicDbSearchButton").click(function(){
				var searchString = $("#musicDbSearch").val();
				var category = $("#musicDbSearch_category").val();
				if (searchString) {
					$("#musicDbSearchButton").attr("disabled","disabled");
					$.getJSON("/assets/php/serverside/musicDbSearch.php", { category: category, searchString: searchString }, function(data) {
							$("#artistDetails").empty();
							if (data.num == "0") {
								$("#artistDetails").append("No results found.");
							}
							if (category == "artist") {
								for (i = 0; i < data.num; i++) {
									var append = $('<div></div>').append($('<a></a>').attr("href","#").attr("id","searchResult_" + data["x" + i]["artist"] + "").append(data["x" + i]["artist"]).click(function() { showArtistsUnderscore($(this).attr("id")); }));
									$("#artistDetails").append(append);
								}
							}
							if (category == "album") {
								for (i = 0; i < data.num; i++) {
									var append = $('<div></div>').append($('<a></a>').attr("href","#").attr("id",i + "_" + data["x" + i]["artist"] + "").append(data["x" + i]["artist"] + " - " + data["x" + i]["album"]).click(function() { showArtistsUnderscore($(this).attr("id")); }));
									$("#artistDetails").append(append);
								}
							}
							if (category == "song") {
								
							}
							$("#artistDetails").show();
							$("#musicDbSearchButton").removeAttr("disabled");
					});
				}
		});
});

