$(function() {
    //top films
    $('ul.tabs').delegate('li:not(.current)', 'click', function() {
        $(this).addClass('current').siblings().removeClass('current')
            .parents('div.section').find('div.box').hide().eq($(this).index()).fadeIn(0);
    });

    /** Голосовалочка */
    $('.mark').click(function() {
        var id = this.title;
        $.post("/video/savemark", {id : id, mark : user_votes},
            function(xhr){
                if(xhr['is_user'] == false){
                    $('.count_'+id).empty().append('<a href="http://joylife.ru/user/signup">Зарегистрируйтесь</a>');

                    $('.service_'+id).empty().append('<a href="http://joylife.ru/user/signup">Зарегистрируйтесь</a>');
                } else {
                    $('.votes_'+id).width((xhr['sred_mark']*17 < 85) ? xhr['sred_mark']*17 : 85);

                    $('.sred_'+id).empty().append('Рейтинг Joylife<span>' + xhr['sred_mark'].toFixed(2) + '</span>');
                    $('.mark_'+id).empty().append('Ваша оценка <span>'    + xhr['user_mark']            + '</span>');
                    $('.count_'+id).empty().append('Всего голосов <span>' + xhr['count_votes']          + '</span>');

                    /** digits only */
                    $('.d_sred_'+id).empty().append(xhr['sred_mark'].toFixed(2));
                    $('.d_mark_'+id).empty().append(xhr['user_mark']);
                    $('.d_count_'+id).empty().append('(' + xhr['count_votes'] + ')');
                }
        });
    });

    /** наведение мыши*/
    /* $('.mark').hover(function() {
        $('.votes_'+this.title+', .hover_'+this.title).toggle();
    }); */
var title;
    //при наведении считаем ширину
    $(".mark").mousemove(function(e){
        title = $(this).attr('title');
        $('.votes_'+title).hide();
        $('.hover_'+title).show();
        var margin_doc = $(".r"+this.title).offset();
        var widht_votes = e.pageX - margin_doc.left;
        user_votes = Math.ceil(widht_votes/17);
        $('.raiting_hover').width((user_votes*17 < 85) ? user_votes * 17 : 85);
    });
    
    $(".mark").mouseout(function(e){
        $('.votes_'+title).show();
        $('.hover_'+title).hide();
    });
});

//ajax load top films
//and update div #rtop
function loadrtop(type){
      $.ajax({
        type: "POST",
        url: "/video/top",
        data: "type="+type,
        dataType: "html",
        success: function(xhr){
            $(".rtop").empty().prepend(xhr);
        }
    });
    return false;
}

//@type ()
function videoajax(type, select){
    //внимание, идет загрузка
    $("#filmslala").empty().prepend('Внимание!!! идет загрузка');
    $.ajax({
        type: "GET",
        url: "/"+type,
        data: select,
        dataType: "html",
        success: function(xhr){
            $("#filmslala").empty().prepend(xhr);
        }
    });
    return false;
}

//add bookmarks
//@param id int film_id
function add_bookmark(id){
    $.ajax({
        type: "POST",
        url: "/video/addbookmark",
        data: "id="+id,
        dataType: "json",
        success: function(xhr){
        }
    });
    return false;
}

//del bookmarks
//@param id int film_id
function del_bookmark(id){
    $.ajax({
        type: "POST",
        url: "/video/delbookmark",
        data: "id="+id,
        dataType: "json",
        success: function(xhr){
            //hide bookmark
            $("#bookmark_"+id).hide(50);
        }
    });
    return false;
}

// delete film from user history
function delfin(id){
    $(function(){
        $.post("/video/delfin", {id: id} );
        $("#film_"+id).hide(50);
    });
}

//film.portal.ru/film/0001 - image box
//при нажании всплывает большая картинка
function loadImg(path){
    $('.big_img').empty().prepend('<img src="'+path+'" />');
}


/** страница добавления фильмов юзерами */

var changed_genres = []; //массив из выбранных жанров
function addGenre(){
    //взять селект
    var id   = $("select[name=genres] option:selected").val();
    var name = $("select[name=genres] option:selected").text();

    if(id && (id!=999) && !changed_genres[id]){
        $(".selected_genres").append('<div class="gen gen_'+id+'">'+name+'<b onclick="delGenre('+id+')">-</b></div><div class="clear"></div>');
        changed_genres[id] = true;
        updGenresList();
    }
    $("select[name=genres]").val(999);
}

function delGenre(id){
    changed_genres[id] = false;
    $('.gen_'+id).empty().hide();
    updGenresList();
}

//берем из массива changed_genres,
//соединяем в строку
//и пишем в input name="changed_genres"
function updGenresList(){
    var list = '';
    for(var key in changed_genres){
        if(changed_genres[key]) list += "|"+key;
    }
    $("input[name=changed_genres]").val(list);
    return true;
}
