$(function() {

    $('#side-menu').metisMenu();
    
    $('.counter').countTo();
    
    $(".colorbox").colorbox({
        maxWidth:'95%', 
        maxHeight:'95%'
    });
    
    /*
    $('a[href*=#]:not([href=#])').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
          var target = $(this.hash);
          target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
          if (target.length) {
            $('html,body').animate({
              scrollTop: target.offset().top
            }, 500);
            return false;
          }
        }
    });
    */

});

$('.btn-comment').click(function() {
    $('#CommentId').val('');
    tinyMCE.get('CommentContent').setContent('');
    $('.row-comment').show(); 
});
$('.btn-comment-cancel').click(function() {
    $('#CommentId').val('');
    tinyMCE.get('CommentContent').setContent('');
    $('.row-comment').fadeOut(); 
});

$('.btn-comment-edit').click(function() {
    $('#CommentId').val($(this).attr('data-id'));
    var comment_content = $(this).parent().parent().find('div.comment-content').html();
    tinyMCE.get('CommentContent').setContent(comment_content);
    $('.row-comment').show(); 
});
$('.btn-comment-delete').click(function() {
    // TO DO: Ask for confirmation
});

//Loads the correct sidebar on window load,
//collapses the sidebar on window resize.
$(function() {
    $(window).bind("load resize", function() {
        console.log($(this).width())
        if ($(this).width() < 768) {
            $('div.sidebar-collapse').addClass('collapse')
        } else {
            $('div.sidebar-collapse').removeClass('collapse')
        }
    })
})

tinymce.init({
    selector: ".wysiwyg",
    language : 'en',
    plugins: [
        "advlist autolink link lists charmap",
        "visualblocks visualchars code nonbreaking",
        "directionality paste"
    ],

    content_css: "/assets/css/tinymce.css",
    style_formats: [
        {title: 'Titel', inline: 'span', classes : 'titel'},
        {title: 'Subtitel', inline: 'span', classes : 'subtitel'},
        {title: 'Normaal', block: 'p'},
        {title: 'Button', inline: 'span', classes : 'btn'},
    ],
    
    toolbar1: "bold italic underline | bullist numlist | link unlink | code",
    content_css: "/assets/css/tinymce.css",
    menubar: false,
    statusbar : false,
    paste_as_text: true,
    toolbar_items_size: 'small',
    autosave_restore_when_empty: false
});

$(document).on("click", ".confirm_action", function () {
    var controller = $(this).data('controller');
    var action = $(this).data('action');
    var item_id = $(this).data('item_id');
    
    if(controller && action && item_id) {
        $("#confirmModal #confirmSubmit").on("click", function() {
            var url = '/' + controller + '/' + action + '/' + item_id;
            window.location=url;
            $("#confirmModal").modal('hide');
        });
    } else {
        $("#confirmModal").modal('hide');
        return false;
    }
});

function reload() {
    $('#adminSettingsModal').modal('hide');
    $('#userSettingsModal').modal('hide');
    setTimeout(function() {
        location.reload();
    }, 250);  
}


$('#userSettingsSubmit').click(function() {
    submitUserSettings();
});
$('#userSettingsCancel').click(function() {
    $('#userSettingsModal').modal('hide');
});
$('#userSettingsModal').on('hidden.bs.modal', function () {
    reload();
});

$('#userSettingsCancel').bind('keypress', function(event){
    if(event.keyCode == 13) {
        event.preventDefault();
        $('#userSettingsCancel').modal('hide');
        submitSettings();
    }
});

$('#ConfigurationMailserverTransport').change(function() {
    if($(this).val() == 'SMTP') {
        $('#mailSmtp').show();
    }else{
        $('#mailSmtp').hide();
    }
});

function submitUserSettings() {
    var $validator = $("#userSettingsForm").validate();

    var $valid = $("#userSettingsForm").valid();
	if(!$valid) {
		$validator.focusInvalid();
        return false;
	}else{
	    var succeed = false;
	    
	    $.ajax({
        	async: false,
            type: 'post',
            url: '/users/settings/',
            data: $('#userSettingsForm').serialize(),
            cache: false,
            dataType: 'json',
            success: function (data) {
                if (data.status == 'OK') {
                    reload();
                }
            }
        });
    }
    return succeed;
}


$('.btn-follow').mouseover(function() {
    if($(this).hasClass('active')) {
        $(this).addClass('btn-danger');
        $(this).removeClass('active');
        $(this).removeClass('btn-primary');
        $(this).html(translation.unfollow);
    }
}).mouseout(function() {
    if($(this).hasClass('btn-danger')) {
        $(this).addClass('btn-primary');
        $(this).addClass('active');
        $(this).removeClass('btn-danger');
        $(this).html(translation.following);
    }
}).click(function() {
    follow($(this));
});

function follow(el) {
    var followers = el.parent().parent().find('span.counter-followers');
    var user_id = el.attr('data-id');
    var count = parseInt(followers.html());
    
    if (user_id === undefined) {
        return false;
    }
    
    $.ajax({ 
        type: "GET", 
        url: "/users/follow/" + user_id,
        success: function(result) {
            if (result == 1) {                    
                el.removeClass('btn-primary');
                el.removeClass('btn-danger');
                el.removeClass('active');
                el.addClass('btn-primary active');
                el.html(translation.following);
                
                count++;
                el.parent().parent().find('span.counter-followers').html(count);
            }else if(result == 2) {                    
                el.removeClass('btn-primary');
                el.removeClass('btn-danger');
                el.removeClass('active');
                el.addClass('btn-primary');
                el.html(translation.follow);
                
                count--;
                el.parent().parent().find('span.counter-followers').html(count);
            }
        }
    });
}