$(function() {
    var b = $('body');
    var generator_id = b.data('generator-id');

    if (generator_id) {
        // вешаем инвайтерский хвост на все внутренние ссылки
        b.delegate('a', 'mouseover', function() {
            var href = $(this).attr('href');

            if (!href || href.indexOf('inv=') !== -1 || (href.indexOf('/') !== 0 && href.indexOf(window.location.protocol + '//' + window.location.hostname) !== 0)) {
                return true;
            }
            var p = (href.indexOf('?') === -1 ? '?' : '&');
            if (href.indexOf('#') === -1) {
                href = href + p + 'inv=' + generator_id;
            } else {
                href = href.replace('#', p + 'inv=' + generator_id + '#');
            }

            $(this).attr('href', href);
    
            return true;
        });
    }
});


$('.actions .close_icon, .actions_close').live('click', function() {
    $(this).closest('.actions').hide('fast');
    return false;
});

$('.actions .close_icon, .actions_close').live('click', function() {
    $(this).closest('.actions').hide('fast');
    $(this).parents('.popup-wrapper').html('').hide();
    return false;
});

$('.hub-hover').live('click', function() {
    $(this).closest('.h-userbar').toggleClass('nohover')
    return false;
});

$('.fl-item .close_icon').live('click', function() {
    $(this).closest('.fl-item').hide('fast');
    return false;
});

$('.share_window .close_icon').live('click', function() {
    $(this).closest('.share_window').hide('fast');
    return false;
});

$('.login_window .close_icon').live('click', function() {
    $(this).closest('.login_window').hide('fast').remove();
    return false;
});

$('.news-actions .login_window_trigger').live('click', function() {
    var top = $(this).closest('.nl-vote_block').height()/2-21;
    $('.login_window').hide('fast').remove();
    var login_block=$('.login_window_sample').clone().addClass('login_window').removeClass('login_window_sample');
    $(login_block).appendTo($(this).parents('.nl-vote_block')).css('top', top+'px');
    return false;
});

$('.comment-item .login_window_trigger').live('click', function() {
    var top = 18;
    $('.login_window').hide('fast').remove();
    var login_block=$('.login_window_sample').clone().addClass('login_window').removeClass('login_window_sample');
    $(login_block).appendTo($(this).closest('.nl-vote_block')).css('top', top+'px');
    return false;
});

function tb_resize(height) {
    $('#TB_window').animate({ 'marginTop': - Math.ceil((height + 45) / 2) }, 400);
    $('#TB_ajaxContent').animate({ 'height': height }, 400);
}

function RegisterForm(el, loginForm) {
    this.is_busy = false;

    this.el = el;
    this.el_form = this.el.find('form');
    this.el_captcha = this.el_form.find('[data-role=captcha]');
    this.el_error = this.el.find('.error');

    this.captcha_src = this.el_captcha.attr('src');

    this.loginForm = loginForm;

    this.init();

    this.show();
}
RegisterForm.prototype.show = function() {
    var that = this;
    if (that.loginForm) {
        tb_resize(415);
        that.loginForm.el.fadeOut(650, function() {
            that.el.fadeIn(400);
        });
    } else {
        that.el.show();
    }
};
RegisterForm.prototype.setBusy = function(val) {
    if (val) {
        this.is_busy = true;
        this.el.find('.text').prop('readonly', true).end()
               .find('.submit').prop('disabled', true);
    } else {
        this.is_busy = false;
        this.el.find('.text').prop('readonly', false).end()
               .find('.submit').prop('disabled', false);
    }
};
RegisterForm.prototype.setError = function(str) {
    if (str) {
        this.el_error.html(str).show();
    } else {
        this.el_error.hide();
    }
};
RegisterForm.prototype.init = function() {
    var that = this;
    that.el.find('input[type=button]').click(function() {
        if (that.loginForm) {
            that.setBusy(true);
            that.loginForm.show();
            setTimeout(function() { that.setBusy(false); }, 2000);
        } else {
            tb_remove();
        }
    });
    that.el_form.ajaxForm({
        'beforeSubmit': function() {
            if (that.is_busy) {
                return false;
            }
            that.setBusy(true);

            // TODO: проверки на корректность данных
        },
        'dataType': 'json',
        'success': function(r) {
            if (r.error) {
                that.setError(r.error);
                that.el_captcha.attr('src', that.captcha_src + '&t=' + Math.random());
                that.el_form.find('[name=keystring]').val('');
            } else {
                that.setError();
                that.el.find('dd, dt').each(function() {
                    var t = $(this);
                    if (t.is(':visible')) {
                        t.hide();
                    } else {
                        t.show();
                    }
                });
                tb_resize(200);
            }
        },
        'complete': function() {
            that.setBusy(false);
        }
    });
};

function LoginForm(el, is_popup, registerForm) {
    this.is_busy = false;
    this.is_popup = is_popup;

    this.el = el;
    this.el_form_login = this.el.find('form.login');
    this.el_form_reg = this.el.find('form.reg');
    this.el_error = this.el.find('.error');

    this.base_height = $('#TB_ajaxContent').height();
    
    this.registerForm = registerForm;
    
    this.init();

    this.show();
}
LoginForm.prototype.show = function() {
    var that = this;
    if (that.registerForm) {
        that.registerForm.el.fadeOut(400, function() {
            that.el.fadeIn(400);
            tb_resize(that.base_height);            
        });
    } else {
        that.el.show();
    }
};
LoginForm.prototype.setLoginError = function(str) {
    if (str) {
        this.el_error.html(str).show();
    } else {
        this.el_error.hide();
    }
};
LoginForm.prototype.setBusy = function(val) {
    if (val) {
        this.is_busy = true;
        this.el.find('.text').prop('readonly', true).end()
               .find('.submit').prop('disabled', true);
    } else {
        this.is_busy = false;
        this.el.find('.text').prop('readonly', false).end()
               .find('.submit').prop('disabled', false);
    }
};
LoginForm.prototype.init = function() {
    var that = this;
    that.el_form_login.ajaxForm({
        'beforeSubmit': function() {
            if (that.is_busy) {
                return false;
            }
            that.setBusy(true);

            var l = $.trim(that.el_form_login.find('input[name=l]').val());
            var p = $.trim(that.el_form_login.find('input[name=p]').val());

            if (l == '' || p == '') {
                that.setLoginError(not_all_fields_are_filled + '.');
                that.setBusy(false);
                return false;
            }
            if (!/^\S+@[\w.-]+\.\w+$/.test(l)) {
                that.setLoginError(incorrect_email + '.');
                that.setBusy(false);
                return false;
            }
        },
        'dataType': 'json',
        'success': function(json) {
            if (json.status == 0) {
                that.setLoginError(json.msg);
            } else if (json.status == 1) {
                location.reload(true);
            } else if (json.status == 2) {
                that.el_form_login.hide();
                that.el_form_reg.find('input[name=id]').val(that.el_form_login.find('input[name=l]').val());
                that.el_form_reg.find('input[name=key]').val(that.el_form_login.find('input[name=p]').val());
                that.el_form_reg.show();
            }
        },
        'complete': function() {
            that.setBusy(false);
        }
    });
    that.el_form_reg.ajaxForm({
        'beforeSubmit': function() {
            if (that.is_busy) {
                return false;
            }
            that.setBusy(true);
            if (that.is_popup) {
                if (that.registerForm) {
                    that.registerForm.show();
                    setTimeout(function() { that.setBusy(false); }, 2000);
                    return false;
                }
            } else {
                var id = that.el_form_reg.find('input[name=id]').val();
                var key = that.el_form_reg.find('input[name=key]').val();

                tb_remove();
                tb_show(null, this.url + '&id=' + encodeURIComponent(id) + '&key=' + encodeURIComponent(key) + '&width=500&height=420', false);
                setTimeout(function() { that.setBusy(false); }, 2000);
                return false;
            }
        },
        'dataType': 'html',
        'success': function(html) {
            that.el.after(html);
            var reg = that.el.next('#bregister');
            that.registerForm = new RegisterForm(reg, that);
            that.registerForm.show();
            setTimeout(function() { that.setBusy(false); }, 2000);
        },
        'error': function() {
            that.setBusy(false);
        }
    });
    that.el_form_reg.find('input[type=button]').click(function() {
        that.el.find('form.reg').hide();
        that.el.find('form.login').show();
    });
    that.el.find('dt span.title').click(function() {
        var dt = $(this).parent();
        var dd = dt.next();
        var v = dd.is(':visible');
    
        dt.siblings('dd').hide().end()
          .siblings('dt').removeClass('opened');
    
        if (v) {
            dd.hide();
            dt.removeClass('opened');
        } else {
            dd.show();
            dt.addClass('opened');
        }
    });
};



$(function() {
    $('.nlvb-num').each(function() {
        var num = parseInt($(this).find('.num').html(), 10);
        voteobj.drawCircle(this, num);
    });
});

(function() {
    var tpl_actions2 = null;
    var mouseleave_actions2 = function() {
        $(this).hide();
        return false;
    };
    $('.nlhh_icon').live('click', function() {
        var item = $(this);
        if (tpl_actions2 === null) {
            if (!document.getElementById('nl_actions2')) {
                return;
            }
            tpl_actions2 = tmpl('nl_actions2');
        }
        
        var actions2 = item.siblings('.actions2');
        if (actions2.is(':empty')) {
            actions2.html(tpl_actions2({
                'id': item.data('id'),
                'author_eid': item.data('author-eid'),
                'author': item.data('author'),
                'isadmin': item.data('isadmin'),
				'lname': item.data('lname'),
				'fname': item.data('fname')
            }));
            actions2.bind('mouseleave', mouseleave_actions2);
        }
        
        actions2.toggle('fast');
        return false;
    });
})();

$('.show_share').live('click', function() {
    var o = $(this).closest('.actions').offset();
    var win = $('.share_window');
    var h = win.show().height();
    win.hide().css({
        'left': o.left,
        'top': o.top - h - 10
    }).show('fast');
    return false;
});
$('.nl-actions').live('click', function() {
    var em = $('.news-actions-block');
    $(em).clone().appendTo($(this).parent()).css({
        'position': 'absolute',
        'left': 0,
        'top': 15}).show('fast');

    return false;
});

$('.comm-actions').live('click', function() {
    $('li.cm .actions').remove();
    if ($(this).hasClass('shown')) {
        $(this).removeClass('shown');
        return;
    }
    $(this).addClass('shown');
    var classes = $(this).attr('class');
    var matches= classes.match(/item(\d+)/);
    var comm_id=matches[1];
    var is_editable=$(this).closest('.comment-item').find('input[name=is_editable]').val();
    var is_ban=$(this).closest('.comment-item').find('input[name=is_ban]').val();
    var em = $('.comm-actions-block').clone().removeClass('comm-actions-block');
    if(is_editable==0){
        /*delete edit item from menu*/
        $(em).find('a.edit').parent().remove();
    }
    /*if(is_ban==0){*/
        /*delete ban item from menu*/
        $(em).find('a.ban').parent().remove();
    /*}*/
    var html = $(em).html();
    html = html.replace(/comm_id/g, comm_id);
    $(em).html(html);
    $(em).appendTo($(this).closest('li')).css({
        'position': 'absolute',
        'left': 0,
        'top': 15}).show('fast');
    return false;
});

if (typeof voteobj == 'undefined') {
    var voteobj = {};
}

voteobj.drawCircle = function(em, num) {
    var canvas = $(em).find('.draw_circle').get(0);
    if (num < 0) {
        num = -num;
        $(canvas).attr('src','/img/v3/vote-m.png');
    } else {
        $(canvas).attr('src','/img/v3/vote-p.png');
    }

    var temp = num;
    var numLetters = 0;
    while (temp > 0) {
        temp = Math.floor(temp / 10);
        numLetters++;
    }
    var min = Math.pow(10, numLetters - 1);
    var max = Math.pow(10, numLetters) - 1;

    var all = max - min;

    var percent = (num - min) / all;
    //console.log(percent);
    //return;
    //9px width letter
    //8px for indents
    var rad = ((numLetters) * 9 + percent * 9 + 10) / 2;
    rad = Math.ceil(rad);
    /*
     if(rad>22)
     {
     rad=22;
     }*/

    $(canvas).attr('width', rad * 2).attr('height', rad * 2).css({
        'width': rad * 2,
        'height': rad * 2
    });
    $(em).css({
        'width': rad * 2,
        'line-height': rad * 2 + 'px',
        'height': rad * 2
    });
    return true;
};

