var ns6=document.getElementById&&!document.all

$(function() {
    var options = {
        dataType : 'json',
        success: function(data) {
            if (data.error) {
                $('.ajaxError').text(data.error);
                $('#loading').html('<br><input type="submit" value=" Отправить ">');
            }
            else {
                $('#formComments').html("<center><div class='ajaxComplete'>Спасибо! Ваш комментарий добавлен.</div></center>");
            }
            
            if (data.body) $(".listComments").replaceWith(data.body);
        },
        beforeSubmit: function() {
            $('#loading').html('<div class="ajaxLoading">идет обмен данными...</div>');
        }
    };
    $('#formComments').ajaxForm(options);
});

// функция проверки заполненности строки поиска
function checkSearch() {
    if (!$('#formSearch input[name="names"]').val()) {
        alert('Укажите строку поиска!');
        $('#formSearch input[name="names"]').focus();
        return false;
    }

    return true;
};

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); };
            }
        });
    }
}

// функция для добавления страницы в соц закладки
function socialBookmarks() {
    // параметры закладки
    var title = encodeURIComponent(document.title);
    var url   = encodeURIComponent(location.href);

    var dir='/images/services/';

    var services = [
        ['bobrdobr.ru/addext.html?url='+url+'&title='+title,'bobr.gif','BobrDobr'],
        ['memori.ru/link/?sm=1&u_data[url]='+url+'&u_data[name]='+title,'memori.gif','Memori'],
        ['www.mister-wong.ru/index.php?action=addurl&bm_url='+url+'&bm_description='+title,'wong.gif','Mister Wong'],
        ['del.icio.us/post?v=4&noui&jump=close&url='+url+'&title='+title,'del.gif','del.icio.us'],
        ['zakladki.yandex.ru/userarea/links/addfromfav.asp?bAddLink_x=1&lurl='+url+'&lname='+title,'yandex.gif','Yandex'],
        ['www.google.com/bookmarks/mark?op=add&bkmk='+url+'&title='+title,'google.gif','Google'],
        ['moemesto.ru/post.php?url='+url+'&title='+title,'mm.gif','MoeMesto']];

    var btn = '';

    for (i=0;i<services.length;i++)
        btn += '<a href="http://'+services[i][0]+'" title="' + services[i][2] + '" target="_blank"><img src="'+dir+services[i][1]+'" alt="'+services[i][2]+'" style="border:0;padding:0;margin:0 4px 0 0;"></a>';
    document.write(btn);
}

function w(obj, param) {
    obj.href = param;
}

// учет клика яндекса
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;
}

// функция оценки объекта
function rateSend(obj, my_link) {
    $.ajax({
        type: "GET",
        url: my_link,
        dataType: "json",
        success: function(data) {
            $(obj).parents('.rateBlock').replaceWith('<p style="float: right; font-size: 13px;"><b>' + (data.status ? 'Оценено!' : 'Ваша оценка: ' + data.rate) + '</b></p>');
        }
    });
}

// функция показа меню пользователя
function showUserMenu(e, id_user, login, link_profile, chat) {

    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) {

        var userMenu  = '<div id="chat-box-user-menu"><div style="overflow: auto; width: 160px;"><div id="chat-box-user-menu-head">' + login + '</div>';
            userMenu += '<div style="float: right;"><a onClick="hideUserMenu();" style="cursor: pointer;" title="Закрыть окно"><img src="/images/close.gif" alt="Закрыть меню пользователя"></a></div></div>';
            userMenu += '<ul><li id="chat-box-link-profile"><img src="/images/smiles/icon2.gif" align="absmiddle"><a target="_blank" href="' + link_profile + '&id=' + id_user + '" class="mod_link" title="Перейти на профиль пользователя в новом окне">Профиль пользователя</a></li>';
        if (chat) userMenu += '<li id="chat-box-link-private"><img src="/images/smiles/icon1.gif" align="absmiddle"><a class="mod_link" onClick="openUserPrivate(' + id_user + ');" title="Открыть приват-канал с пользователем">Перейти в приват</a></li>';
            userMenu += '</ul></div>';

        $('body').append(userMenu);

        // считаем смещение по горизонтали, чтобы не выходило за пределы экрана
        var h_offset = $(document).width() - x;
        if (h_offset < $('#chat-box-user-menu').width()) x = x - $('#chat-box-user-menu').width();

        $('#chat-box-user-menu').css({position: 'absolute', left: x, top: y + 7 }).fadeIn('slow');

        // вешаем закрытие по нажатию вне меню
        $('#chat-box-user-menu').hover(function() {
            $(document).one('click', function() {
                hideUserMenu();
            });
        });
    }
}

// функция закрытия окна меню
function hideUserMenu() {
    // закрываем окно
    $('#chat-box-user-menu').remove();
}
