// функция проверки данных из формы авторизации
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 && window.event.srcElement.value && window.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;
}

// функция начала индикации аякс запроса
function startAjaxRequest() {
    var nProcessing       = $('#ajax_processing');
    var overlayProcessing = $('#ajax_overlay');
 
//    if (overlayProcessing.length == 0) {
        overlayProcessing = document.createElement( 'div' );
        overlayProcessing.setAttribute( 'id', 'ajax_overlay' );
        $(overlayProcessing).appendTo('body');
        $(overlayProcessing).height($(document).height()); 
  //  }

    if (nProcessing.length == 0) {
        nProcessing = document.createElement( 'div' );
        nProcessing.setAttribute( 'id', 'ajax_processing' );
        nProcessing.innerHTML = '<span class="ajaxLoadingSmall" style="display: inline;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>Идет загрузка...';
        if ($.browser.msie) $(nProcessing).height('50');
        $(nProcessing).appendTo('body');
    }
    
    $('#ajax_overlay, #ajax_processing').show();
}

// функция выполнения аякс запроса
function stopAjaxRequest() {
    $('#ajax_processing, #ajax_overlay').hide();
}

// функция выбора типа рабочей информации
function showWorkStat(type, obj) {
    $.ajax({
        type: "GET",
        url: LinkFullScreen + '&stat=' + type,
        dataType: "html",
        beforeSend: function() {
            $(obj).after('<span class="ajaxLoadingSmall" style="display: inline;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>');
        },
        complete: function(data) {
            $(obj).next().remove();
        },
        success: function(data) {
            $('#dynam_stat_work').html(data);
        }
    });
}

// форма изменения статуса пользователя
function userStatusEdit(edit_link) {
    // удаляем старую форму
    $('#objectForm').remove();

    // загружаем новую форму
    $.ajax({
        type: "GET", url: edit_link, dataType: "html",
        beforeSend: startAjaxRequest,
        complete: stopAjaxRequest,
        success: function(data) {
            // если ответ - не диалог, то обертываем в диалог для вывода
            if (data.indexOf('objectForm') == -1) data = '<div id="objectForm" style="display: none;" title="Сообщение">' + data + '</div>';
            // вставляем полученный ответ
            $(data).appendTo("body");
            // открываем форму
            $("#objectForm").dialog({
                bgiframe: true, autoOpen: false, height: 250, width: 530, modal: true,
                close: function() {
                    $('#objectForm form').clearForm();
                },
                buttons: {
                    'Закрыть': function() {
                        $(this).dialog('close');
                    },
                    'Сохранить': function() {
                        $('#objectForm form').ajaxSubmit({
                            dataType: 'json',
                            success: function(data) {
                                $('#userStatus img').remove();
                                if (data.text) $('#userStatus a').text(data.text);
                                if (data.icon) $('#userStatus a').before("<img src='/images/smiles/" + data.icon + ".gif' align='absmiddle'>");
                                $('#objectForm').dialog('close');
                            },
                            complete: stopAjaxRequest,
                            beforeSubmit: startAjaxRequest
                        });
                    }
                }
            });
            $('#objectForm').dialog('open');
       }
    });
}
