//Функция показа окна контекстной помощи
function showHelpWindow(notionName,html)
{
    var chelp_win;
    if (chelp_win = Windows.getWindow('content_help_window'))  //проверяем, было ли удалено окно
    {
        chelp_win.close();

    }
    //создаем эффект открытия окна
    var effect = new PopupEffect(html, {className: "popup_effect",duration:0.2});

    //создаем окно
    chelp_win = new Window('content_help_window',
        {className: "alphacube", width:500, height:500, zIndex: 100, resizable: true, maximizable: false,
         minimizable: false, title: "Справочное окно", draggable:true, wiredDrag: true, destroyOnClose: true,
         showEffect:effect.show.bind(effect)}
                                );

    //инициализируем "сохранялку" состояния окна
    WindowStore.init('help_window_store');
    chelp_win.getContent().innerHTML=
        "<div style='padding:10px; text-align:center'>"+
            "Идет загрузка, пожалуйста подождите...<br/>&nbsp;<br/><img src='/images/progress.gif' alt='' />"+
        "</div>";

    var cookie = WindowUtilities.getCookie('content_help_window');
    if (cookie != null)
    {
        chelp_win.show();
    } else
    {
        chelp_win.showCenter();
    }

///Включаем Ajax///////////////////////////////////////////////////
    // Create new JsHttpRequest object.
    var req = new JsHttpRequest();
    // Code automatically called on load finishing.
    req.onreadystatechange = function()
    {
        if (req.readyState == 4) {
            if(req.responseJS && req.responseJS.error == 0)
            {
                var also ='';
                if (req.responseJS.help_source != 0)
                {
                    also = '<p class="context_help_also"><a href="?menu_id=90901'+req.responseJS.help_source+'#'+notionName+'">Подробнее >></a></p>';
                }

                chelp_win.getContent().innerHTML = '<div class="context_help">'+req.responseJS.help_text+also+"</div>";
                chelp_win.setTitle('Справка: '+notionName);
            } else
            {
                chelp_win.getContent().innerHTML = '<h3 align="center" style="padding:15px;">Невозможно отобразить страницу помощи.</h3>';
            }

        }
    }
    // Enable caching of the query results
    req.caching = true;
    // Prepare request object.
    req.open('POST', '?menu_id=80902', true);
    // Send data to backend.
    req.send( { 'action': 'show_notion', 'notionName': notionName } );

}

//Диспетчер помощи
function HelpDispatcher(htmlElement)
{
    //Проверка правильности задания параметров конструктора
    if (!htmlElement || typeof(htmlElement)!="object")
        throw "Sorry, \"htmlElement\" argument of HelpDispatcher should be an HTML element";

    //сохранение ссылки на объект
    this.htmlElement = htmlElement;

    //сохранение объекта в документе
    document.helpDispatcher = this;

    //инициализация массива div элементов для которых будет выводиться помошь
    this.div_array = new Array();

    //инициализация массива элементов для которых будет выводиться помошь
    this.help_array = new Array();

    //инициализация массива notions для элементов для которых будет выводиться помошь
    this.notion_array = new Array();

    Event.observe(htmlElement, "mouseout", this.eventMouseOut);
    Event.observe(htmlElement, "click", this.eventClick);
    Event.observe(document, "keydown", this.eventKeyDown);

}

HelpDispatcher.prototype =
{
    first_start : true,
    active      : false,
    
    eventMouseOut: function(event)
    {
        Event.element(event).style.cursor = "pointer";
    },

    eventClick: function(event)
    {
        var element = Event.element(event);
        if(document.helpDispatcher.active)
        {
            //деактивация диспетчера
            document.helpDispatcher.deactivation(element);
        } else
        {
            if(document.helpDispatcher.help_array.length > 0)
            {
                //активация диспетчера
                document.helpDispatcher.activation(element);
            }
        }
    },

    eventKeyDown: function(event)
    {
         var characterCode = event.which || event.keyCode;
         if (characterCode == Event.KEY_ESC && document.helpDispatcher.active)
         {
            document.helpDispatcher.deactivation(document.helpDispatcher.htmlElement);         
         }
    },
    
    //активация диспетчера
    activation: function(element)
    {
        document.body.style.cursor = "help";

        if (this.first_start)
        {
            for (var i = 0; i < this.help_array.length; i++)
            {
                this.divActivation(this.help_array[i],this.notion_array[i])
            }

            this.first_start = false
        }

        for (var i = 0; i < this.div_array.length; i++)
        {
            this.div_array[i].style.display = "inline";
        }

        element.style.cursor = "help";
        element.className = "help_dispatcher_on";

        this.active = true;
    },

    //деактивация диспетчера
    deactivation: function(element)
    {
        element.className = "help_dispatcher_off";
        document.body.style.cursor = "default";
        element.style.cursor = "default";

        for (var i = 0; i < this.div_array.length; i++)
        {
            this.div_array[i].style.display = "none";
        }


        this.active = false;
    },

    //метод - установщик помощи на элемент
    addHelpTarget: function(element, notionName)
    {
        this.notion_array.push(notionName);
        this.help_array.push(element);
        
        //var notion = document.getElementById(element);
        ///Event.observe(notion, "click", this.divEventClick);
    },

    //метод, осуществляющий добавление div при первом запуске
    divActivation: function(element,notionName)
    {
        var position = Position.cumulativeOffset(element);
        var size = element.getDimensions();

        // Create a div
        var div = document.createElement("div");
        div.className = "help_div_layer_out";
        div.style.height = size.height + "px";
        div.style.width  = size.width  + "px";
        div.style.top    = position[1] + "px";
        div.style.left   = position[0] + "px";
        div.style.position = "absolute";
        div.style.display = "none";
        div.notionName = notionName;       //сохраняем  notionName
        document.body.appendChild(div);

        Event.observe(div, "mouseover", this.divEventMouseOver);
        Event.observe(div, "mouseout", this.divEventMouseOut);
        Event.observe(div, "click", this.divEventClick);

        this.div_array.push(div);
    },

    //обработчиr события для div
    divEventMouseOver: function(event)
    {
        Event.element(event).className = "help_div_layer_over";
    },

    //обработчиr события для div
    divEventMouseOut: function(event)
    {
        Event.element(event).className = "help_div_layer_out";
    },

    //обработчиr события для div
    divEventClick: function(event)
    {
        var element = Event.element(event);
        showHelpWindow(element.notionName,element);
        document.helpDispatcher.deactivation(document.helpDispatcher.htmlElement);
    }

}

