﻿function InitSite()
{
    var startAd = $("#banner_800x600")[0];
    if (startAd != undefined)
    {
        $(startAd).remove();
        flashembed("SWFPlayer", { src: "OnlinePlayer.swf", width: 375, height: 40, wmode: "transparent", id: "streamPlayer" });
        window.streamPlayer = $("#streamPlayer")[0];
        SetPromoContent();
    }
    $("body").css("background-color", "#FFF");
}

function SetPromoItem(id, title, url, imgUrl, swfUrl, flvUrl)
{
    var swfId = null;
    var promoItems = $("#Live_MainWin_PromoScrollable").children(".items")[0];
    if (promoItems != undefined)
    {
        if (ValidatePath(flvUrl) == true)
        {
            // inserts promo videos
            var flvDiv = $(document.createElement("div"))[0];
            var divId = "promo" + id.toString() + "_" + Math.round(Math.random() * 10000).toString();
            swfId = "promoFlv" + id.toString() + "_" + Math.round(Math.random() * 10000).toString();
            $(flvDiv).addClass("jqPromoVideo").attr("id", divId);
            $(promoItems).append(flvDiv);
            flashembed(divId, { src: "PromoPlayer.swf", id: swfId, wmode: "opaque" }, { url: flvUrl, clickUrl: escape(url) });
            window[swfId] = $("#" + swfId)[0];
        }
        else if (ValidatePath(swfUrl) == true)
        {
            // inserts promo flash
            var swfDiv = $(document.createElement("div"))[0];
            var swfDivId = "promo" + id.toString() + "_" + Math.round(Math.random() * 10000).toString();
            swfId = "promoSwf" + id.toString() + "_" + Math.round(Math.random() * 10000).toString();
            $(swfDiv).attr("id", swfDivId);
            $(promoItems).append(swfDiv);
            flashembed(swfDivId, { src: swfUrl, id: swfId, wmode: "opaque" }, { clickTag: escape(url) });
        }
        else if (ValidatePath(imgUrl) == true)
        {
            // inserts promo images
            var imgDiv = $(document.createElement("div"))[0];
            $(imgDiv).attr("id", "promo" + id.toString() + "_" + Math.round(Math.random() * 10000).toString()).html("<a href='" + url + "' target='_blank'><img src='" + imgUrl + "' alt='" + title + "' /></a>");
            $(promoItems).append(imgDiv);
        }
    }
}

function ValidatePath(url) {
    var valid = false;
    if (url != undefined) {
        if (url != null) {
            if (isNaN(url)) {
                if (url.length > 0) valid = true;
            }
        }
    }
    return valid;
}

function ContinueLoading()
{
    ConnectTabs("NavTabs_Wrapper", [{ tab: "Main_Tab_AntenaLive", panel: "Live" }, { tab: "Main_Tab_History", panel: "History" }, { tab: "Main_Tab_Playlists", panel: "Playlists"}]);
    ConnectTabs("Live_Info_Wrapper", [{ tab: "Live_Tab_SongInfo", panel: "Live_SongInfo" }, { tab: "Live_Tab_ShowInfo", panel: "Live_ShowInfo"}]);
    ConnectTabs("Live_Panels_Wrapper", [{ tab: "Live_Tab_Shoutbox", panel: "Live_Shoutbox" }, { tab: "Live_Tab_SongLyrics", panel: "Live_SongLyrics" }, { tab: "Live_Tab_SongTrivia", panel: "Live_SongTrivia"}]);

    var promo = null;
    var scItems = $("#Live_MainWin_PromoScrollable").children(".items").children();
    if (scItems.length > 1)
    {
        $("#Live_MainWin_PromoScrollable").scrollable({ circular: true }).autoscroll({ autoplay: true, interval: window.scrollableInterval });
        window.scrollableApi = $("#Live_MainWin_PromoScrollable").data("scrollable");
        window.scrollableApi.onSeek = function ()
        {
            promo = window.scrollableApi.getItems()[window.scrollableApi.getIndex()];
            if ($(promo).hasClass("jqPromoVideo") == true && window.promoVideoReady == true)
            {
                if ($(promo).children().length > 0)
                {
                    window.promoVideo = $(promo).children()[0];
                    ReinitPromoVideo();
                }
            }
        }
    }
    else if (scItems.length == 1)
    {
        promo = scItems[0];
        if ($(promo).hasClass("jqPromoVideo") == true && $(promo).children().length > 0)
        {
            window.promoVideo = $(promo).children()[0];
            setTimeout(ReinitPromoVideo, 500);
        }
    }
}

function ReinitPromoVideo()
{
    if (window.promoVideo != null && $("#Live").is(":visible") == true) window.promoVideo.VideoReset();
}

function ConnectTabs(wrapperId, pairs)
{
    if (wrapperId != null && pairs.length > 0)
    {
	    if (typeof window.ShoutboxAutoScroll == "function") window.ShoutboxAutoScroll();
		var panels = $("#" + wrapperId).children("div");
		for(var i = 0; i < pairs.length; i++)
		{
			var tab   = $("#" + pairs[i].tab)[0];
			var panel = $("#" + pairs[i].panel)[0];
			$(tab).bind("click", { panel: panel, tab: tab }, function (e)
			{
			    if ($(e.data.tab).hasClass("disabled") == false)
			    {
			        $("#Live_MainWin_CurrentTrack").hide();
			        if (e.data.panel.id != "Playlists" && window.youTubePlayer != null) SetStreamPlayerVolume(1);
			        var listItems = $(this).parent().children("li");
			        for (var j = 0; j < listItems.length; j++) listItems[j] == this ? $(listItems[j]).addClass("selected") : $(listItems[j]).removeClass("selected");
			        for (var p = 0; p < panels.length; p++) panels[p] == e.data.panel ? $(panels[p]).show() : $(panels[p]).hide();
			        if (e.data.panel.id == "Live") setTimeout(ReinitPromoVideo, 500);
			    }
			});
		}
	}
}	

function InsertYouTube(containerID, code)
{
    swfobject.embedSWF("http://www.youtube.com/v/" + code + "?enablejsapi=1&playerapiid=ytplayer", containerID, "100%", "100%", "10", null, null, { allowScriptAccess: "always" }, { id: "myytplayer" });
}

function onYouTubePlayerReady(playerId)
{
	ytplayer = document.getElementById("myytplayer");
	ytplayer.addEventListener("onStateChange", "onYouTubeStateChange");
	window.youTubePlayer = ytplayer;
}

function onYouTubeStateChange(newState)
{
    switch (newState) 
    {
        case 1: //playing
            SetStreamPlayerVolume(0);
            break;
        case 0: // ended
        case 2: // paused
            SetStreamPlayerVolume(1);
            break;
        default: break;
    }
}

function SetStreamPlayerVolume(vol)
{
	if(isNaN(vol)) vol = 1;
	if(vol < 0) vol = 0;
	if(vol > 1) vol = 1;
	var streamPlayer = document.getElementById("streamPlayer");
	streamPlayer.SetVolume(vol);
}

function UpdateSongs(songs)
{
	if(songs != undefined)
	{
		if(songs.length > 0)
		{
			UpdateCurrentSong(songs[0]);
			$("#History_Last10").html("").append(GetHistoryList(songs, 10));
		}
	}
}

function UpdateCurrentSong(songData)
{
    var id               = songData.id               != null ? songData.id               : 0;
	var artist           = songData.artist           != null ? songData.artist           : "-";
	var title            = songData.title            != null ? songData.title            : "-";
	var albumTitle       = songData.albumTitle       != null ? songData.albumTitle       : "-";
	var albumImageUrl    = songData.albumImageUrl    != null ? songData.albumImageUrl    : "img/defaultCD100x100.jpg";
	var bigAlbumImageUrl = songData.bigAlbumImageUrl != null ? songData.bigAlbumImageUrl : "img/defaultCD180x180.jpg";
	var buyNowUrl        = songData.buyNowUrl        != null ? songData.buyNowUrl        : "#";
	var grade            = songData.grade            != null ? songData.grade            : 0;
	var like             = songData.like             != null ? songData.like             : 0;

	InitMainWin(artist, title, bigAlbumImageUrl);

	var el_songDetails  = $("#Live_SongInfo_Details")[0];
	var el_album        = $("#Live_SongInfo_AlbumCover")[0];
	var el_buyNow       = $("#Live_SongInfo_BuyNowCover")[0];
	var el_tab_trivia   = $("#Live_Tab_SongTrivia")[0];
	var el_tab_lyrics   = $("#Live_Tab_SongLyrics")[0];
	var el_panel_trivia = $("#Live_SongTrivia")[0];
	var el_panel_lyrics = $("#Live_SongLyrics")[0];

	$(el_album).attr("href", buyNowUrl);
	buyNowUrl.length > 1 ? $(el_buyNow).show() : $(el_buyNow).hide();
	$(el_album).children("img").attr("src", albumImageUrl).attr("alt", artist + ": " + title).show();
	$(el_album).children("img").error(function () { $(this).attr("src", "img/defaultCD100x100.jpg"); });

	var details = "<div>" + title + "</div><div>" + artist + "</div><div>" + albumTitle + "</div>";
    try { id = Number(id); } catch (err) { id = 0; }
	if (id > 0) 
    {
	    try { grade = Number(grade); } catch (err) { grade = 0; }
	    try { like = Number(like); } catch (err) { like = 0; }
	    details += "<ul class=\"jqGrade\">" + CreateGradeInnerHTML(grade, id) + "</ul>";
	    if (window.streamPlayer != null)
        {
            // hide like button if user cannot 'like' anyway
            if (window.streamPlayer.CanLike(id) == true) details += "<p class=\"btnLike\" onclick=\"LikeSong(" + id.toString() + ");\"><span class=\"right\" style=\"position:relative;right:-25px;top:10px;\">(" + like.toString() + ")</span></p>";
	    }
	}

	$(el_songDetails).html(details);
	
	if(songData.trivia != null)
	{
		$(el_tab_trivia).show();
		if($(el_tab_trivia).hasClass("disabled")) $(el_tab_trivia).removeClass("disabled");
		$(el_panel_trivia).children("h2").html(artist + ": " + title);
		$(el_panel_trivia).children("div").html(songData.trivia);
	}
	else
	{
		$(el_tab_trivia).addClass("disabled");
		if($(el_panel_trivia).hasClass("none")) $(el_panel_trivia).addClass("none");
	}
	
	if(songData.lyrics != null)
	{
		$(el_tab_lyrics).show();
		if($(el_tab_lyrics).hasClass("disabled")) $(el_tab_lyrics).removeClass("disabled");
		$(el_panel_lyrics).children("h2").html(artist + ": " + title);
		$(el_panel_lyrics).children("div").html(songData.lyrics);
	}
	else
	{
		$(el_tab_lyrics).addClass("disabled");
		if($(el_panel_lyrics).hasClass("none")) $(el_panel_lyrics).addClass("none");
	}
}

function CreateGradeInnerHTML(grade, id)
{
    var str = "";
    for (var i = 0; i < 5; i++) str += "<li class=\"star" + (i < Math.round(grade) ? " vote" : "") + "\" onclick=\"SetGrade(" + id.toString() + "," + Number(i + 1).toString() + ");\"></li>";
    return str;
}

function GetHistoryList(songs, elements)
{
	var endIndex = elements;
	if(endIndex == 0) endIndex = songs.length;
	var ul = $(document.createElement("li"))[0];
	$(ul).addClass("historyList");
	for(var i = 1; i < endIndex; i++)
	{
		var li = $(document.createElement("li"))[0];
		var img = $(document.createElement("img"))[0];
		$(img).attr("src", songs[i].albumImageUrl).attr("alt", songs[i].albumTitle).error(function () { $(this).attr("src", "img/defaultCD100x100.jpg"); });
		if(songs[i].buyNowUrl != null)
		{
			var a = $(document.createElement("a"))[0];
			$(a).attr("href", songs[i].buyNowUrl).append(img);
			$(li).append(a);
		}
		else
		{
			$(li).append(img);
		}
		var div = $(document.createElement("div"))[0];
		var h3 = $(document.createElement("h3"))[0];
		var p = $(document.createElement("p"))[0];
		$(h3).html(songs[i].title  != null ? songs[i].title  : "N/A");
		$(p).html((songs[i].artist != null ? songs[i].artist : "N/A") + (songs[i].publisher != null ? "<br/>" + songs[i].publisher : ""));
		$(div).append(h3).append(p);
		$(li).append(div);
		$(ul).append(li);
	}
	return ul;
}

function UpdateShowInfo(jsObj)
{
    if (jsObj != null) 
    {
        var title     = jsObj.title;
        var desc      = jsObj.desc;
        var blogUrl   = jsObj.blogUrl;
        var startTime = jsObj.startTime;
        var endTime   = jsObj.endTime;
        var images    = jsObj.images;
        var el_details   = $("#Live_ShowInfo_Details")[0];
        var el_a_showImg = $("#Live_ShowInfo_ShowImg")[0];
        var el_a_showBtn = $("#Live_ShowInfo_ShowBtn")[0];
        if (el_details != undefined)
        {
            $(el_details).html("<span>" + startTime + (String(startTime).length > 1 ? "-" : "") + endTime + "</span><h3>" + title + "</h3><p>" + desc + "</p>");
        }
        if (el_a_showBtn != undefined)
        {
            $(el_a_showImg).attr("href", blogUrl != null ? blogUrl : "#");
            $(el_a_showBtn).attr("href", blogUrl != null ? blogUrl : "#");
            $(el_a_showBtn).children("img").attr("alt", title != null ? title : "");
            $(el_a_showImg).children("img").attr("alt", title != null ? title : "").attr("src", images[0]);
            $(el_a_showImg).children("img").error(function () { $(this).attr("src", "img/defaultShowInfo100x100.jpg"); });
        }
    }
}

function LikeSong(id)
{
    if (window.streamPlayer != null)
    {
        if (window.streamPlayer.CanLike(id) == true) window.streamPlayer.SngLike(Number(id));
    }
}

function SetGrade(id, grade)
{
    if (window.streamPlayer != null) 
    {
        if (window.streamPlayer.CanGrade(id) == true)
        {
            window.streamPlayer.SngGrade(Number(id), Number(grade));
        }
        else
        {
            alert("Već ste ocijenili ovu pjesmu!");
        }
    }
}

function SWFLike(val) { $(".btnLike").remove(); }
function SWFGrade(val, id) { $(".jqGrade").html(CreateGradeInnerHTML(val, id)); }

function InitMainWin(artist, track, coverURL)
{
    var promoContainer = $("#Live_MainWin_Promo")[0];
    var winContainer = $("#Live_MainWin")[0];
    var currentTrack = $("#Live_MainWin_CurrentTrack")[0];
    if(window.scrollableApi != null) window.scrollableApi.stop();
    $(promoContainer).hide();
    $(currentTrack).children("h3").html(artist + ": " + track);
    $(currentTrack).children("img").attr("alt", artist + ": " + track).attr("src", coverURL).error(function ()
    {
        $(this).attr("src", "img/defaultCD180x180.jpg");
    });
    $(currentTrack).show("slide", {}, 500, function ()
    {
        setTimeout(function ()
        {
            $(currentTrack).fadeOut(500, function ()
            {
                $(promoContainer).show();
                if (window.scrollableApi != null)
                {
                    window.scrollableApi.seekTo(0, 0).play();
                }
                else
                {
                    setTimeout(ReinitPromoVideo, 500);
                }
            });
        }, 3000);
    });
}

function ScrollableCTRL(status)
{
    switch (status)
    {
        case "ready":
            window.promoVideoReady = true;
            break;
        case "playStart":
            if(window.scrollableApi != null) window.scrollableApi.stop();
            break;
        case "playStop":
            if (window.scrollableApi != null)
            {
                window.scrollableApi.play();
            }
            else
            {
                setTimeout(ReinitPromoVideo, 500);
            }
            break;
        default: break;
    }
}
