var  playlistTotalSongCount = 0;

var currentSelectedSongs = [];

var currentSelectionTotalTime = 0;

var pageCount;

var userArgs = {};

var playlistID;

var available_genres = [];

function savePlaylist(playlist, playlistID, print_pdf) {

    if(print_pdf==1){

        jQuery('.playlist_loading').show();

    }else{

        var imageUrl =  jQuery('.loading_img').attr('datasrc');

        jQuery('.loading_img').html('<img src=" '+imageUrl+'">');

        jQuery('.loading_img').show();

    }

    var pdf_link = jQuery('.avail-playlist-pdf.icon').attr('href');

    jQuery.ajax({

        url: PlaylistAjax.ajaxurl,

        type: "POST",

        data:{

            'action': 'fe-ajax',

            'fn':'save-playlist',

            'playlist':playlist,

            'playlist_id':playlistID,

            'print_pdf':print_pdf,

            'pdf_link':pdf_link,

            'postNonce': PlaylistAjax.postNonce

        },

        dataType: 'json',

        success:function(data){

            var updatedListCount = data.updatedListCount;

            if(print_pdf==1){

                jQuery('.playlist_loading').hide();

                window.open(pdf_link, '_blank');

            }else{

                jQuery('.loading_img').hide();
            }

            if (jQuery('#playlist-selection option[value="' + playlistID + '"]').length == 0) {

                var o1 = new Option(playlistID, playlistID);

                if(playlistID!='Background Music' && playlistID!='Dancing Music'){

                    jQuery('#playlists').find('.save_playlist_select').append(o1);

                }

                jQuery('#playlists option[value="'+playlistID+'"]').text(playlistID +"(Total: "+updatedListCount+")" );

                var o = new Option(playlistID, playlistID);

                jQuery('#playlist-selection').append(o);

                jQuery('#playlist-selection option[value="' + playlistID + '"]').text(playlistID +"(Total: "+updatedListCount+")" );

            }else{

                jQuery('#playlists option[value="'+playlistID+'"]').text(playlistID +  "(Total: "+updatedListCount+")" );

                jQuery('#playlist-selection option[value="' + playlistID + '"]').text( playlistID + "(Total:"+updatedListCount+")" );

            }

            jQuery('#playlist-selection').val(playlistID).trigger("change", false);

            jQuery('#playlist-option-modal').modal('hide');

            jQuery("#playlist-pdf").parent().attr("href", data.pdf_url);

        },

        error: function(errorThrown){

            console.log(errorThrown);

        }

    });

}


function getAvailableGenres(){

    jQuery.ajax({

        url: PlaylistAjax.ajaxurl,

        type: "POST",

        data:{

            'action': 'fe-ajax',

            'fn':'get-available-genres',

            'postNonce': PlaylistAjax.postNonce
        },

        dataType: 'json',

        success:function(data){

            available_genres = data.available_genres;

        },

        error: function(){

            console.log("Error");

        }
    });
}

function ucfirst( str ) {
    // Make a string&#039;s first character uppercase
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    var f = str.charAt(0).toUpperCase();

    return f + str.substr(1, str.length-1);

}

function formatTimeLength(runtime){

    var hours = parseInt( runtime / 3600 ) % 24;

    var minutes = parseInt( runtime / 60 ) % 60;

    var seconds = runtime % 60;

    return  (hours < 10 && hours != 0 ? "0" + hours : hours) + "h " + (minutes < 10 ? "0" + minutes : minutes) + "m " + (seconds  < 10 ? "0" + seconds : seconds) +"s";
}

function querySongs(args) {

    var imageUrl =  jQuery('.playlist_loading').attr('datasrc');

    jQuery('.playlist_loading').html('<img src=" '+imageUrl+'">');

    jQuery('.playlist_loading').show();

    jQuery.ajax({

        url: PlaylistAjax.ajaxurl,

        type: "POST",

        data:{

            'action': 'fe-ajax',

            'fn':'query',

            'postNonce': PlaylistAjax.postNonce,

             'args':args

        },

        dataType: 'json',

        success:function(data){

            jQuery('.playlist_loading').hide();

            pageCount = Math.ceil( data.count / Number( jQuery('#limit-results-selection').val()));

            playlistTotalSongCount = data.count;

            if (pageCount >= 0) {

                jQuery('#total-pages').val(pageCount);

                var page_value = jQuery('.current-page').val().split("/");

                var totalPages = jQuery("#total-pages").val();

                jQuery(".current-page").val(page_value[0]+"/"+totalPages);

            }

            jQuery("#music_selector_results").replaceWith(data.html);

            if(data.count > 800){

                var count_k = ' ~'+ Math.round(data.count/1000)+ ' k';

            }else{

                var count_k = data.count;

            }

            //get the selected playlist from params
            var selectedPlaylist = args['playlist_selection'];

            if(selectedPlaylist  === "sample"){

                jQuery('#playlist-selection option:selected').text('Print Version Playlist (Total:'+count_k+' )');

            }else if(selectedPlaylist  === "selected"){

                jQuery('#playlist-selection option:selected').text("Current Selection (Total:"+count_k+" )");

            }else{

                jQuery('#playlist-selection option:selected').text(ucfirst(args.playlist_selection) +' (Total:'+count_k+' )');

                currentSelectedSongs = data.selected_songs ? data.selected_songs  : [] ;

                currentSelectionTotalTime = parseInt(data.songs_length);

                jQuery(".song-count").text(currentSelectedSongs.length);

                jQuery("#playlist-selection option[value='selected']").text("Current Selection (Total:"+currentSelectedSongs.length+" )");

                var songs_time_formated = formatTimeLength(currentSelectionTotalTime);

                jQuery('.playlist-length').text(songs_time_formated);

            }

            jQuery("#select-all-songs").prop("checked", currentSelectedSongs.length == playlistTotalSongCount);

        },

        error: function(errorThrown, data){

            console.log(errorThrown);

        }

    });

}

function generatePDFLink (username, playlistName) {

    var pdfdir = jQuery('.pdf_url').attr('value');

    if (playlistName == 'sample') {

        url = pdfdir + 'song-list.pdf'

    } else {

        var filename = encodeURIComponent(playlistName);

        var url = pdfdir + username + '-' + filename + '.pdf';

    }

    return url;
}

function collectArgs() {

    userArgs = {};

    if(currentSelectedSongs.length > 0) {

        userArgs["post__in"] = currentSelectedSongs;

    } else {

        userArgs["post__in"] = {};

    }
    userArgs['selected_song_length'] = currentSelectionTotalTime;

    userArgs["playlist_selection"] = jQuery("#playlist-selection").val();

    userArgs['posts_per_page'] = jQuery("#limit-results-selection").val();

    var page_value = jQuery(".current-page").val().split("/");

    userArgs['offset'] = parseInt(jQuery('#limit-results-selection').val()) * (Math.abs(parseInt(page_value[0])) - 1);

    if (jQuery('#search-by').val() == 'title'  && jQuery('#search-term').val() != "") {

        userArgs['s'] = jQuery('#search-term').val();

    } else if (jQuery('#search-term').val() != "") {

        userArgs['search_by'] =  jQuery('#search-by').val();

        userArgs['search_term'] = jQuery('#search-term').val();
    }

    return userArgs;

}

jQuery(document).ready(function() {

    jQuery("#song_selector_block #instruction").popover({

        trigger: "click",

        title: "Instructions",

        content: "<div class='help-info' style='padding: 10px; font-size: 12px !important;'>"

                    +"<p>1. Make sure you have selected 'Full Playlist' in the drop box to the left.</p>"

                    +"<p>2. Use the search tools to find the songs you like.</p>"

                    +"<p>3. Click the 'YouTube/Eye' icon in the far right column to listen to a song in YouTube.</p>"

                    +"<p>4. Select the songs by clicking the checkbox or double clicking the row.</p>"

                    +"<p>5. Click 'Show Selection' to view your current playlist selection.</p>"

                    +"<p>6. Click 'Save' to save your playlist selection.</p>"

                    +"<p>7. Click 'PDF PRINT' to see the print version of your playlist.</p>"

                    +"<p>8. Print and give to your DJ on the night, or email it to us beforehand.</p>"

                    +"<p>9. To make a new playlist, click 'Show Selection', uncheck all songs at the top of the row, make a new selection and save with a new playlist name.</p>"

                    +"<p>10. Select previously saved playlists in the 'Select A Playlist' drop down.</p>"

                +"</div>",

        container: ".bootstrap-iso",

        placement: "left",

        html: true,

        template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'

    });

    var musicDataTable = jQuery('#music_selector_table').DataTable({

        "searching":false,

        "lengthChange": false,

        "pageLength": 10,

        "scrollY":"270px",

        "scrollCollapse": false,

        "paging": false,

        "info": false,

        "ordering": false

    });

    var setCurrentPage= function(currentPage){

        var totalPages = jQuery("#total-pages").val();

        jQuery(".current-page").val(currentPage+"/"+totalPages);

    };

    function updateContent(page){

        setCurrentPage(page);

        querySongs(collectArgs());
    }

    getAvailableGenres();

    jQuery("#music_selector_table").stupidtable();

    updateContent(1);

    jQuery('.avail-playlist-pdf').hide();

    jQuery(this).on("click","dataTables_scroll, .dataTables_scrollFootInner, .dataTable, tr, td", function(event){

        event.stopPropagation();

    });

    jQuery('body').on('dblclick', '#music_selector_results tr', function (){

        jQuery(this).find("input[type=checkbox]").trigger('click');

    });

    jQuery(this).on("click", ".next-batch",function () {
        //value format (1/100), index 0 is the current page
        var page_value = jQuery(".current-page").val().split("/");

        var currentPage = Math.abs(parseInt(page_value[0]));

        if (currentPage !==  parseInt(page_value[1])) {

            currentPage++;

        } else {

            currentPage = 1;

        }

        playlistID = jQuery('#playlist-selection option:selected').val();

        updateContent(currentPage);

    });

    jQuery(this).on("click", ".prev-batch", function () {

        var page_value = jQuery(".current-page").val().split("/");

        var currentPage = Math.abs(parseInt(page_value[0]));

        if (currentPage != 1) {

            currentPage--;

        } else {

            currentPage = parseInt(jQuery('#total-pages').val());

        }

        playlistID = jQuery('#playlist-selection option:selected').val();

        updateContent(currentPage);

    });

    jQuery('#search-songs').click(function () {

        updateContent(1);

    });

    jQuery('#limit-results-selection').change(function () {

        updateContent(1);

    });

    jQuery('#loadPlaylist').click(function(){

        var selectElement = jQuery("#playlist-selection");

        selectElement.data("current", selectElement.data("next"));

        selectElement.val(selectElement.data('current'));

        loadPlaylist();
    });

    function loadPlaylist(){

      var selectedValue = jQuery("#playlist-selection").val();
      //cached existing playlist selected
      var newUrl = generatePDFLink(username, selectedValue);

      jQuery('#pdf-print').attr('href', newUrl).attr('title', selectedValue + ' PDF')

      jQuery("#pdf-print").removeClass("hide");

      updateContent(1);

    }

    jQuery('#playlist-selection').change(function (event, showConfirmDialog) {

        var selectedValue = this.value;

        if (selectedValue === "full" || selectedValue === "selected") {

            jQuery('#pdf-print').addClass("hide");


        } else if(selectedValue === "sample"){

            var newUrl = generatePDFLink("", selectedValue);

            jQuery('#pdf-print').attr('title', 'Print Version PDF').attr('href', newUrl).removeClass("hide");

        } else {

            if(showConfirmDialog === false){

                loadPlaylist();

            }else{

               jQuery(this).val(jQuery(this).data('current'));

               jQuery(this).data("next", selectedValue);

               jQuery('#playlist-option-modal #playlist_select').val(selectedValue);

               jQuery('#confirmation').modal('show');
            }
            return false;
        }

        updateContent(1);

        jQuery(this).data('current', selectedValue);

    });

    jQuery('#search-btn').click(function(e){

        updateContent(1);

    });

    jQuery('#search-term').keyup(function(e){

        if(e.keyCode == 13){

            jQuery("#search-btn").trigger("click");

        }
    });

    jQuery('#playlist-option-modal').keypress(function (e) {

        var key = e.which;

        if(key == 13){

          jQuery('#submit-playlist').trigger("click");

          return false;

        }
    });

    jQuery('#search-by').change(function () {

        if(this.value == 'song_genre') {

            jQuery('#search-term').autocomplete ({

                source: available_genres

            });

        } else if (jQuery('#search-term').data('uiAutocomplete')) {

            jQuery('#search-term').autocomplete("destroy");

            jQuery('#search-term').removeData('uiAutocomplete');

        }

    });

    jQuery('body').on("click","#current-selection-q", function (event) {

        jQuery("#playlist-selection").val('selected').trigger("change");

    });

    jQuery('body').on('click', '.popover', function(){

        jQuery(this).popover('hide');

    });

    jQuery('body').on('change','.select-single-song', function () {

        var playlistID = jQuery("#playlist-selection").val();

        var songCountElement = jQuery(".song-count");

        var playlistLengthElement =  jQuery('.playlist-length');

        var sourceElement = jQuery(this);

        var selectedValue = sourceElement.val();

        var optionText = '';

        if(!sourceElement.prop("checked")){


            if(playlistID != "full" && playlistID != "sample" && playlistID != "selected"){

                var song_row = jQuery(this).closest('tr');

                delete_song(playlistID, song_row.attr("id"));

                song_row.remove();

                optionText = playlistID;

            }else if(playlistID === 'selected'){

               var song_row = jQuery(this).closest('tr');

               song_row.remove();

               optionText = 'Current Selection';

            }

            if(jQuery.inArray(selectedValue, currentSelectedSongs) >= 0){

                sourceElement.closest("tr").removeClass("selected-track");

                var removeItem = selectedValue;

                currentSelectedSongs = jQuery.grep(currentSelectedSongs, function( n ) {

                    return n != removeItem;

                });

                //subtract current selection time
                currentSelectionTotalTime -= parseInt(sourceElement.data("time"));

            }

            if(optionText){

              jQuery("#playlist-selection option[value='"+playlistID+"']").text(optionText +" (Total: "+currentSelectedSongs.length+")");

            }

        }else{

            if(jQuery.inArray(selectedValue, currentSelectedSongs) === -1 ){

                sourceElement.closest("tr").addClass('selected-track');

                currentSelectedSongs.push(selectedValue);

                currentSelectionTotalTime += parseInt(sourceElement.data("time"));
            }

        }

        songCountElement.text(currentSelectedSongs.length);

        var songs_time_formated = formatTimeLength(currentSelectionTotalTime);

        playlistLengthElement.text(songs_time_formated);

        jQuery("#select-all-songs").prop("checked", currentSelectedSongs.length == playlistTotalSongCount);

        updateSelectionOptionCount();

    });

    jQuery("#select-all-songs").on('click', function () {

        jQuery(".select-single-song").prop("checked", jQuery(this).prop("checked"));

        jQuery(".select-single-song").trigger("change");

    });

    function updateSelectionOptionCount(){

        jQuery("#playlist-selection").find("option[value='selected']").text("Current Selection (Total: "+currentSelectedSongs.length+" )");

    }

});
