$(document).ready(function(){
    NProgress.configure({ showSpinner: true });
    NProgress.start();

    title_lock = 'disabled';

    _token = $('meta[name="_token"]').attr('content');
    auth_download = $('meta[name="auth_download"]').attr('content');
    auth_download = parseInt(auth_download);
    is_login = $('meta[name="is_login"]').attr('content');
    is_login = parseInt(is_login);
    vk_auth = $('meta[name="vk_auth"]').attr('content');
    soundcloud_key = $('meta[name="soundcloud_key"]').attr('content');

    // Enter your ids or classes
    var toggler = '.navbar-toggle';
    var pagewrapper = '#page-wrapper';
    var menuwidth = '100%'; // the menu inside the slide menu itself
    var slidewidth = '70px';
    var menuneg = '-100%';
    var slideneg = '-70px';

    $(document).on("click", toggler, function (e) {
        var selected = $(this).hasClass('slide-active');
        menuDirection = $(this).attr('data-direction');
        var animeOpt = {};

        animeOpt[menuDirection] = selected ? menuneg : '0px';
        $($(this).attr('data-target')).stop().animate(animeOpt);

        animeOpt[menuDirection] = selected ? '0px' : slidewidth;
        $(pagewrapper).stop().animate(animeOpt);


        $(this).toggleClass('slide-active', !selected);
        $($(this).attr('data-target')).toggleClass('slide-active');

        $('#page-wrapper, .navbar, body, .navbar-header').toggleClass('slide-active');
        $($(this).attr('data-target')).css('height', $(window).height());
        $(pagewrapper).css({'left' : 'unset', 'right' : 'unset'});
    });

    var selected = '#slidemenu, #page-wrapper, body, .navbar';
    $(window).on("resize", function () {
        if ($('.navbar-toggle').is(':hidden')) {
            $(selected).removeClass('slide-active');
            clipTransparentImage();
            genresFit();
        }
    });

    $(document).on('click', '.toggleGenre' ,function(e) {
        var that = $(this);
        _genre_id = that.parent().attr('id');
        _token = $('meta[name="_token"]').attr('content');

        $.post(rootURL+'/user/admin/genres',
            { genre_id: _genre_id, _token: _token },
            function(data){
                if(data == 'ok')
                {
                    if(that.hasClass("fa-eye"))
                    {
                        that.removeClass("fa-eye").addClass("fa-eye-slash");
                    }
                    else
                    {
                        that.removeClass("fa-eye-slash").addClass("fa-eye");    
                    }
                }
            }
        );
    });

    $(".pjax").on("click", function(event){
        var that = $(this);
        pjax.invoke({
            'url': that.attr("href"),
            'container': 'wrapper',
            'timeout': 4000,
            'beforeSend': function(e){
                NProgress.start();
            },
            'complete': function(e){
                genresFit();
                NProgress.done();
                clipTransparentImage();
                sortLists();
            },
        });
        event.preventDefault();
    });

    $('.navbar-form').submit(function(e) {
        var q = $(this).find('.form-control').val();
        //q = slugify(q);
        pjax.invoke({
            'url': rootURL+'/search/'+q,
            'container': 'wrapper',
            'timeout': 4000,
            'beforeSend': function(e){ NProgress.start(); },
            'complete': function(e){ genresFit(); NProgress.done(); clipTransparentImage(); sortLists(); },
        });
        e.preventDefault();
    });


    $("#login-form").ajaxForm({
        type: "post",
        delegation: true,
        dataType: "json",
        beforeSubmit: function(){
            NProgress.start();
            $("#btn-login").attr("disabled", "true");
        },
        success: function(data){
                var n = noty({
                text        : data.message,
                type        : data.status,
                dismissQueue: true,
                layout      : 'bottomRight',
                closeWith   : ['click'],
                theme       : 'relax',
                maxVisible  : 10
            });
            if(data.status == "success")
            {
                pjax.invoke({
                    'url': rootURL,
                    'container': 'wrapper',
                    'timeout': 4000,
                    'beforeSend': function(e){
                        NProgress.start();
                    },
                    'complete': function(e){
                        genresFit();
                        NProgress.done();
                        sortLists();
                    },
                });
                $("#login").modal('hide');
            }
            $("#btn-login").removeAttr("disabled");
        }
    });

    $("#signup-form").ajaxForm({
        type: "post",
        delegation: true,
        dataType: "json",
        beforeSubmit: function(){
            $("#btn-signup").attr("disabled", "true");
        },
        success: function(data){
            var n = noty({
                text        : data.message,
                type        : data.status,
                dismissQueue: true,
                layout      : 'bottomRight',
                closeWith   : ['click'],
                theme       : 'relax',
                maxVisible  : 10
            });
            if(data.status == 'success') {
                $("#signup").modal('hide');
            }
            $("#btn-signup").removeAttr("disabled");
        }
    });


    $("#create-playlist-form").ajaxForm({
        type: "post",
        delegation: true,
        dataType: "json",
        beforeSubmit: function(){
            $('#create-playlist-modal').modal('hide');
            NProgress.start();
        },
        success: function(data){
            var n = noty({
                text        : data.message,
                type        : data.status,
                dismissQueue: true,
                layout      : 'bottomRight',
                closeWith   : ['click'],
                theme       : 'relax',
                maxVisible  : 10
            });
            if(data.status == 'success') {
                pjax.invoke({
                    'timeout': 4000,
                    'url': rootURL+'/user/playlist',
                    'container': 'wrapper',
                    'beforeSend': function(e){
                        //NProgress.start();
                    },
                    'complete': function(e){
                        
                    },
                });
            }
            genresFit();
            NProgress.done();
        }
    });
    
    $("#track-playlist-form").ajaxForm({
        type: "post",
        delegation: true,
        dataType: "json",
        beforeSubmit: function(){
            $('#track-playlist-modal').modal('hide');
            NProgress.start();
        },
        success: function(data){
            var n = noty({
                text        : data.message,
                type        : data.status,
                dismissQueue: true,
                layout      : 'bottomRight',
                closeWith   : ['click'],
                theme       : 'relax',
                maxVisible  : 10
            });
            if(data.status == 'success') {
                genresFit();
                NProgress.done();
            }
        }
    });

    $("#edit-playlist-form").ajaxForm({
        type: "post",
        delegation: true,
        dataType: "json",
        beforeSubmit: function(){
            $('#edit-playlist-modal').modal('hide');
            NProgress.start();
        },
        success: function(data){
            var n = noty({
                text        : data.message,
                type        : data.status,
                dismissQueue: true,
                layout      : 'bottomRight',
                closeWith   : ['click'],
                theme       : 'relax',
                maxVisible  : 10
            });
            if(data.status == 'success') {
                pjax.invoke({
                    'timeout': 4000,
                    'url': rootURL+'/user/playlist/'+data.slug,
                    'container': 'wrapper',
                    'beforeSend': function(e){
                        //NProgress.start();
                    },
                    'complete': function(e){
                        genresFit();
                        NProgress.done();
                    },
                });
            }
        }
    });

    $("#rm-track-form").ajaxForm({
        type: "post",
        delegation: true,
        dataType: "json",
        beforeSubmit: function(){
            $('#rm-track-modal').modal('hide');
            NProgress.start();
        },
        success: function(data){
            var n = noty({
                text        : data.message,
                type        : data.status,
                dismissQueue: true,
                layout      : 'bottomRight',
                closeWith   : ['click'],
                theme       : 'relax',
                maxVisible  : 10
            });
            if(data.status == 'success') {
                pjax.invoke({
                    'timeout': 4000,
                    'url': rootURL+'/user/playlist/'+data.slug,
                    'container': 'wrapper',
                    'beforeSend': function(e){
                        //NProgress.start();
                    },
                    'complete': function(e){
                        genresFit();
                        NProgress.done();
                    },
                });
            }
        }
    });

    $("#rm-playlist-form").ajaxForm({
        type: "post",
        delegation: true,
        dataType: "json",
        beforeSubmit: function(){
            $('#rm-playlist-modal').modal('hide');
            NProgress.start();
        },
        success: function(data){
            var n = noty({
                text        : data.message,
                type        : data.status,
                dismissQueue: true,
                layout      : 'bottomRight',
                closeWith   : ['click'],
                theme       : 'relax',
                maxVisible  : 10
            });
            if(data.status == 'success') {
                pjax.invoke({
                    'timeout': 4000,
                    'url': rootURL+'/user/playlist',
                    'container': 'wrapper',
                    'beforeSend': function(e){
                        //NProgress.start();
                    },
                    'complete': function(e){
                        genresFit();
                        NProgress.done();
                    },
                });
            }
        }
    });

    $("#edit-user-form").ajaxForm({
        type: "post",
        delegation: true,
        dataType: "json",
        beforeSubmit: function(){
            $('#edit-user-modal').modal('hide');
            NProgress.start();
        },
        success: function(data){
            var n = noty({
                text        : data.message,
                type        : data.status,
                dismissQueue: true,
                layout      : 'bottomRight',
                closeWith   : ['click'],
                theme       : 'relax',
                maxVisible  : 10
            });
            if(data.status == 'success') {
                pjax.invoke({
                    'timeout': 4000,
                    'url': rootURL+'/user/'+data.url,
                    'container': 'wrapper',
                    'beforeSend': function(e){
                        //NProgress.start();
                    },
                    'complete': function(e){
                        genresFit();
                        NProgress.done();
                    },
                });
            }
        }
    });

    $("#user-mode-form").ajaxForm({
        type: "post",
        delegation: true,
        dataType: "json",
        beforeSubmit: function(){
            $('#user-mode-modal').modal('hide');
            NProgress.start();
        },
        success: function(data){
            var n = noty({
                text        : data.message,
                type        : data.status,
                dismissQueue: true,
                layout      : 'bottomRight',
                closeWith   : ['click'],
                theme       : 'relax',
                maxVisible  : 10
            });
            if(data.status == 'success') {
                pjax.invoke({
                    'timeout': 4000,
                    'url': rootURL+'/user/admin/user',
                    'container': 'wrapper',
                    'beforeSend': function(e){
                        //NProgress.start();
                    },
                    'complete': function(e){
                        //NProgress.done();
                    },
                });
            }
            genresFit();
            NProgress.done();
        }
    });

    $("#user-status-form").ajaxForm({
        type: "post",
        delegation: true,
        dataType: "json",
        beforeSubmit: function(){
            $('#user-status-modal').modal('hide');
            NProgress.start();
        },
        success: function(data){
            var n = noty({
                text        : data.message,
                type        : data.status,
                dismissQueue: true,
                layout      : 'bottomRight',
                closeWith   : ['click'],
                theme       : 'relax',
                maxVisible  : 10,
            });
            if(data.status == 'success') {
                pjax.invoke({
                    'timeout': 4000,
                    'url': rootURL+'/user/admin/user',
                    'container': 'wrapper',
                    'beforeSend': function(e){
                        //NProgress.start();
                    },
                    'complete': function(e){
                        //NProgress.done();
                    },
                });
            }
            genresFit();
            NProgress.done();
        }
    });

    $(document).on('click', '#lyrics-modal', function (event) {
        NProgress.start();
        var that = $(this);
        var lyrics_id = that.parents('tr').data('lyrics');
        var lyricsText = 'Sorry Couldn\'t find Lyrics';
        $.ajax({url:rootURL+'/api/track/lyrics?lyrics_id='+lyrics_id+'&vk_auth='+vk_auth,
            success:function(Data){
                if(Data != '') { lyricsText = Data; }
                $('#lyrics-view-modal').modal('show').find('.modal-body').html(lyricsText);
                NProgress.done();
            }
        });        
    });
    
    $(document).on('show.bs.modal', '#social-share-modal', function (event) {
        var that = $(event.relatedTarget);
        var sharelink = that.parents('tr').data('share');
        var ttitle = that.parents('tr').data('title');
        var modal = $(this);
        modal.find('.bg-facebook').attr('href', 'https://www.facebook.com/sharer.php?u='+sharelink);
        modal.find('.bg-twitter').attr('href', 'https://twitter.com/share?url='+sharelink+'&text='+ttitle+'&via='+$('meta[name="twitter:site"]').attr('value'));
        modal.find('.bg-google').attr('href', 'https://plus.google.com/share?url='+sharelink);
        modal.find('.bg-pinterest').attr('href', 'https://pinterest.com/pin/create/bookmarklet/?url='+sharelink+'&description='+ttitle);
        modal.find('.bg-stumble').attr('href', 'http://www.stumbleupon.com/submit?url='+sharelink+'&title='+ttitle);
        modal.find('.bg-vk').attr('href', 'http://vk.com/share.php?url='+sharelink);
        modal.find('.bg-linkedin').attr('href', 'http://www.linkedin.com/shareArticle?url='+sharelink+'&title='+ttitle);
        modal.find('.bg-digg').attr('href', 'http://www.digg.com/submit?url='+sharelink+'&title='+ttitle);
        //modal.find('input[name="ttitle"]').val(ttitle);
    });

    $(document).on('show.bs.modal', '#track-playlist-modal', function (event) {
        var that = $(event.relatedTarget);
        var trackid = that.parents('tr').data('trackid');
        var title = that.parents('tr').data('title');
        var modal = $(this);
        modal.find('input[name="trackid"]').val(trackid);
        modal.find('input[name="title"]').val(title);
    });

    $(document).on('show.bs.modal', '#rm-track-modal', function (event) {
        var that = $(event.relatedTarget);
        var track = that.parents('tr').data('trackid');
        var modal = $(this);
        modal.find('input[name="track"]').val(track);
    });

    $(document).on('show.bs.modal', '#edit-user-modal', function (event) {
        var that = $(event.relatedTarget);
        var user = that.data('user');
        var username = that.data('username');
        var email = that.data('email');
        
        var modal = $(this);
        modal.find('input[name="user"]').val(user);
        modal.find('input[name="username"]').val(username);
        modal.find('input[name="email"]').val(email); 
    });

    $(document).on('show.bs.modal', '#user-status-modal', function (event) {
        var that = $(event.relatedTarget);
        var user = that.data('user');
        var modal = $(this);
        modal.find('input[name="user"]').val(user);
    });

    $(document).on('show.bs.modal', '#user-mode-modal', function (event) {
        var that = $(event.relatedTarget);
        var user = that.data('user');
        var modal = $(this);
        modal.find('input[name="user"]').val(user);
    });

    $(window).load(function(){
        NProgress.done();
        $('#wrapper').removeClass('hidden');
        genresFit();
        clipTransparentImage();
        sortLists();
    });

$(document).on('click', '.play-album', function(){
        that = $(this);

        var playlist = that.data('playlist');
        playlist = $.trim(playlist).trim();
        var url = rootURL+'/user/playlist/'+playlist+'/play';

        $.post(url,
            { _token: _token, sid: soundcloud_key },
            function(data){
                if(data != '') {
                    $(".sm2-playlist-wrapper > .sm2-playlist-bd").html(data);
                    document.getElementById('play-pause').click();
                    title_lock = 'enabled';
                    soundManager.stopAll();
                    soundManager.load('sm-player', {url: $('.sm2-playlist-bd li a:first').attr('href')});
                    var smPlayer = soundManager.getSoundById('sm-player');
                    smPlayer.play();
                    document.title = $('.sm2-playlist-bd li:first a > span').text();
                    $('.play-album').removeClass('hidden');
                    that.addClass('hidden');
                }
            }
        );
    });

    $(document).on('click', '.track-play-list', function(){
        //document.getElementById('play-pause').click();
        var that = $(this);
        var trackid = that.parents('tr').data('trackid');
        var _title = that.parents('tr').data('title');

        var _track_link = 'http://api.soundcloud.com/tracks/'+trackid+'/stream?client_id='+soundcloud_key+'&title=sound.mp3';
        if(!$(".sm2-playlist-wrapper > .sm2-playlist-bd li a span:contains("+_title+")").length ){
            $(".sm2-playlist-wrapper > .sm2-playlist-bd").prepend('<li><a href="'+_track_link+'"><span>'+_title+'</span></a></li>');
        }

        document.getElementById('play-pause').click();
        
        title_lock = 'enabled';
        document.title = _title;
        if(that.hasClass("active"))
        {
            that.removeClass("active");
            that.find("span.fa").removeClass("fa-pause").addClass("fa-play");
            soundManager.stopAll();
        }
        else
        {
            $(".track-play").removeClass("active");
            $(".track-play").find("span.fa").removeClass("fa-pause");
            soundManager.stopAll();
            that.addClass("active");
            that.find("span.fa").addClass("fa-pause");
            /*if(!$(".sm2-playlist-wrapper > .sm2-playlist-bd li a:contains("+_title+")").length ){
                $(".sm2-playlist-wrapper > .sm2-playlist-bd").prepend('<li><a href="'+_track_link+'">'+_title+'</a></li>'); 
            }*/
            soundManager.load('sm-player', {url: _track_link});
            var smPlayer = soundManager.getSoundById('sm-player');
            smPlayer.play({
                onfinish: function() {
                    $(".btn-group .track-play").removeClass("active");
                    $(".btn-group .track-play").find("span.fa").removeClass("fa-pause");
                    soundManager.stopAll();
                }
            }); 
        }
        
    });


    $(document).on('click', '.track-download', function(){
        if(auth_download) {
            if(!is_login) {
                $("#signup").modal();
                return;
            }
        }
        var that = $(this);
        var trackid = that.parents('tr').data('trackid');
        window.location.href = rootURL+'/download/track/'+trackid;
    });

});

clipTransparentImage = function() {
    var that = $('.bg-transparent');
    $('.transparent-img').css({'clip': 'rect(0,'+that.width()+'px,'+that.outerHeight()+'px,0)'});

}

genresFit = function() {
    var genreCtrl = $('.genre-list');
    var total_width = genreCtrl.width()-380-genreCtrl.find('li.dropdown').width();
    var width_genre = 0;
    genreCtrl.find('.li-show').each(function(i, genre){
        if(width_genre < total_width) {
            width_genre += $(genre).width();
            //alert(width_genre +' / '+ total_width);
        } else {
            var clonedData = $(genre).clone();
            clonedData.appendTo('#more-gl');
            $(genre).remove();
        }
    });

    var windowWidth = $(document).width();
    if(windowWidth < 768) {
        $('.elemWidth.hidden-480').remove();
    }

    $('.scroll-items').each(function(i, element){
        var abc = 0;
        $(element).find('.elemWidth').each(function(i, ewidth){
            var width = $(ewidth).outerWidth();
            abc = abc+width;
        });
        $('.track-album').css('width', (genreCtrl.width()-abc)+'px');
    });

}
sortLists = function()
{
    $( "#sortable" ).sortable({
        placeholder: "ui-state-highlight",
        update: function( event, ui ) {
            var catArray = $(this).sortable('toArray');
            //alert(catArray);
            for(var i=0; i<catArray.length; i++)
            {
                $("input[name='"+(catArray[i])+"']").val(i+1);
            }

        }
    });
    $( "#sortable" ).disableSelection();
}

// $(document).ready(function(){$('input[name=search]').autocomplete({source:function(Query,Response){$.ajax({url:'http://suggestqueries.google.com/complete/search?client=youtube&ds=yt&q='+Query.term,dataType:'jsonp',success:function(Data){if(Data){var DataArr=Data.toString().split(',');var Queries=new Array();for(var q=1;q<(DataArr.length-1);q++){DataArr[q]=$.trim(DataArr[q]);if(0<DataArr[q].length&&DataArr[q]!='[object Object]'&&!$.isNumeric(DataArr[q])){Queries.push(DataArr[q]);}}if(0<Queries.length){Response(Queries);}}}});},delay:1000,minLength:2});});
