// функция проверки данных из формы авторизации
function onformsubmit(name) {
    var f = document.forms[name];

    if (!f) {
        alert('Несовместимый браузер');
        return false;
    }

    if (!f.elements['login'].value) {
        alert('Введите логин!');
        return false;
    }

    if (!f.elements['password'].value) {
        alert('Введите пароль!');
        return false;
    }

    return true;
}

var ns6=document.getElementById&&!document.all;

function restrictinput(maxlength, e, placeholder) {
    if (window.event && event.srcElement.value.length >= maxlength)
        return false;
    else if (e.target && e.target == eval(placeholder) && e.target.value.length >= maxlength) {
        var pressedkey = /[a-zA-Z0-9\.\,\/]/;
        if (pressedkey.test(String.fromCharCode(e.which))) e.stopPropagation();
    }
}

function countlimit(maxlength, e, placeholder, idCounter) {
    var theform = eval(placeholder);
    var lengthleft = maxlength-theform.value.length;
    var placeholderobj = document.all ? document.all[placeholder] : document.getElementById(placeholder);

    if (window.event || e.target&&e.target == eval(placeholder)) {
        if (lengthleft < 0) {
            theform.value = theform.value.substring(0, maxlength);
            lengthleft = 0;
        }
        document.getElementById(idCounter).innerHTML = 'Осталось ' + lengthleft + ' символов.';
    }
}

function displaylimit(thename, theid, thelimit, idCounter) {
    var theform = theid != "" ? document.getElementById(theid) : thename;
    if (document.all) {
        eval(theform).onkeypress = function() { return restrictinput(thelimit, event, theform); };
        eval(theform).onkeyup = function(){ countlimit(thelimit, event, theform, idCounter); };
    }
    else if (ns6) {
        document.body.addEventListener('keypress', function(event) { restrictinput(thelimit, event, theform); }, true);
        document.body.addEventListener('keyup', function(event) { countlimit(thelimit, event, theform, idCounter); }, true);
    }
}

function revalidate(index) {
    var my_form = document.getElementById(index);
    var check   = 1;
    if (my_form)
        $.each(my_form['elements'], function(i, n){
            if (n.getAttribute('id') == 'mustHave') {
                if (!n.value) check = 0;
            }
        });

    return check;
}

function check_disability(index) {
    var my_form = document.getElementById(index);
    if (my_form) {
        $.each(my_form['elements'], function(i, n){
            if (n.name == 'sendButton') {
                n.disabled = !(revalidate(index));
                return true;
            }
        });
    }
}

function form_init(index) {
    var my_form = document.getElementById(index);
    if (my_form) {
        $.each(my_form['elements'], function(i, n){
            if (n.getAttribute('id') == 'mustHave') {
                n.onblur = function () { check_disability(index); };
                n.onkeyup = function () { check_disability(index); };
                n.onkeydown = function () { check_disability(index); };
            }
        });
    }
}

var activeUserLink;

// функция вывода профиля пользователя
function showProfile(e, id_user, obj) {

    var isIE = navigator.userAgent.toLowerCase().indexOf("msie") != -1;

    if (isIE && event) {
        var pY = document.documentElement.scrollTop  || document.body.scrollTop;
        var pX = document.documentElement.scrollLeft || document.body.scrollLeft;
        var x = event.x + pX;
        var y = event.y + pY;
    }
    else if (e) {
        x = e.pageX;
        y = e.pageY;
    }

    if (x && y) {
        // убираем старую подсветку
        if (activeUserLink && activeUserLink.length > 0) activeUserLink.css({backgroundColor: 'white'});
        // подсвечиваем ссылку
        activeUserLink = $(obj);
        activeUserLink.css({backgroundColor: '#DEF4FF'});
        // считаем смещение по горизонтали, чтобы не выходило за пределы экрана
        var h_offset = $(document).width() - x;
        if (h_offset < $('#profileWindow').width()) x = x - $('#profileWindow').width();

        $('#profileWindow').css({position: 'absolute', left: x, top: y + 7 }).fadeIn('slow');
        $.ajax({
            type: "GET",
            url: showProfileLink + '&id_user=' + id_user,
            dataType: "html",
            beforeSend: function(data) {
                $('#profileWindow').html('<div class="headerProfile"><img src="/images/ajax-loader-small.gif">&nbsp;Идет загрузка данных...</div>');
            },
            success: function(data) {
                $('#profileWindow').html(data);
                $('#profileBody').slideDown('normal');
            }
        });
    }
}

// функция закрытия окна профиля
function hideProfile() {
    // убираем подсветку ссылки
    activeUserLink.css({backgroundColor: 'white'});
    // закрываем окно
    $('#profileWindow').hide();
}

// функция разворачивания окна
function openFullWindow() {
    $('#blocks').hide();
    $('#leftblock').hide();
    $('#module').attr('colspan', 4);

    linkF = $('<a>Свернуть окно</a>').click( function() { closeFullWindow(); });
    $('#linkFullScreen').html(linkF);

    $.ajax({
        type: "GET",
        url: LinkFullScreen + '&open=1',
        dataType: "html"
    });
}

// функция сворачивания окна
function closeFullWindow() {
    $('#blocks').show();
    $('#leftblock').show();
    $('#module').attr('colspan', 3);

    linkF = $('<a>Развернуть окно</a>').click( function() { openFullWindow(); });
    $('#linkFullScreen').html(linkF);

    $.ajax({
        type: "GET",
        url: LinkFullScreen + '&open=0',
        dataType: "html"
    });
}

// учет клика яндекса
function r(w, a) {
    var unique = new Date().getTime();
    var path = a ? a.href : document.location;
    document.createElement('IMG').src = 'http://clck.yandex.ru/click/dtype=' + w + '/u=' + unique + '/*' + path;
}