﻿var edit_artist;
var edit_album;
var player_type;
var force_HTML5_player = false;
var force_FLASH_player = false;

function LOG(msg) {
	if(typeof(console) != "undefined") {
		console.log(msg);
	}
}

function inWaiting() {
	$("body").css("cursor", "wait");
	$("<img src='img/spinner.gif' style='padding-left:10px;'/>").appendTo($("#c_body_header").children().eq(0));
}

function getSilverlightVersion() {
	var version = '';
	var container = null;
	try {
		var control = null;
		if (window.ActiveXObject) {
			control = new ActiveXObject('AgControl.AgControl');
		}
		else {
			if (navigator.plugins['Silverlight Plug-In']) {
				container = document.createElement('div');
				document.body.appendChild(container);
				container.innerHTML = '<embed type="application/x-silverlight" src="data:," />';
				control = container.childNodes[0];
			}
		}
		if (control) {
			if (control.isVersionSupported('2.0')) { version = 'Silverlight/2.0'; }
			else if (control.isVersionSupported('1.0')) { version = 'Silverlight/1.0'; }
		}
	}
	catch (e) { }
	if (container) {
		document.body.removeChild(container);
	}
	return version;
}

function createMusicPlayer(sel, uk) {
	if (force_HTML5_player) {
		createHTML5Player();
		return;
	}
	if(force_FLASH_player) {
		createFlashMusicPlayer(uk);
		return;
	}

	var slVersion = getSilverlightVersion();

	if (sel == 1 && slVersion == 'Silverlight/2.0') {
		player_type = "Silverlight";
		$.post("c/plsl.aspx", { rnd: Math.random() }, function(text) {
			if (lf(text) == 1)
				$("#playerContainer").html(text);
		}, "html");
	}
	else {
		createFlashMusicPlayer(uk);
//		$.post("c/plfl.aspx", { rnd: Math.random() }, function(text) {
//			if (lf(text) == 1)
//				$("#playerContainer").html(text);
//		}, "html");
	}
}

function createFlashMusicPlayer(uk) {
	var atts = { id: "clodderplayer" };	
	var params = { allowScriptAccess: "sameDomain", allowFullScreen: false, wmode: "transparent", bgcolor: "#1a50b8" };
	swfobject.embedSWF("clodderfp.swf", "playerContainer", "100%", "60", "10", null, { uk: uk }, params, atts, createFlashMusicPlayer_callbackFn);
}

function createFlashMusicPlayer_callbackFn(e)
{
	if (e.success) {
		player_type = "Flash";
		document.kejkplayer = document.getElementById("clodderplayer")
	}
	else {
		createHTML5Player();
	}
}

function createYTPlayer(videoId)
{
	//alert("YT:" + videoId);
	var ytplayer = document.getElementById("kejkytplayer")
	if (ytplayer) {
		ytplayer.loadVideoById(videoId);
		$.scrollTo("#ytDiv");
	}
	else {
		$(".ytplayerContainer").show();
		var params = { allowScriptAccess: "always" };
		var atts = { id: "kejkytplayer", play: "true" };
		swfobject.embedSWF("http://www.youtube.com/v/" + videoId + "&hl=sv&fs=1&color1=0x2b405b&color2=0xA1CCED&enablejsapi=1&playerapiid=ytplayer",
							"ytapiplayer", "600", "360", "8", null, null, params, atts);
		$.scrollTo("#ytDiv");
	}
}

function onYouTubePlayerReady(playerId) 
{
	var ytplayer = document.getElementById("kejkytplayer");
	if (ytplayer) {
		ytplayer.playVideo();
		ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
	}
	//alert("YT:" + ytplayer);
}

function onytplayerStateChange(newState) {
	//alert("yt play state: " + newState);
	if (newState == 1) {
		//playing ==> paus music
		pausePlayer();
	}
}

function pauseVideo() {
	var ytplayer = document.getElementById("kejkytplayer")
	if (ytplayer) {
		ytplayer.pauseVideo();
	}
}

//---------------------------------
var slPlayer = null;

//Will call player and start current song
function startPlayer() {
	if(xppMode)
		document.location = "clodder:startPlayer";
	else
	{
		if (slPlayer != null)
			slPlayer.Content.Page.startPlaying();
		else {
			if (player_type == "HTML5")
				html5Player_startPlayer();
			else
				document.kejkplayer.startPlaying();
		}
	}
}

//Will call player and pause current song
function pausePlayer() {
	if (slPlayer != null)
		slPlayer.Content.Page.pausePlaying();
	else if (player_type == "HTML5")
		html5Player_pausePlayer();
	else
		document.kejkplayer.pausePlaying();
}

//Will call player and toggle current song
function togglePlayer() {
	if (slPlayer != null)
		slPlayer.Content.Page.togglePlaying();
	else if (player_type == "HTML5")
		html5Player_togglePlayer();
	else
		document.kejkplayer.togglePlaying();
}

//Called when the silverlight player is loaded
function slPlayerLoaded(sender) {
	slPlayer = sender.getHost();
}

//Player will call this when state changes
function onPlayerStateChanged(newState, title) {
	if (newState == 1) {
		document.title = "clodder - " + title;
		$("#bbtitle").html(title);
		$("#bbplay").hide();
		$("#bbpause").show();
		//playing ==> paus video
		pauseVideo();
	}
	else if (newState == 0) {
		document.title = "clodder";
		$("#bbtitle").html("");
		$("#bbplay").show();
		$("#bbpause").hide();
	}
}

//Open website in new window
function oiw() {
	var width = 1050;
	if (screen.availWidth < width)
		width = screen.availWidth;
	var height = 1100;
	if (screen.availHeight-20 < height)
		height = screen.availHeight-20;
	
	window.open("default.aspx?windowed=1", null, "scrollbars=1,resizable=1,status=0,titlebar=0,toolbar=0,width="+width+",height="+height);
	document.location = "dmz/closed.aspx";
}

function getTimeString(date) {
	//var today = new Date();
	var y = date.getFullYear();
	var mo = checkTime(date.getMonth());
	var d = checkTime(date.getDate());
	var h = date.getHours();
	var m = checkTime(date.getMinutes());
	return y + "-" + mo + "-" + d + " " + h + ":" + m;
}

function checkTime(i) {
	if (i < 10) {
		i = "0" + i;
	}
	return i;
}

//var dateStr = '\/Date(-62135578800000-0500)\/'
function convertJsonDate(dateStr)
{
	var okDate = /Date\(([-+]?\d+[-+]?\d+)\)/.exec(dateStr)
	var when = new Date(eval(okDate[1]));
	return when;
}

function bbPlay() {
	togglePlayer();
}

function bbPause() {
	pausePlayer();
}

function initNewPlaylistBallon() {
	$("#playlistBallon button").button();
	$("#newPlOk").click(function() {
		$("#playlistBallon").hide();
		newPlaylist($("#newPlaylistBox").val());
	});
	$("#newPlCancel").click(function() {
		$("#playlistBallon").hide();
	});
	$("#newPlaylistBox").keyup(function() {
		var t = $("#newPlaylistBox").val();
		if(t.length==0)
			$("#newPlOk").button("disable");
		else
			$("#newPlOk").button("enable");
	});

	$("li.playlistItem").droppable({
		hoverClass: 'ui-state-active',
		accept: '.songDragHandle',
		drop: function(event, ui) {
			var plsId = $(this).attr("plsId");
			var songId = ui.draggable.parent().find("li").attr("songId");
			//console.log("drop plsId: " + plsId);
			//console.log("drop songid: " + songId);
			addSongToPlaylist(plsId, songId);
		}
	});
}

function showNewPLBallon() {
	$("#playlistBallon").show();
	$("#newPlaylistBox").val("");
	$("#newPlaylistBox").focus();
	$("#newPlOk").button("disable");
}

function refreshUserPlaylists() {
	$.post("c/userpls.aspx", { rnd: Math.random() }, function(text) {
		if (lf(text) == 1)
			$("#uplsCont").html(text);
		initNewPlaylistBallon();
	}, "html");
}

function newPlaylist(name) {
	$.post("s/newpl.ashx", { name: name, rnd: Math.random() }, function(text) {
		if (lf(text) == 1)
			refreshUserPlaylists();
	}, "html");
}

function deletePlaylist(id) {
	$.post("s/deletepl.ashx", { id: id, rnd: Math.random() }, function(text) {
		if (lf(text) == 1)
			refreshUserPlaylists();
	}, "html");
}

function addSongToPlaylist(plsId, songId) {
	var currentPlsId = $("#pls").attr("plsId");
	if (currentPlsId != plsId) {
		$.post("s/addToPl.ashx", { plsId: plsId, songId: songId, rnd: Math.random() }, function(text) {
		}, "html");
	}
	else {
		$.post("s/addToPl.ashx", { plsId: plsId, songId: songId, flush: 1, rnd: Math.random() }, function(text) {
			if(lf(text) == 1)
				refreshPlaylist();
		}, "html");
	}
}

var createDragHelperHelper = function(songId, name, artName) {
	return $('<li class="plitem_drag" songId="' + songId + '"><div><a>' + name + '</a></div><div class="plart">' + artName + '</div></li>');
}

var createDragHelper = function(event) {
	var artName = $(this).parent().next().children("a").text();
	var name = $(this).text();
	name = name.substr(name.indexOf(".") + 2);
	var songId = $(this).parents("tr").attr("songId");
	//console.log("drag songId: " + _artistName);
	return createDragHelperHelper(songId, name, artName);
}

var createDragHelperArt = function(event) {
	var name = $(this).text();
	name = name.substr(name.indexOf(".") + 2);
	var artName = $("#lblArtistName").text();
	var songId = $(this).parents("tr").attr("songId");
	return createDragHelperHelper(songId, name, artName);
}

//Called from player when pl needs to be refreshed
var playlistTimer;
function refreshPlaylist_old(title) {
	$.post("c/pl.aspx", { rnd: Math.random() }, function(text) {
		if (lf(text) == 1)
			$("#plCont").html(text);
		makePlaylistSortable();
		if (playlistTimer != undefined)
			clearTimeout(playlistTimer);
		playlistTimer = setTimeout("refreshPlaylist()", 5 * 60 * 1000);
	}, "html");
}

//Called from player when pl needs to be refreshed
function refreshPlaylist(title) {
	$.post("c/nowplay.aspx", { rnd: Math.random() }, function (text) {
		if (lf(text) == 1) {
			$("#nowPlayingCont").html(text);
			highlightCurrentSong();
			initRecomendParts();
		}
	}, "html");
}

function initRecomendParts() {
	$("#btnRecomend").button();

	var songId = $("#nowPlaying").attr("songId");
	$("#btnRecomend").click(function () {
		$("#btnRecomend").after("<img src='img/spinner.gif' style='padding-left:10px;'/>");
		$.post("s/songLink.ashx", { id: songId, rnd: Math.random() }, function (text) {
			console.log(text);
			$("#btnRecomend").hide();
			$("#btnRecomend").next().hide();
			$("#pnlRecomendLink").show();
			$("#recomendLink").val(text);
		}, "html");
	});
}

function highlightCurrentSong() {
	var songId = $("#nowPlaying").attr("songId");
	var itemId = $("#nowPlaying").attr("itemId");
	//console.log("songId " + songId);
	//console.log("itemId " + itemId);
	$(".currentSong").removeClass("currentSong");
	$(".currable").each(function(index, element) {
		var cSongId = $(element).attr("songId");
		var cItemId = $(element).attr("itemId");
		//console.log("cItemId " + cItemId);
		//console.log("cSongId " + cSongId);
		if ((cItemId != null && cItemId == itemId) || (cItemId == null && cSongId == songId)) {
			$(element).addClass("currentSong");
		}
	});
}

function makePlaylistSortable() {

	$("#pls").sortable({ start: onSortPlayListStart, stop: onSortPlayListStop });
	$("#pls").disableSelection();

	$(".pl_item").hover(
			function(e) {
				$(this).find(".delpl")
					   .show()
					   .bind("click", deletePlaylistItem);
			},
			function(e) {
				$(this).find(".delpl")
					   .hide()
					   .unbind("click", deletePlaylistItem);
			});
/*
	$("#pls").droppable({
		hoverClass: 'ui-state-active',
		accept: '.songDragHandle',
		drop: function(event, ui) {
			var plsId = $("#pls").attr("plsId");
			var songId = ui.draggable.parent().find("li").attr("songId");
			addSongToPlaylist(plsId, songId);
		}
	});
*/
}

function renumberPlaylist() {
	$(".pl_name").each(function(index, element) {
		var name = $(this).find("a").text();
		name = name.substr(name.indexOf(".") + 2);
		$(this).find("a").text((index + 1) + ". " + name);
	});
}

function deletePlaylistItem() {
	var itemId = $(this).parent().parent().attr("itemId");
	//console.log("itemId: " + itemId);
	delpli(itemId,$(this).parent().parent());
}

function delpli(itemId,li) {
	$.post("s/deleteitem.ashx", { id: itemId, rnd: Math.random() }, function(text) {
		if (lf(text) == 1) {
			$(li).remove();
			renumberPlaylist();
		}
	}, "html");
}

var onSortStartTickCount;
function onSortPlayListStart(event, ui) {
	var now = new Date();
	onSortStartTickCount = now.getTime();
}

function onSortPlayListStop(event, ui) {
	var plsId = $(ui.item).attr("itemId");
	var now = new Date();
	if (now.getTime() - onSortStartTickCount < 100) {
		//To short to be a real move, probably a play
		cs(plsId);
	}
	else {
		var pos = Number($(ui.item).prevAll().length);
		addSpinner(ui.item);
		movePlaylistItem(plsId, pos, ui.item);
	}
}

function addSpinner(to) {
	$("<img src='img/spinner.gif' style='vertical-align: middle;'/>").appendTo($(to).children().eq(0));
}

function removeSpinner(to) {
	$(to).children().eq(0).find("img").remove(); 
}

function movePlaylistItem(plsId, pos, to) {
	$.post("s/moveitem.ashx", { id: plsId, pos: pos, rnd: Math.random() }, function(text) {
		if (lf(text) == 1) {
			removeSpinner(to);
			renumberPlaylist();
		}
	}, "html");
}

function OnFBSessionChange(response) {
	if (response.session) {
		// A user has logged in, and a new cookie has been saved
		//LOG("logging in to " + _landingPageUrl);
		window.location = _landingPageUrl;
	} else {
		// The user has logged out, and the cookie has been cleared
		//console.log("logging out");
	}
}

function logout() {
	if (_fbUserId != undefined) {
		var session = FB.getSession();
		if (session != null) {
			FB.logout(function () {
				window.location = "pages/logout.aspx";
			});
			return;
		}
	}

	window.location = "pages/logout.aspx";
}

function prepareDialogs() {
	$("#dlgImageSearch").dialog({
		autoOpen: false,
		width: 350,
		title: "Sök efter en bild",
		minWidth: 300,
		position: [350, 350]
	});
}

//Called from player when user clicks info
function songInfo(id) {
	var songInfoLink = $("#nowPlaying").attr("songInfoLink");
	plHash(songInfoLink);
}

