

$(document).ready(function(){
	
	//Pour le lecteur youtube
	function onYouTubePlayerReady(playerId) {
	    ytplayer = document.getElementById("myytplayer");
	    ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
	}

	function onytplayerStateChange(newState) {
	    alert("Player's new state: " + newState);
	}
	
	//Ajouts playlist
	$(".add_playlist").qtip({
		show: { when: { event: 'click' } },
		hide: { fixed: true, delay: 1000 },
		position: {
			corner: {
				tooltip: 'topMiddle'
			}
		},
		style: { 
			name: 'dark',
			tip: 'topMiddle'
		},
		api: { 
			beforeShow: function() { this.loadContent('/ajax', { action: 'getplaylists' }, 'post'); } 
		},
		content: {
		    url:  '/ajax',
		    data: { action: 'getplaylists' },
		    method: 'post'
		}
	});
	
	$('#search_artist_input').val('');
	$('#contribute_song_name').val('');
	$("#artist_select_add_song").val(0);
	
	//Form contribute
	$('#search_artist_show').click( function() { 
		$('#contribute_select_artist').hide();
		$('#contribute_search_artist').show();
		$("#artist_select_add_song").val(0);
	});
	$('#search_artist_hide').click( function() { 
		$('#contribute_search_artist').hide();
		$('#contribute_select_artist').show();
		$('#search_artist_input').val('');
	});
	$('#search_artist_button').click( function() {
		var artist = $('#search_artist_input').val();
		checkArtist(artist);
	});
	
	//Votes buttons
	makeVotesButtons();
	
	//Search form
	$('#searchTxt').keyup( function () {
		if($('#searchTxt').val().length <= 3 && $('#searchGenre').val() == '' && $('#searchArtist').val() == '' && $('#searchContributor').val() == '') {
			$('#helpSearchTxt').html(" (You need to enter 3 letters minimum)");
		} else {
			$('#helpSearchTxt').html("&nbsp;");
			search($('#searchTxt').val(), $('#searchGenre').val(), $('#searchArtist').val(), $('#searchContributor').val());
		}
	});
	$('.searchElement').change( function () {
		search($('#searchTxt').val(), $('#searchGenre').val(), $('#searchArtist').val(), $('#searchContributor').val());
	});

});

//ShowPlaylists
function showPlaylists() {
	jQuery.ajax({
		type: "POST",
		url: "/ajax",
		data: "action=showplaylists",
		success: function(html){
			$(".listPlaylists").html(html);
			$(".listPlaylists").fadeIn();
			$(".listPlaylists").bind('mouseleave', function() {
				$(this).fadeOut();
			});
		}
	});
}

//Open player
function openPlaylist(playlistId) {
	//290px de large et 280px de hplaylistaut
	w = 400;
	h = 420;
	url = '/player?playlist=' + playlistId;
	sw = screen.availWidth - w - 40;
	win = window.open(url,'GothicListPlaylist','width='+w+',height='+h+',top=100,left='+sw+',scrollbars=0,resizable=1,status=0,toolbar=0,location=0,menubar=0,directories=0');
	win.focus();
}

function makeVotesButtons() {
	//Connected vote image
	$('img.imgVote').hover(
			function () {
				$(this).parent().children('.msgVote').html("Click to vote !");
				$(this).parent().children('.msgVote').fadeIn();
			}, 
			function () {
				$(this).parent().children('.msgVote').fadeOut();
	});
	
	//Not connected vote image
	$('input.imgVote').hover(
		function () {
			$(this).parent().parent().children('.msgVote').html("Click to vote !");
			$(this).parent().parent().children('.msgVote').fadeIn();
		}, 
		function () {
			$(this).parent().parent().children('.msgVote').fadeOut();
	});
	
	//Connected voted image
	$('.imgVoted').hover(
		function () {
			$(this).parent().children('.msgVote').html("Delete my vote !");
			$(this).parent().children('.msgVote').fadeIn();
			$(this).attr("src","/public/img/cross.png");
		}, 
		function () {
			$(this).parent().children('.msgVote').fadeOut();
			$(this).attr("src","/public/img/award_star_gold_3.png");
	});
}
function search(txt, genre, artist, contributor) {
	searchtxt = uriEncode(txt);

	jQuery.ajax({
		type: "POST",
		url: "/ajax",
		data: "action=search&searchTxt=" + txt + "&genre=" + genre + "&artist=" + artist + "&contributor=" + contributor,
		success: function(html){
			$("#searchResults").html(html); 
			//$("#searchResults").trigger("update");
			//if(jQuery.trim(html) != '') {
				CB_Init();
				makeVotesButtons();
			//}
			//var sorting = [[0,1]]; 
			//$("#searchResults").trigger("sorton",[sorting]); 
		}
	});
}

function resetFormAddSong() {
	$('#contribute_search_artist').hide();
	$("#artist_select_add_song").val(0);
	$("#accordion_add_song").accordion("activate", 0);
	$('#contribute_select_artist').show();
	$('#search_artist_input').val('');
	$('#contribute_song_name').val('');
	$("#recap_song").html(''); 
	$("#recap_artist").html('');
}

function validArtistAddSong() {
	if($("#artist_select_add_song").val() == 0 && $('#search_artist_input').val() == '') {
		alert('Please choose an artist.');
		return false;
	}
	
	if($("#artist_select_add_song").val() != 0 && $('#search_artist_input').val() != '') {
		alert('Please choose an artist in selectbox or in the field but not both.');
		return false;
	}
	
	if($("#artist_select_add_song").val() != 0) {
		$("#accordion_add_song").accordion("activate", 1);
	} else {
		var artist = $('#search_artist_input').val();
		checkArtist(artist);
	}
}

function validSongAddSong() {
	if($('#contribute_song_name').val() == '') {
		alert('Please enter a song name.');
		return false;
	}
	
	if($("#artist_select_add_song").val() == 0 && $('#search_artist_input').val() == '') {
		alert('Please choose an artist.');
		return false;
	}
	
	if($("#artist_select_add_song").val() != 0 && $('#search_artist_input').val() != '') {
		alert('Please choose an artist in selectbox or in the field but not both.');
		return false;
	}
	
	if($("#artist_select_add_song").val() != 0) {
		var artist = $("#artist_select_add_song").val();
		var artistText = $("#artist_select_add_song option:selected").text().trim();
	} else {
		var artist = $('#search_artist_input').val();
		var artistText = $('#search_artist_input').val();
	}
	
	var song = $('#contribute_song_name').val();
	checkSong(song, artist, artistText);
}

function uriEncode(string) {
	string = encodeURI(string);
	string = string.replace(/,/g,'%2C');
	string = string.replace(/\?/g,'%3F');
	string = string.replace(/:/g,'%3A');
	string = string.replace(/@/g,'%40');
	string = string.replace(/�/g,'c');
	string = string.replace(/&/g,'%26');
	string = string.replace(/=/g,'%3D');
	string = string.replace(/\+/g,'%2B');
	string = string.replace(/\$/g,'%24');
	return string;
}

function checkSong(song, artist, artistText) {
	song = uriEncode(song);
	artist = uriEncode(artist);
	
	jQuery.ajax({
		type: "POST",
		url: "/ajax",
		data: "action=checkSong&song=" + song + "&artist=" + artist,
		success: function(msg){
			if(jQuery.trim(msg) == 'NO') {
				var songName = $('#contribute_song_name').val();
				$("#recap_song").html(songName); 
				$("#recap_artist").html(artistText);
				$("#accordion_add_song").accordion("activate", 2);
			} else {
				alert(msg);
			}
		}
	});
}

function voteSong(song, user, type, element) {
	var oldSrc = $(element).attr("src");
	$(element).attr("src", "/public/img/loading1.gif");
	
	jQuery.ajax({
		type: "POST",
		url: "/ajax",
		data: "action=voteSong&song=" + song + "&user=" + user + "&type=" + type,
		success: function(msg){ 
			if(!isNaN(jQuery.trim(msg))) {
				if(type == 'vote') {
					$(element).parent().children().eq(0).hide();
					$(element).parent().children().eq(1).show();
					alert('Thanks for supporting this artist !');
				}
				if(type == 'unvote') {
					$(element).parent().children().eq(1).hide();
					$(element).parent().children().eq(0).show();
					$(element).parent().children('.msgVote').html('');
				}
				$(element).parent().children('.nbVotes').html("(" + jQuery.trim(msg) + ")");
			} else {
				alert(msg);
				$(element).parent().children().eq(0).click(function() { return false; });
				$(element).parent().children().eq(0).attr("src","/public/img/exclamation.png");
			}
		}
	});
	
	$(element).attr("src", oldSrc);
}

function checkArtist(artist) {
	artist = uriEncode(artist);
	
	jQuery.ajax({
		type: "POST",
		url: "/ajax",
		data: "action=checkArtist&artist=" + artist,
		success: function(msg){
			if(jQuery.trim(msg) == 'OK') {
				$("#accordion_add_song").accordion("activate", 1);
			} else {
				alert(msg);
				
				//Check si la reponse n'est pas artist existe
				var myKey = /already exists/;
				var myMatch = msg.search(myKey);
				if(myMatch == -1) {
					var answer = confirm("Do you really want to continu with this artist : " + artist + " ?")
					if (answer){
						$("#accordion_add_song").accordion("activate", 1);
					}
				}
			}
		}
	});
}

function addVisit(idSong) {
	jQuery.ajax({
		type: "POST",
		url: "/ajax",
		data: "action=addVisit&idSong=" + idSong
	});
}

function editGenre(idGenre) {
	$('#genre_title_' + idGenre).hide();
	$('#genre_name_' + idGenre).hide();
	$('#edit_modif_genre_' + idGenre).hide();
	$('#modif_genre_name_' + idGenre).show();
	$('#modif_genre_parent_' + idGenre).show();
	$('#submit_modif_genre_' + idGenre).show();
}

function editSong(idSong) {
	$('#song_title_' + idSong).hide();
	$('#edit_modif_song_' + idSong).hide();
	$('#song_youtubeid_' + idSong).hide();
	$('#modif_song_name_' + idSong).show();
	$('#submit_modif_song_' + idSong).show();
	$('#modif_song_youtubeid_' + idSong).show();
}
function openPlayer() {
	window.open ("/player?id=4","mywindow","scrollbars=1,status=1,toolbar=1,location=0,directories=0,menubar=1,resizable=1,width=450,height=700");
}

function addPlaylist(playlistName) {
	if(!playlistName) {
		alert('Playlist not added : no name specified');
	} else {
		$.post("/ajax", { action: "addplaylist", playlist: playlistName },
	    function(data) {
	         alert(data);
	    });
	}
};

function addToPlaylist(idPlaylist) {
	$.post("/ajax", { action: "addtoplaylist", playlistid: idPlaylist, songidtoadd: songToPlaylist },
    function(data) {
         alert(data);
    });
}
