function isSuccessViewsImage(sel) {
    if ($.browser.opera) {
        width = sel.attr('width');
        height = sel.attr('height');
        sel.removeAttr('width');
        sel.removeAttr('height');
        sel.attr('alt', '');
        aHeight = sel.height();
        aWidth = sel.width();
        if (width) {
            sel.attr('width', width);
        }
        if (height) {
            sel.attr('height', height);
        }
        if (aHeight<=1 || aWidth<=1) {
            return false;
        }
        return true;
    } else if ($.browser.msie) {
        obj = sel[0];
        return obj.fileSize!=-1;
    } else {
        return parseInt(sel.attr('naturalWidth'))>0;
    }
}

CountedByHeightItems = function(c) {
    this.init(c);
}

CountedByHeightItems.prototype =  {
    c:null,
    
    init: function(c) {
        this.c = c;
        this.tryRecalcContainerElementsHeights();
    },
    
    thumbsAlreadyLoaded: function() {
        var loaded = true;
        this.c.children().each(function(){
            img = $(this).find('img');
            if (img.length>0 && !isSuccessViewsImage(img)) {
                loaded = false;
            }
        });
        return loaded;
    },
    
    recalcContainerElementsHeights: function() {
        maxWidth = this.c.width();
        curWidth = 0; maxHeight = 0;
        elems = []; row = 0;
        this.c.children().each(function(){
            width = $(this).outerWidth();
            //height = $(this).find('img').outerHeight();
            height = $(this).height();
            if (curWidth+width>maxWidth) {
                while (elems.length>0) {
                    elem = elems.pop();
                    elem.css('height', maxHeight);
                    elem.css('width', elem.width());
                    elem.addClass('row'+row);
                }
                maxHeight = 0;
                curWidth = 0;
                row++;
            }
            curWidth+=width;
            maxHeight = (maxHeight<height) ? height : maxHeight;
            elems.push($(this));
        });
        while (elems.length>0) {
            elem = elems.pop();
            elem.css('height', maxHeight);
            elem.css('width', elem.width());
            elem.addClass('row'+row);
        }
    },
    
    tryRecalcContainerElementsHeights: function() {
        if (this.thumbsAlreadyLoaded()) {
            this.recalcContainerElementsHeights();
        } else {
            var that = this;
            setTimeout(function(){
                that.tryRecalcContainerElementsHeights();
            }, 100);
        }
    }
    
}

function updateFlashObjects() {
    $('object').each(function(){
        c = $(this).parent();
        if ($(this).width()>c.width()) {
            m = $(this).attr('width')/c.width();
            h = Math.floor($(this).attr('height')*m);
            w = c.width();
            $(this).attr('width', w)
                    .attr('height', h)
                    .find('embed')
                        .attr('width', w)
                        .attr('height', h);
        }
    });
}

$(document).ready(function() {
    // Выравнивание по высоте блока gameslist
    if ($('.gameslist').length>0) {
        new CountedByHeightItems($('.gameslist'));
    }
    // Выравнивание по высоте скриншотов
    $('.thumbs').each(function(){
        new CountedByHeightItems($(this));
    });
    // Выравнивание по ширине флешевских объектов
    updateFlashObjects();
    // следить за игрой
    if ($('#follow_game').length>0) {
        new AjaxProgress($('#follow_game'));
        $("#follow_game").bind("click", function(e){
            var that = this;
            var game_id = $("#game_id").val();
            this.showProgress();
            $.getJSON("/games/index/follow-game"
                ,{game_id:game_id}
                ,function(data){
                    that.hideProgress();
                    if (data.err){
                        $("#follow_game_span").html('Ошибка, попробуйте перегрузить страницу');
                    }else{
                        var mess = '';
                        if(data.res) {
                            mess = 'отписаться от слежения за игрой'
                        }else{
                            mess = 'следить за игрой';
                        }
                        if ($(that).attr('nodeName') == 'A'){
                            $(that).html(mess);
                        }else{
                            $(that).val(mess);
                        }
                    }
                    $("span[name=follow_user_count]").html(data.follow_user_count);
                }
            );
        });
    }
    
    // подписаться на рассылку
    if ($("#subscribe_news").length>0) {
        new AjaxProgress($('#subscribe_news'));
        $("#subscribe_news").bind("click", function(e){
            var that = this;
            this.showProgress();
            $.getJSON("/news/index/subscribe"
                ,function(data){
                    that.hideProgress();
                    if (data.err){
                        $("#subscribe_news_span").html('Ошибка, попробуйте перегрузить страницу');
                    }else{
                        var mess = '';
                        if(data.res) {
                            mess = 'отказаться от подписки'
                        }else{
                            mess = 'подписаться';
                        }
                        $(that).val(mess);
                    }
                }
            );
        });
    }
    
    // оценить игру
    if ($("#user_estimate_button").length) {
        new AjaxProgress($("#user_estimate_button"));
        $("#user_estimate_button").bind("click", function(e){
            var game_id = $("#game_id").val();
            var rate = '';
            $('input[name=rate_user_estimate]').each(function(){
                if ($(this).attr('checked')) {
                 rate = $(this).val();
                }
            });
            if (!rate){
                alert('Нужно выбрать оценку');
            }else{
                this.showProgress();
                var that = this;
                $.getJSON("/games/index/estimate"
                    ,{rate:rate, game_id:game_id}
                    ,function(data){
                        that.hideProgress();
                        $("#user_estimate_block").html('Ваш голос учтен');
                        $("span[name=rate_avg_user]").html(data.rate_avg_user);
                        $("span[name=rate_count]").html(data.rate_count);
                    }
                );
            }
        });
    }
    // голосовать
    if ($("#vote_now").length>0) {
        new AjaxProgress($('#vote_now'));
        $("#vote_now").bind("click", function(e){
            var question_id = $("#question_id").val();
            var answer_id   = '';
            var is_selected = false;
            $('input[name=answer_id[]]').each(function(){
                if ($(this).attr('checked')) {
                 answer_id  += $(this).val()+',';
                 is_selected = true;
                }
            });
            if (!is_selected){
                alert('Нужно выбрать вариант ответа');
            }else{
                this.showProgress();
                var that = this;
                
                answer_id  = answer_id.substring(0, answer_id.length-1);
                $.get("/vote/index/vote"
                    ,{answer_id:answer_id, question_id:question_id}
                    ,function(data){
                        that.hideProgress();
                        $("#vote_block").html(data);
                    }
                );
            }
        });
    }

    // поиск
    new Autocomplete($('#search-game input:text'), {
        'changeUrl':   '/games/index/autocomplite-name'
    });
    $("#search-game").submit(function(){
        // меняем / на %2F
        var search_query = $(this).find("input[name=search_query]");
        search_query.val(search_query.val().replace('/', '%2F'));
    });
    $("#search").submit(function(){
        // меняем / на %2F
        var search_query = $(this).find("input[name=search_query]");
        search_query.val(search_query.val().replace('/', '%2F'));
    });
    $('#search input:radio').change(function(){
        var val = $('#search input:radio:checked').val();
        $('#search form').each(function(){
            if ($(this).attr('id')==val) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    });
    $('#search input:radio').each(function(){
        if ($(this).attr('checked')) {
            $(this).trigger('change');
        }
    });
    $('#search input[name=search_query]').change(function(){
        var search_query = $(this).val();
        $('#search input[name=search_query]').each(function(){
            $(this).val(search_query);
        });
    });
    

});
