$(document).ready(function() {
    var playItem = 0;

    //var playListItems = [];
    var MusicBox = function() {
        $.post('explorer.php', {'dispatch':'get_meta', 'data':myPlayList}, function(data) {
            myPlayList = $.parseJSON(data);

            $("#jquery_jplayer")
	            .jPlayer({
	                ready: function() {
	                    displayPlayList();
	                    playListInit(false); // Parameter is a boolean for autoplay.
	                },
	                oggSupport: true,
	                swfPath: 'jPlayer/js',
	                volume:50,
	                errorAlerts:true,
	                warningAlerts:true
	            })
	            .jPlayer("onProgressChange", function(loadPercent, playedPercentRelative, 
	            		playedPercentAbsolute, playedTime, totalTime) {
	                jpPlayTime.text($.jPlayer.convertTime(playedTime));
	                jpTotalTime.text($.jPlayer.convertTime(totalTime));
	            })
	            .jPlayer("onSoundComplete", function() {
	                playListNext();
	            });
        });
    };

    function setPlaylist() {
        if (musicBoxClass != 'favorites') {
            myPlayList = playListItems;
        } else {
        	setFavoritesAsPlaylist();
        }
    }

    /** MusicBox Favorites **/
    $('.favorite').live('click', function() {
        if (localStorageSupport()) {
            addFavorite($(this).parent('li').attr('id'));        	
        }
    });

    $('.remove-favorite').live('click', function() {
        if (localStorageSupport()) {
            removeFavorite($(this).parent('li').attr('id'));
            $(this).parent('li').remove();
        }
    });

    function addFavorite(song) {
        var favorites = localStorage.getObject('musicBoxFavs');
        favorites = (favorites != null) ? favorites : [];

        var exists = false;
        $.each(favorites, function(key, value) {
            if (value == song)
                exists = true;
        });

        if (!exists) {
            favorites.push(song);       	
        }

        localStorage.setObject('musicBoxFavs', favorites);
    }

    function removeFavorite(song) {
        var favorites = localStorage.getObject('musicBoxFavs');
        favorites = (favorites != null) ? favorites : [];

        $.each(favorites, function(key, value) {
            if (value == song)
                favorites.splice(key, 1);
        });

        setFavoritesAsPlaylist();
        setPlaylist();

        localStorage.setObject('musicBoxFavs', favorites);
    }

    function setFavoritesAsPlaylist() {
        var favorites = localStorage.getObject('musicBoxFavs');
        favorites = (favorites != null) ? favorites : false;

        if (favorites) {
            myPlayList = [];
            $.each(favorites, function(key, value) {
                var ogg = (value.substr(0, value.length - 3)) + 'ogg';
                myPlayList.push({'mp3':value, 'ogg':ogg});
            });
        }
    }

    /**HTML5 Checks **/
    function localStorageSupport() {
        return ('localStorage' in window) && window['localStorage'] !== null;
    }

    /** Local Storage **/
    if (localStorageSupport()) {
        Storage.prototype.setObject = function(key, value) {
            this.setItem(key, JSON.stringify(value));
        };

        Storage.prototype.getObject = function(key) {
            return this.getItem(key) && JSON.parse(this.getItem(key));
        };
    }

    /** Playlist Stuff **/
    var jpPlayTime = $("#jplayer_play_time");
    var jpTotalTime = $("#jplayer_total_time");
    $("#jplayer_previous").click(function() {
        playListPrev();
        $(this).blur();
        return false;
    });

    $("#jplayer_next").click(function() {
        playListNext();
        $(this).blur();
        return false;
    });

    $('.thumb-wall-inner img').live('onload', function() {
        show_thumb($(this));
    });

    function displayPlayList() {
        var playlistClass = $('#main').attr('class');
        $("#jplayer_playlist ol").empty();
        for (i = 0; i < myPlayList.length; i++) {
            var listItem = (i == myPlayList.length - 1) ? "<li id='" + myPlayList[i].mp3 + "' class='jplayer_playlist_item_last'>" : "<li id='" + myPlayList[i].mp3 + "'>";
            var src = 'cover.php?filename=' + myPlayList[i].mp3;
            var fav = (playlistClass != 'favorites') ? '<a  class="favorite tooltip" href="#" >&hearts;</a>' : '';
            var removeFav = (playlistClass == 'favorites') ? '<span class="remove-favorite">x</span>' : '';

            if (playlistClass != 'thumb-wall') {
                listItem += "<a href='#' id='jplayer_playlist_item_" + i + "' tabindex='1'>" + myPlayList[i].name + "</a> - " + myPlayList[i].artist + removeFav + fav + "<span class='track-length'>" + myPlayList[i].play_length + "</span></li>";
            } else {
                var thumb_image = '';
                if (myPlayList[i].cover == 1) {
                    thumb_image = ('<img id="thumb-image-' + i + '"src="' + src + '"/>');
                }

                listItem += "<a href='#' id='jplayer_playlist_item_" + i + "' tabindex='1'><span class='thumb-wall-inner'>" + myPlayList[i].name + "<span class='artist'>" + myPlayList[i].artist + "</span>" + thumb_image + "</span></a>" + fav + "</li>";
            }

            $("#jplayer_playlist ol").append(listItem);

            $("#jplayer_playlist_item_" + i).data("index", i).click(function() {
                var index = $(this).data("index");
                if (playItem != index) {
                    playListChange(index);
                } else {
                    $("#jquery_jplayer").jPlayer("play");
                }
                
                $(this).blur();
                return false;
            });
        }
    }

    function playListInit(autoplay) {
        if (autoplay) {
            playListChange(playItem);
        } else {
            playListConfig(playItem);
        }
    }

    function playListConfig(index) {
        $("#jplayer_playlist_item_" + playItem).removeClass("jplayer_playlist_current").parent().removeClass("jplayer_playlist_current");
        $("#jplayer_playlist_item_" + index).addClass("jplayer_playlist_current").parent().addClass("jplayer_playlist_current");
        playItem = index;
        $("#jquery_jplayer").jPlayer("setFile", myPlayList[playItem].mp3, myPlayList[playItem].ogg);

        $('.info-thumb img').remove();
        if (myPlayList[playItem].cover == 1)
        {
            $('.info-thumb').append('<img src="cover.php?filename=' + myPlayList[playItem].mp3 + '"/>');
        }
    }

    function playListChange(index) {
        playListConfig(index);
        $("#jquery_jplayer").jPlayer("play");
    }

    function playListNext() {
        var index = (playItem + 1 < myPlayList.length) ? playItem + 1 : 0;
        playListChange(index);
    }

    function playListPrev() {
        var index = (playItem - 1 >= 0) ? playItem - 1 : myPlayList.length - 1;
        playListChange(index);
    }

    function show_thumb(thisThumb) {
        thisThumb.fadeIn('fast');
    }

    var myPlayList;
    setPlaylist();
    MusicBox();
});
