$(function () {
    
    $('#advice_question').DefaultValue("Položte otázku a získajte odpoveď ...");
    
    //vyhladavac otazok
    $('#questionSearchQ').questionSearch({
        onSelect: function (holder,otazka) {
            Router.route('joblife/advice/question/id/' + otazka.id + '/');
            //return false;
        }
    });
    
    $('#next-questions').click(function () {
        var offset = $(this).attr('rel');
        var new_offset = parseInt(offset,10) + parseInt(3,10);
        loadNewestQuestions(new_offset);
    });
    $('#prev-questions').click(function () {
        var offset = $(this).attr('rel');
        var new_offset = parseInt(offset,10) - parseInt(3,10);
        
        if(new_offset <= 0){
            new_offset = 0;
        }
        
        loadNewestQuestions(new_offset);
    });
    
    $('#advice_question').keyup(function () {
        var count = calculateChars();
        if(count < 1){
            $('#advice_question').val($('#advice_question').val().substr(0,110));
            $('#advice_question').animate({ scrollTop: $('#advice_question').height() }, 1);
        }
    });
    
});

function loadNewestQuestions(offset) {
    $.ajax({
       type: "POST",
       url: Router('joblife/advice/load-newest/'),
       data: "offset="+offset,
       success: function(ret){
           
           $('#prev-questions').attr('rel',offset);
           $('#next-questions').attr('rel',offset);
           if(offset < 1){
               $('#prev-questions').hide();
           } else {
               $('#prev-questions').show();
           }
           $('#newestQuestionBlock').html(ret);
           //$("#newestQuestionBlock").animate({opacity:0},400,'swing', function () {
           //   vykonaj zmenu
           //   $(this).animate({opacity:1},400,'swing');
           //});
       }
    });
}


function calculateChars() {
    var charcount = 110 - $('#advice_question').val().length;
    if(charcount == '' || charcount < 0){
        $('#charcount').html('0');
    } else {
        $('#charcount').html(charcount);
    }
    
    return charcount;
}