﻿// uses cookiefunctions from common.js
var Playlist =
{
    cookieName: "playlist",
    cookieExpireDays: 30,
    isPlaylistVisible: false,
    itemsCount: 0,
    carousel: null,
    currentlyPlaying: 0,
    totalItems: 0,

    AddToPlaylist: function (id) {
        if (Playlist.IsVideoExistsInPlaylist(id)) {
            var htmlError = '<div class="modalTitle"><h1>Çalma Listesi<h1></div><div class="okayMSGFormat"><p>Bu video çalma listenizde mevcut. Aynı videoyu listenize ekleyemezsiniz.</p></div><div class="popupBtnContain fix"><a href="javascript:void(0);" class="modal-closer btnOne darkBlueBac floatRight">Tamam<span></span></a></div>';
            openDialogWithSetHTML(htmlError);
        }
        else {
            $.get(
                '/ajax/AjaxPublic.ashx?action=getvideodataforplaylist&vId=' + id,
            	function (videoInfo) {
            	    Playlist.AddToPlaylistCookie(videoInfo);
            	    //    Playlist.FillPlaylistFromCookie();
            	    videoInfo = eval('(' + videoInfo + ')');
            	    videoInfo = videoInfo.video;
            	    if (videoInfo != null) {
            	        Playlist.AddToPlaylistCarousel(videoInfo.thumbnail, videoInfo.title, false);
            	        Playlist.ShowPlaylist();
            	    }
            	}
            );
        }
    },

    AddToPlaylist2: function (videoInfo) {
        if (Playlist.IsVideoExistsInPlaylist(videoInfo.video.id)) {
            var htmlError = '<div class="modalTitle"><h1>Çalma Listesi<h1></div><div class="okayMSGFormat"><p>Bu video çalma listenizde mevcut. Aynı videoyu listenize ekleyemezsiniz.</p></div><div class="popupBtnContain fix"><a href="javascript:void(0);" class="modal-closer btnOne darkBlueBac floatRight">Tamam<span></span></a></div>';
            openDialogWithSetHTML(htmlError);
        }
        else {
            videoInfo = Playlist.GetStringFromJson(videoInfo);
            Playlist.AddToPlaylistCookie(videoInfo);
            //    Playlist.FillPlaylistFromCookie();
            videoInfo = eval('(' + videoInfo + ')');
            videoInfo = videoInfo.video;
            if (videoInfo != null) {
                Playlist.AddToPlaylistCarousel(videoInfo.thumbnail, videoInfo.title, false);
                Playlist.ShowPlaylist();
            }
        }
    },

    Carousel_itemLoadCallback: function (crsl, state) {
        Playlist.carousel = crsl;
    },

    AddToPlaylistCarousel: function (thumbnail, title, isCurrentlyPlaying) {
        var itemHTML = '<em';
        if (isCurrentlyPlaying)
            itemHTML += ' class="active" ';

        title = title.replace("\"", "'");
        itemHTML += '><img class="south" src="' + thumbnail + '" alt="' + title + '" title="' + title + '" style="cursor:pointer;" /><span style="cursor:pointer;">Sil</span></em>';

        // get handle to scrollable API 
        var api = $("div.scrollable").scrollable();

        // append new item using jQuery's append() method 
        api.getItemWrap().append(itemHTML);

        // rebuild scrollable and move to the end to see what happened 
        api.reload().end();

        Playlist.itemsCount++;

        Playlist.RefreshRemoveFunctions();

        Playlist.GetCurrentlyPlaying();
    },

    RemoveFromPlaylist: function (index) {
        // get handle to scrollable api 
        var api = $("div.scrollable").scrollable();

        // move in 1 millisecond to the end to see what will happen 
        // api.end(1);

        // remove last item with jQuery's remove() method 
        api.getItems().filter(":eq(" + index + ")").remove();

        // rebuild scrollable and go one step backward 
        api.reload();

        Playlist.RemoveFromCookie(index);
        Playlist.RefreshRemoveFunctions();

        Playlist.itemsCount--;
        Playlist.GetCurrentlyPlaying();

        if (Playlist.itemsCount == 0) {
            Playlist.HidePlaylist();
        }
    },

    RemoveFromCookie: function (index) {
        var cookieVal = readCookie(Playlist.cookieName);
        var newcookieVal = '';
        var startIndex = Playlist.GetNthIndexOf(cookieVal, '{\'video', index);
        var endIndex = Playlist.GetNthIndexOf(cookieVal, '{\'video', index + 1);
        //alert(startIndex + "," + endIndex);

        if (startIndex > 0)
            newcookieVal = cookieVal.substr(0, startIndex);

        if (endIndex > startIndex) {
            newcookieVal += cookieVal.substr(endIndex);
        }

        if (newcookieVal.charAt(newcookieVal.length - 1) == ',')
            newcookieVal = newcookieVal.substr(0, newcookieVal.length - 1);

        //alert(newcookieVal);

        createCookie(Playlist.cookieName, newcookieVal, Playlist.cookieExpireDays);

        var items = eval('({videos: [' + newcookieVal + ']})');
        Playlist.totalItems = items.videos.length;
        Playlist.ShowCurrentAndTotal();
    },

    RefreshRemoveFunctions: function () {
        var itemsCount = $('.items span').length;
        for (var i = 0; i < itemsCount; i++) {
            $('.items span:eq(' + i + ')').unbind('click');
            $('.items span:eq(' + i + ')').click(Playlist.GetRemoveFunction(i));
        }

        for (var i = 0; i < itemsCount; i++) {
            $('.items img:eq(' + i + ')').unbind('click');
            $('.items img:eq(' + i + ')').click(Playlist.GetImageRedirectFunction(i));
        }
    },

    GetRemoveFunction: function (i) {
        return function () {
            Playlist.RemoveFromPlaylist(i);
        };
    },

    GetImageRedirectFunction: function (i) {
        return function () {
            Playlist.GotoUrl(i);
        };
    },

    GetNthIndexOf: function (str, key, occurence) {
        var index = str.indexOf(key);
        if (occurence == 0) {
            return index;
        }
        else {
            occurence--;
            var foundIndex = Playlist.GetNthIndexOf(str.substr(index + 1), key, occurence);
            if (foundIndex > 0) {
                index += foundIndex + 1;
            }
            return index;
        }
    },

    AddToPlaylistCookie: function (json) {
        var cookieVal = readCookie(Playlist.cookieName);
        if (cookieVal == null) {
            cookieVal = '';
        }

        if (cookieVal.length > 0 && json.length > 0) {
            cookieVal += ',';
        }
        cookieVal += json;
        createCookie(Playlist.cookieName, cookieVal, Playlist.cookieExpireDays);

        var items = eval('({videos: [' + cookieVal + ']})');
        Playlist.totalItems = items.videos.length;
        Playlist.ShowCurrentAndTotal();
    },

    IsVideoExistsInPlaylist: function (videoId) {
        var cookieVal = readCookie(Playlist.cookieName);
        if (cookieVal != null && cookieVal != '') {
            var items = eval('({videos: [' + cookieVal + ']})');
            for (var i = 0; i < items.videos.length; i++) {
                var videoIdInCookie = items.videos[i].video.id;
                if (videoIdInCookie == videoId) {
                    return true
                }
            }
        }
        return false;
    },

    FillPlaylistFromCookie: function () {
        var cookieVal = readCookie(Playlist.cookieName);

        if (cookieVal == null) {
            Playlist.HidePlaylist();
        }
        else {
            Playlist.GetCurrentlyPlaying();
            if (cookieVal != '') {
                var items = eval('({videos: [' + cookieVal + ']})');
                if (items.videos.length == 0) {
                    if (Playlist.isPlaylistVisible) {
                        Playlist.HidePlaylist();
                    }
                }
                else {
                    Playlist.ShowPlaylist();
                    for (var i = 0; i < items.videos.length; i++) {
                        var videoInfo = items.videos[i];
                        Playlist.totalItems = items.videos.length;
                        if (videoInfo != null) {
                            videoInfo = videoInfo.video;
                            if (videoInfo != null) {
                                var isCurrentlyPlaying = false;
                                if ((i + 1) == this.currentlyPlaying) {
                                    isCurrentlyPlaying = true
                                }
                                Playlist.AddToPlaylistCarousel(videoInfo.thumbnail, videoInfo.title, isCurrentlyPlaying);
                            }
                        }
                    }
                }
            }
            else {
                Playlist.HidePlaylist();
            }
            Playlist.ShowCurrentAndTotal();
        }
    },

    ShowCurrentAndTotal: function () {
        $('#spnCurrentPlaying').html(this.currentlyPlaying);
        $('#spnTotalItems').html(this.totalItems);
    },

    GetCurrentlyPlaying: function () {
        var isVideoPage = window.location.href.indexOf('http://www.rubidik.com/video/') == 0;
        if (isVideoPage) {
            var videoId = currentVideoId;

            var cookieVal = readCookie(Playlist.cookieName);
            if (cookieVal != null && cookieVal != '') {
                var items = eval('({videos: [' + cookieVal + ']})');
                Playlist.currentlyPlaying = 0;

                for (var i = 0; i < items.videos.length; i++) {
                    var cookieVideoId = items.videos[i].video.id;
                    if (cookieVideoId == videoId) {
                        this.currentlyPlaying = i + 1;
                        Playlist.RefreshRemoveFunctions();
                        break;
                    }
                }
            }
        }
        Playlist.ShowCurrentAndTotal();
    },

    TogglePlaylist: function () {
        $("#playListContent").toggle();

        if (Playlist.isPlaylistVisible == true) {
            Playlist.isPlaylistVisible = false;
            $('#lnkTogglePlaylist').html("Listeyi göster");
            $('#allPlay').addClass("playListContainClose");
        }
        else {
            Playlist.isPlaylistVisible = true;
            $('#lnkTogglePlaylist').html("Listeyi gizle");
            $('#allPlay').removeClass("playListContainClose");
            $('#allPlay').addClass("playListContainOpen");
        }
    },

    ShowPlaylist: function () {
        if (Playlist.isPlaylistVisible == false) {
            Playlist.TogglePlaylist();
        }
    },

    HidePlaylist: function () {
        if (Playlist.isPlaylistVisible == true) {
            Playlist.TogglePlaylist();
        }
    },

    GotoUrl: function (i) {
        if (i < Playlist.totalItems) {
            var cookieVal = readCookie(Playlist.cookieName);

            if (cookieVal == null) {
                Playlist.TogglePlaylist();

            }
            else {
                $('#playlistCarousel').html('');


                if (cookieVal != '') {
                    var items = eval('({videos: [' + cookieVal + ']})');
                    var url = items.videos[i].video.url;
                    window.location = url;
                }
            }
        }
        else {
            var htmlError = '<div class="modalTitle"><h1>Çalma Listesi<h1></div><div class="okayMSGFormat"><p>Çalma listesinde video yok</p></div><div class="popupBtnContain fix"><a href="javascript:void(0);" class="modal-closer btnOne darkBlueBac floatRight">Tamam<span></span></a></div>';
            openDialogWithSetHTML(htmlError);
        }
    },

    GotoNext: function () {
        if (Playlist.currentlyPlaying > 0 && Playlist.currentlyPlaying < Playlist.totalItems) {
            Playlist.GotoUrl(Playlist.currentlyPlaying);
        }
    },

    ClearPlaylist: function () {
        eraseCookie(Playlist.cookieName);

        Playlist.totalItems = 0;
        Playlist.currentlyPlaying = 0;

        Playlist.ShowCurrentAndTotal();

        var api = $("div.scrollable").scrollable();

        // remove last item with jQuery's remove() method 
        api.getItems().remove();

        // rebuild scrollable and go one step backward 
        api.reload();
    },

    GetStringFromJson: function (videoInfo) {
        videoInfo = videoInfo.video;
        var str = "{'video': {'id': '" + videoInfo.id + "', 'title': '" + videoInfo.title.replace('\'', '\\\'') + "', 'thumbnail': '" + videoInfo.thumbnail + "', 'url': '" + videoInfo.url + "' }}";
        return str;
    }
}
