var HydraEditorToolbar = function()
{
    // Определяем тип броузера
    this.init_browser_type();

    // Текущий выбранный объект
    this.last_selected_object = false;
    // Текущий range
    this.range = false;

    
}

HydraEditorToolbar.prototype.init_browser_type = function()
{
    if (navigator.appName == 'Microsoft Internet Explorer') {
        this.browser_type = 'ie';
    }

    if (navigator.appName == 'Netscape') {
        this.browser_type = 'gecko';
    }
}

/**
 * Инициализация тулбара с заданном контейнере
 * @param string container_id  идентификатор контейнера, в который надо загружать тулбар
 */
HydraEditorToolbar.prototype.init = function(toolbar_container_id, content_container_id)
{
    
    var toolbar_container = hydra.get(toolbar_container_id);
    if (!toolbar_container) {
       // alert("Некуда загружать тулбар");
        return false;
    }

    if (hydra.get('for-'+content_container_id)) {
        // если такой тулбар уже создан, то нечего инитить
        return true;
    }

    

    var toolbar = document.createElement('ul');
    toolbar.setAttribute('class', 'editor-toolbar');
    toolbar.setAttribute('id', 'for-'+content_container_id);
    toolbar_container.appendChild(toolbar);

    // Добавляем элементы на тулбар
    this.add_toolbar_items(toolbar, {
        html: {
           "icon" : "html.gif",
           "onclick":function() {editor_toolbar.change_mode(content_container_id);},
           "title": "Исходный код"
        },
        bold:{
            "class":"editor-toolbar-bold",
            "onclick":function() {editor_toolbar.bold();},
            "title": "Сделать текст жирным"
        },
        italic: {
            "class":"editor-toolbar-italic",
            "onclick":function() {editor_toolbar.italic();},
            "title": "Сделать текст наклонным"
        },
        underline: {
            "class":"editor-toolbar-underline",
            "onclick":function() {editor_toolbar.exec_command('Underline', true);},
            "title": "Подчеркивание текста"
        },
        StrikeThrough: {
            "class":"editor-toolbar-strikethrough",
            "onclick":function() {editor_toolbar.exec_command('StrikeThrough', true);},
            "title": "Зачеркивание текста"
        },

        undo: {
            "icon":"undo.gif",
            "onclick":function() {editor_toolbar.exec_command('Undo', 'Undo');},
            "title": "Undo"
        },

        redo: {
            "icon":"redo.gif",
            "onclick":function() {editor_toolbar.exec_command('Redo', 'Redo');},
            "title": "Redo"
        },

        link: {
            "class":"editor-toolbar-link",
            "onclick":function() {editor_toolbar.link();},
            "title": "Добавить ссылку"
        },
        unlink: {
            "class":"editor-toolbar-unlink",
            "onclick":function() {editor_toolbar.unlink();},
            "title": "Убрать ссылку"
        },
        numlist: {
            "class":"editor-toolbar-numlist",
            "onclick":function() {editor_toolbar.numlist();},
            "title": "Нумерованный список"
        },
        bullist: {
            "class":"editor-toolbar-bullist",
            "onclick":function() {editor_toolbar.bullist();},
            "title": "Ненумерованный список"
        },
        align_left: {
            "class":"editor-toolbar-align-left",
            "onclick":function() {editor_toolbar.align_left();},
            "title": "Выравнивание влево"
        },
        align_right: {
            "class":"editor-toolbar-align-right",
            "onclick":function() {editor_toolbar.align_right();},
            "title": "Выравнивание вправо"
        },
        align_justify: {
            "class":"editor-toolbar-align-justify",
            "onclick":function() {editor_toolbar.align_justify();},
            "title": "Полное выравнивание"
        },
        align_center: {
            "class":"editor-toolbar-align-center",
            "onclick":function() {editor_toolbar.align_center();},
            "title": "Выравнивание по центру"
        },
        insert_image: {
            "class":"editor-toolbar-insert-image",
            "onclick":function() {editor_toolbar.insert_image();},
            "title": "Добавить картинку"
        },
        font: {
            "class":"editor-toolbar-font",
            "onclick":function() {editor_toolbar.show_submenu(this, 'choose-fonts-menu', 'create_font_menu' );},
            "title": "Изменить шрифт"
        },
        format: {
            "class":"editor-toolbar-format",
            "onclick":function() {editor_toolbar.show_submenu(this, 'choose-format-menu', 'create_format_menu' );},
            "title": "Форматирование блока"
        },
        clear_format: {
            "class":"editor-toolbar-clearformat",
            "onclick":function() {editor_toolbar.clear_format();},
            "title": "Очистить форматирование"
        },
        indent: {
            "class":"editor-toolbar-indent",
            "onclick":function() {editor_toolbar.exec_command("Indent", true);},
            "title": "Увеличить отступ (сделать подсписок)"
        },
        outdent: {
            "class":"editor-toolbar-outdent",
            "onclick":function() {editor_toolbar.exec_command("Outdent", true);},
            "title": "Уменьшить отступ (выйти из подсписка)"
        },
        tidy_clean: {
            "class":"editor-toolbar-clearformat",
            "onclick":function() {editor_toolbar.tidy_clean(content_container_id);},
            "title": "Чистка html"
        },
        text_color: {
            "class":"editor-toolbar-colortext",
            "onclick":function() {editor_toolbar.set_text_color(this);},
            "title": "Цвет текста"
        },
        create_table: {
            "class":"editor-toolbar-create-table",
            "onclick":function() {editor_toolbar.create_table(this);},
            "title": "Создание таблицы"
        },
        borders: {
            "icon":"borders.gif",
            "onclick":function() {
                editor_toolbar.show_dropdown('borders-window', function(elem) {
                    editor_toolbar.set_borders(elem);
                }, this);

            },
            "title": "Границы элемента"
        },
        properties: {
            "icon":"properties.gif",
            "onclick":function() {
                editor_toolbar.show_dropdown('elem-properties-window', function(elem) {
                    editor_toolbar.create_properties_window(elem);
                }, this, function(){
                    editor_toolbar.fill_elem_properties();
                });

            },
            "title": "Свойства элемента"
        },
        font_size: {
            "icon":"font_size.gif",
            "onclick":function() {
                editor_toolbar.show_dropdown('elem-fontsize-window', function(elem) {
                    editor_toolbar.create_fontsize_window(elem);
                }, this);

            },
            "title": "Размер шрифта"
        }
    });
}

/**
 * Создает кнопки на панели управления
 *
 * @param object toolbar_elem контейнер для кнопок - ul
 * @param array items  массив кнопок
 * <code>
 *  (
 *      ["class"] - класс ссылки
 *      ["onclick"] -  функция, которая будет вызываться при клике
 *  )
 * </code>
 */
HydraEditorToolbar.prototype.add_toolbar_items = function(toolbar_elem, items)
{
    for (var item_index in items) {
        var item = items[item_index];

        var li = document.createElement('li');
        var a = document.createElement('button');
        if (item['class'] != undefined) {
            a.setAttribute('class', 'editor-toolbar-item '+item['class']);
        }

        if (item['icon'] != undefined) {
            a.style.backgroundImage = 'url(../_components/editor_toolbar/i/'+item['icon']+')';
        }
        
        a.onclick = item["onclick"];

        if (item["caption"] != undefined) {
           a.innerHTML = item["caption"];
        }

        if (item["title"] != undefined) {
           a.title = item["title"];
        }

        li.appendChild(a);
        toolbar_elem.appendChild(li);
    }
}

/**
 * Переключает режим работы редактора html/design_mode
 */
HydraEditorToolbar.prototype.change_mode = function(content_container_id)
{
    // Получаем наш редактируемый div
    var design = hydra.get(content_container_id);
    var html = hydra.get(content_container_id+"-html");
    // Если у нас еще не создана текстовая область
    if (!html) {
        html = create_textarea_for(content_container_id);
    }
    

    // Если у нас видимый div
    if (html.style.display == "none") {
        design.style.display = "none";
        html.value = design.innerHTML;
        html.style.display = "block";
        return;
    }
    else    {
        design.innerHTML = html.value;
        html.style.display = "none";
        design.style.display = "block";
    }
    
}

HydraEditorToolbar.prototype.get_content = function(content_container_id)
{
    var design = hydra.get(content_container_id);
    return design.innerHTML;
}

/**
 * Возвращает объект выделения
 */
HydraEditorToolbar.prototype.get_selection = function()
{
    if (document.selection != undefined) {
        return document.selection;
    }
    
    var selection = window.getSelection();

    
    
    if (!selection.type) {
            selection.type = 'Text';
    }
    if (!selection.createRange) {
            /**
             * Для FF имитируем присутствие IE ф-ций
             */
            selection.createRange = function() {
                    var range = this.getRangeAt(0);

                    range.parentElement = function() {
                            // var result = this.startContainer;
                            var result = this.commonAncestorContainer;
                            /**
                             * Если предком является елемент #text
                             */
                            if (result.nodeType == 3) {
                                    /**
                                     * Нужно получить родительский узел
                                     */
                                    result = result.parentNode;
                            }
                            return result;
                    };

                    return range;
            };
    }
    return selection;
}

/**
 * Определение выбранного объекта для гекко
 */
HydraEditorToolbar.prototype.get_gecko_selected_object = function()
{
    this.range = false;
    
    var selection = this.get_selection();
    if (!selection)    {
        return false;
    }

    // ??????
    if (selection.type == 'Text') {
        this.range = selection.createRange();
    }
    else {
        this.range = selection.getRangeAt(0);
    }

    // Проверяем было ли получено выделение в разрешенной области
    /*if (!this.can_change_elem_here(selection.anchorNode)) {
        return false;
    }*/
    
    var offset = selection.anchorOffset;
    if (selection.focusNode.childNodes.length > 0)    {
        var item = selection.focusNode.childNodes[offset];
        return item;
    }

    
    
    


    return selection.anchorNode;
}

/**
 * Возвращает текущий выбранный объект
 */
HydraEditorToolbar.prototype.get_selected_object = function()
{
    // Пока определяем выбранный объект только для гекко
    return this.get_gecko_selected_object();
}

HydraEditorToolbar.prototype.bold2 = function()
{
    var range = window.getSelection().getRangeAt(0);
  if (range != null) {
    var span = document.createElement('strong');
    span.className = 'myClass';
    range.surroundContents(span);
  }
return true;

    //alert(window.getSelection());
    var selection = this.get_selection();
    
    selection = "<strong>"+selection+"</strong>";
    document.execCommand('inserthtml', false, selection);
  
}
HydraEditorToolbar.prototype.clear_format = function()
{
    //debugger;
    var object = this.get_selected_object();
    if (object.toString() == "[object Text]") {
        // Если выделен текст - то пробуем найти родительский узел
        var parent_node = object.parentNode;

        if (!parent_node.hasAttribute("contentEditable")) {
            object = parent_node;
        }
        else {
            // Если родительский узел contentEditable - то скорее всего это div публикации а его трогать нельзя
            alert("Не найден форматирующий тег - не от чего чистить.");
            return false;
        }
        
        
    }

    var content = object.textContent;
    var new_node = document.createTextNode(content);

    /**
    // Получаем коллекцию детей
    var children = object.childNodes;
    if (children.length && children.length == 1) {
        var item = children.item(0);

        // Если у нас текстовый узел
        if (item.nodeType ==3) {
            var content = item.nodeValue;
            var new_node = document.createTextNode(content);
        }
        else {
            // Если ребенок не текстовый узел
            //var tag_name = item.tagName;
            //var new_node = document.createElement(tag_name);
            var new_node  = item.cloneNode(true);
        }
    }
    **/

    var parent = object.parentNode;
    parent.replaceChild(new_node, object);
}


HydraEditorToolbar.prototype.bold = function()
{
    //alert(this.get_selected_object());
    window.document.execCommand("bold", null, "");
}

/**
 * Устанавливает цвет текста
 * @param Object btn копка, которая инициировала клик
 */
HydraEditorToolbar.prototype.set_text_color = function(btn)
{
    var win = hydra.get( 'editor-set-text-color');
    if (!win) {
        // Создаем окно выбора цвета
        win = this.create_color_menu(btn, 'editor-set-text-color',
            function(color)
            {
                editor_toolbar.exec_command('ForeColor', color);
                var win = hydra.get( 'editor-set-text-color');
                win.style.display = 'none';
            });
    }
    else {
        if (win.style.display == 'block') {
            win.style.display = 'none';
        }
        else {
            win.style.display = 'block';
        }
    }
}

HydraEditorToolbar.prototype.italic = function()
{
    window.document.execCommand("italic", null, "");
}

HydraEditorToolbar.prototype.list = function()
{
    window.document.execCommand("bold", null, "");
}

/**
 * Создает ссылку из выделенного элемента
 */
HydraEditorToolbar.prototype.link = function()
{
    
    // Запоминаем объект выделения
    this.last_selected_object = this.get_selected_object();
    
    

    var win = new cHydraWindow(
        'link_window',
        'Создание ссылки',
        false,
        false,
        function(){ 
            var container = hydra.get("link_window_container");

            var label = document.createElement("label");
            label.textContent = "URL ссылки:";
            container.appendChild(label);

            var input = document.createElement("input");
            input.setAttribute("id", "et_link_url");

            /*if (editor_toolbar.last_selected_object) {
                input.setAttribute("value", editor_toolbar.last_selected_object.getAttribute("href"));
            }*/

            container.appendChild(input);

            var btn = document.createElement("button");
            btn.textContent = "Ссылка на файл";
            hydra_add_event(btn, "click", function(){fm2_show("et_link_url");});
            container.appendChild(btn);

            var apply_btn = document.createElement("button");
            apply_btn.textContent = "Применить";
            hydra_add_event(apply_btn, "click", function(){
                editor_toolbar.set_link(hydra.get("et_link_url").value);
            });
            container.appendChild(apply_btn);
        },
        false,
        280,
        100
    );
    return true;

    //var url = prompt("Enter a URL:", "http://");

    
    
}

HydraEditorToolbar.prototype.set_link = function(url)
{
    
    var link = this.range;
    if (!link)
        link = this.last_selected_object; //this.get_selected_object();

    // Объектное изменение ссылки
    if (link) {
        if (link.tagName == "A") {
            link.href = url;

                destroy_window("link_window");
            return true;
        }
    }
    

    // Создание ссылки с нуля
    this.wrap_selection_by_tag("a", {"href":url}, false, link);

    destroy_window("link_window");
}

HydraEditorToolbar.prototype.unlink = function()
{
    window.document.execCommand("unlink", null, "");
    return true;

    var link = this.get_selected_object();
    if (!link) {
        return false;
    }
    if (link.tagName == "A") {
        //link.href = url;
        alert(link.innerHTML);
        return true;
    }

    
}

HydraEditorToolbar.prototype.wrap_selection_by_tag = function(tag_name, attr, styles, selection)
{
      //var range = window.getSelection().getRangeAt(0);
      
/*      if (!selection)
        selection = this.get_selection();
      
      var range = selection.createRange();*/
      
      var range = this.range;

      if (range != null) {
        var elem = document.createElement(tag_name);

        // Проставляем аттрибуты
        if (typeof(attr)=="object" || typeof(attr)=="array") {
            for (var attr_name in attr) {
                elem.setAttribute(attr_name, attr[attr_name]);
            }
        }
            
        // Простановка стилей
        if (typeof(styles)=="object" || typeof(attr)=="array") {
            for (var style_name in styles) {
                elem.style[style_name] = styles[style_name];
            }
        }
        
        range.surroundContents(elem);
      }
}

HydraEditorToolbar.prototype.numlist = function()
{
    window.document.execCommand("InsertOrderedList", null, "");
}

HydraEditorToolbar.prototype.bullist = function()
{
    window.document.execCommand("InsertUnorderedList", null, "");
}

HydraEditorToolbar.prototype.align_left = function()
{
    this.set_elem_align("left");
    //window.document.execCommand("JustifyLeft", null, "");
}

HydraEditorToolbar.prototype.align_right = function()
{
    this.set_elem_align("right");
    //window.document.execCommand("JustifyRight", null, "");
}

HydraEditorToolbar.prototype.align_justify = function()
{
    this.set_elem_align("justify");
}

HydraEditorToolbar.prototype.align_center = function()
{
    this.set_elem_align("center");
}

HydraEditorToolbar.prototype.set_elem_align = function(align)
{
    // Если у нас объект, то делаем ему выравнивание (например для картинки)
    var obj = this.get_selected_object();
    if (obj.tagName) {
        obj.setAttribute("align", align);
        return true;
    }
     

    // Проверяем, а вдруг у нас уже есть параграф для данного текста
    var selection = this.get_selection();
    var range = selection.createRange();
    var parent_elem = range.parentElement();

    if (parent_elem.tagName == 'P') {
        parent_elem.setAttribute("align", align);
        return true;
    }

    this.wrap_selection_by_tag("p", {"align":align});
}

HydraEditorToolbar.prototype.insert_image = function()
{
    fm2_show();
}

/**
 * Вставляет картинку в редактируемую область
 */
HydraEditorToolbar.prototype.add_image = function(href)
{
    window.document.execCommand('InsertImage', false, href);
}

HydraEditorToolbar.prototype.create_submenu = function(submenu_id, items, item_func)
{
    var ul = document.createElement('ul');
    ul.setAttribute("id", submenu_id);
    for (var item in items) {
        var li = document.createElement('li');
        var a = document.createElement('a');

        item_func(a, item, items[item]);

        li.appendChild(a);
        ul.appendChild(li);
   }

   return ul;
}

HydraEditorToolbar.prototype.create_font_menu = function(elem)
{
    var fonts = {
        arial:"Arial",
        tahoma:"Tahoma",
        times: "Times New Roman",
        courier: "Courier New",
        georgia: "Georgia",
        helvestica: "Helvetica",
        impact: "Impact",
        verdana: "Verdana"
    };

    var ul = this.create_submenu("choose-fonts-menu", fonts,
        function(a, key, value) {
            a.style.fontFamily = value;
            a.innerHTML = value;
            a.href = "javascript: editor_toolbar.set_font('"+value+"');";
        });
    elem.parentNode.appendChild(ul);
    return ul;
}

/**
* Создает окно с выбором цвета
* @param Object elem кнопка, которая инициирует открытие окна выбора цвета
* @param String window_name имя окна
* @param Function func функция, которая будет вызываться при щелчке на цвете
* @return Object элемент окна (div)
*/
HydraEditorToolbar.prototype.create_color_menu = function(elem, window_name, func)
{
    var div = document.createElement('div');
    div.setAttribute('class', "color_win");
    div.setAttribute('id', window_name);
    div.style.display = 'block';

    for(k=0; k<=5; k++)
    for(j=0; j<=5; j++)
    for(i=0; i<=5; i++) {
        var r = k*51;
        var g = j *51;
        var b = i*51;
        var hex = '#' + RGBtoHex(r,g, b);

        var btn = document.createElement('button');

        btn.style.backgroundColor = hex;
        btn.title = hex;
        hydra_add_event(btn, 'click', function(){func(this.title);});
        div.appendChild(btn);
    }

   elem.parentNode.appendChild(div);

   return div;
}

/**
 * Создает окно установки бордеров
 */
HydraEditorToolbar.prototype.set_borders = function(elem)
{
    var div = document.createElement('div');
    div.setAttribute('class', "borders-window");
    div.setAttribute('id', "borders-window");
    div.style.display = 'block';

    var borders = ['none','dotted', 'dashed', 'solid', 'double',
    'groove', 'ridge', 'inset', 'outset', 'inherit'];

    for (var i=0; i<borders.length; i++) {
        border = borders[i];
        var btn = document.createElement('button');
        
        btn.style.border = "3px "+border+" black";
        btn.innerHTML = border;
        btn.title = border;

        hydra_add_event(btn, 'click', function() {
            var obj = editor_toolbar.get_selected_object();
            if (!obj) {
                return false;
            }

            if (!obj.tagName) {
                var node = obj.parentNode;
                if (!node.tagName) {
                    return false;
                }
                if (node.getAttribute("contenteditable")=="true") {
                    return false;
                }
                obj = node;
                
                
            }
            if (!editor_toolbar.can_change_elem_here(obj)) {
                return false;
            }

            obj.style.border = "3px "+this.title+" black";
            hydra.hide_block('borders-window');
        });

        div.appendChild(btn);
    }


    elem.parentNode.appendChild(div);

   return div;
}

HydraEditorToolbar.prototype.fill_cells = function(x, y, color)
{
    //
    for(var i=1; i<=x; i++)
    for(var j=1; j<=y; j++) {
        var cell =document.getElementById('cell-'+i+'-'+j);
        if (cell)
        cell.style.backgroundColor = color;
    }
}

/**
 * Возвращает текущий Range объект
 * @return Object
 */
HydraEditorToolbar.prototype.get_current_range = function()
{
    var selection = this.get_selection();
    if (this.browser_type == 'gecko') {
        return selection.getRangeAt(0);
    }

    if (this.browser_type == 'ie') {
        return selection.createRange();
    }
}

/**
 * Проверяет можно ли менять этот элемент.
 * То есть по сути, лежит ли этот элемент внутри эелмента, который можно сейчас редактировать
 */
HydraEditorToolbar.prototype.can_change_elem_here = function(node)
{
    while( hydra.get_attribute(node, 'id') != "l-content") {

        if (hydra.get_attribute(node, 'contenteditable')=="true") {
            return true;
        }

        if (!node.parentNode) {
            return false;
        }
        
        node = node.parentNode;
        if (node.tagName == 'HTML') {
            return false;
        }
    }
    return false;
}

HydraEditorToolbar.prototype.can_insert_elem_here = function(selection)
{
    var node = selection.anchorNode;
    if (!node ) {
        return false;
    }
   
    return this.can_change_elem_here(node);
}

/**
 * Генерирует html код для таблицы
 **/
HydraEditorToolbar.prototype.insert_table = function(columns, rows)
{
    if (!this.can_insert_elem_here(this.get_selection())) {
        var win = hydra.get("create-table-window");
        win.style.display = 'none';
       return false;
   }

    var table = document.createElement('table');
    
    for (var r=1; r<= rows; r++) {
        var tr = document.createElement('tr');

        for (var c=1; c<= columns; c++) {

            var td = document.createElement('td');
            td.innerHTML = 'cell-'+c+'-'+r;
            tr.appendChild(td);
        }

        table.appendChild(tr);
    }

   
    

    //
    var range = this.get_current_range();
    //range.deleteContents();
    range.insertNode(table);

    var win = hydra.get("create-table-window");
    win.style.display = 'none';
}

HydraEditorToolbar.prototype.create_table = function(elem)
{
    var win = hydra.get("create-table-window");
    if (!win) {
        win = this.create_new_table_window(elem);
    }
    else {
        if (win.style.display == 'block') {
            win.style.display = 'none';
        }
        else {
            win.style.display = 'block';
        }
    }
}

/**
 * Показывает dropdown окно
 * @param String dropdown_id идентификатор dropdown-окна
 * @param Function creation_func функция создания элемента
 * @param Object elem элемент, для которого надо сделать dropdown
 */
HydraEditorToolbar.prototype.show_dropdown = function(dropdown_id, creation_func, elem, callback_after_show)
{
    this.last_selected_object = this.get_selected_object();

    // Проверяем, не создано ли такое окно
    var win = hydra.get(dropdown_id);
    if (!win) {
        // если не создано - создаем
        win = creation_func(elem);
        
        if (callback_after_show) {
            callback_after_show();
        }
    }
    else {
        if (win.style.display == 'block') {
            win.style.display = 'none';
        }
        else {
            win.style.display = 'block';
            
            if (callback_after_show) {
                callback_after_show();
            }
        }
    }
}

/**
 *  Создает окно создания таблицы
 *  @param Object elem кнопка, инициирующая вставку таблицы
 *  @return Object div окна
 */
HydraEditorToolbar.prototype.create_new_table_window = function(elem)
{
    var div = document.createElement('div');
    div.setAttribute('class', "create-table-window");
    div.setAttribute('id', "create-table-window");
    div.style.display = 'block';

    var column_count = 8;
    var y = 0;
    var x = 0;

    
    for (var i=1; i<49; i++) {

        if (i <= column_count) {
            y = 1;
        }
        else {
            y = Math.floor(i/column_count);
            if (y % column_count > 0) {
                y++;
            }
        }

        if (i % column_count == 0) {
            x = column_count;
        }
        else {
            x = i % column_count;
        }
        

        var li = document.createElement('button');
        li.setAttribute('id', 'cell-'+x+'-'+y);
        li.setAttribute('x', x);
        li.setAttribute('y', y);

        hydra_add_event(li, 'mouseover', function() {
                editor_toolbar.fill_cells(8, 8, 'white');
                editor_toolbar.fill_cells(this.getAttribute('x'), this.getAttribute('y'), 'green');
            }
        );

        hydra_add_event(li, 'click', function() {

                editor_toolbar.insert_table(this.getAttribute('x'), this.getAttribute('y'));
            }
        );

        div.appendChild(li);
    }
    

    elem.parentNode.appendChild(div);

    return div;
}

/**
 * Форматирование
 **/
HydraEditorToolbar.prototype.create_format_menu = function(elem)
{
    var formats = {
        h1:"Заголовок-1",
        h2:"Заголовок-2",
        h3: "Заголовок-3",
        h4: "Заголовок-4",
        h5: "Заголовок-5",
        p: "Параграф"
    };

    var ul = this.create_submenu("choose-format-menu", formats,
        function(a, key, value) {
            var h = document.createElement(key);
            h.innerHTML = value;
            a.appendChild(h);
            a.href = "javascript: editor_toolbar.format_block('"+key+"');";
        });
    elem.parentNode.appendChild(ul);
    return ul;
}

HydraEditorToolbar.prototype.format_block = function(value)
{
    this.exec_command('FormatBlock', value);

    var menu = hydra.get('choose-format-menu');
    if (menu) {
        this.hide_menu(menu);
    }
}


HydraEditorToolbar.prototype.show_menu = function(elem)
{
   elem.style.display = "block";
}

HydraEditorToolbar.prototype.hide_menu = function(elem)
{
   elem.style.display = "none";
}

HydraEditorToolbar.prototype.menu_is_visible = function(elem)
{
   if (elem.style.display == "block") {
       return true;
   }

   return false;
}

HydraEditorToolbar.prototype.exec_command = function(command, value)
{
    window.document.execCommand(command, false, value);
}

/**
 * Устанавливает заданный шрифт
 * @param string font_name имя шрифта
 */
HydraEditorToolbar.prototype.set_font = function(font_name)
{
    window.document.execCommand('FontName', false, font_name);
    var menu = hydra.get('choose-fonts-menu');
    if (menu) {
        this.hide_menu(menu);
    }
}

/**
 * Отображает меню установки шрифта
 * @param object elem - Элемент, для которого нужно отображать выбор шрифта
 * @param string submenu_id идентификатор submenu
 * @param string creator_func_name имя метода, что создает сабменю
 */
HydraEditorToolbar.prototype.show_submenu = function(elem, submenu_id, creator_func_name)
{
    // Проверяем не создали ли мы уже меню
    var menu = hydra.get(submenu_id); 
    if (!menu) {
        // Если меню еще не было создано - создаем его
        menu = this[creator_func_name](elem);  //create_font_menu
    }

    if (this.menu_is_visible(menu)) {
        this.hide_menu(menu);
    }
    else {
        this.show_menu(menu);
    }
}

HydraEditorToolbar.prototype.tidy_clean = function(content_container_id)
{
    var params = new Array();
    params['s_html'] = this.get_content(content_container_id);
    //params['s_html_src'] = this.get_textarea_html();
    call_ajax('hydra_tidy', content_container_id, params);
}

/**
 * Создает окно свойств элемента
 */
HydraEditorToolbar.prototype.create_properties_window = function(elem)
{
    var div = document.createElement('div');
    div.setAttribute('class', 'elem-properties-window');
    div.setAttribute('id', 'elem-properties-window');
    div.style.display = "block";

    
    var label = document.createElement('label');
    label.textContent = "ALT";
    div.appendChild(label);

    var br = document.createElement('br');
    div.appendChild(br);
    
    var input = document.createElement('input');
    input.setAttribute("type", "text");
    input.setAttribute("id", "elem-properties-alt");
    div.appendChild(input);

    var br = document.createElement('br');
    div.appendChild(br);

    hydra.add_label(div, "Внутринний отступ/Padding", {"class":"long"});
    hydra.add_input_elem(div, {"id":"elem-properties-padding", "class":"digit"});
    hydra.add_elem(div, 'label', false, "px");
    hydra.add_br(div);

    
    hydra.add_label(div, "Внешний отступ/Margin", {"class":"long"});
    hydra.add_input_elem(div, {"id":"elem-properties-margin", "class":"digit"});
    hydra.add_elem(div, 'label', false, "px");
    hydra.add_br(div);

    
    hydra.add_label(div, "Ширина/Width", {"class":"long"});
    hydra.add_input_elem(div, {"id":"elem-properties-width", "class":"digit"});
    hydra.add_elem(div, 'label', false, "px");
    hydra.add_br(div);

    hydra.add_label(div, "Высота/Height", {"class":"long"});
    hydra.add_input_elem(div, {"id":"elem-properties-height", "class":"digit"});
    hydra.add_elem(div, 'label', false, "px");
    hydra.add_br(div);


    var btn = document.createElement('button');
    btn.textContent = 'Применить';
    hydra_add_event(btn, 'click', function() {editor_toolbar.apply_elem_properties();});
    div.appendChild(btn);

    elem.parentNode.appendChild(div);
}

/**
 * Создает окно выбора размера шрифта
 */
HydraEditorToolbar.prototype.create_fontsize_window = function(elem)
{
    var div = document.createElement('div');
    div.setAttribute('class', 'elem-fontsize-window');
    div.setAttribute('id', 'elem-fontsize-window');
    div.style.display = "block";

    for(var i=6; i<=20; i++) {
        var btn = document.createElement('button');
        btn.textContent = "Размер "+i;
        btn.setAttribute("fsize", i);
        btn.style.fontSize = i+"px";
        hydra_add_event(btn, "click", function() {editor_toolbar.set_fontsize(this);});
        div.appendChild(btn);
    }

    elem.parentNode.appendChild(div);
}

HydraEditorToolbar.prototype.set_fontsize = function(elem)
{
    //this.exec_command("FontSize", elem.getAttribute("fsize")+ "px");
    
    

    var range = this.get_current_range();
    if (range) {
        // Правильное обрамление текста!!!!!!!!!!!!!!!!!!!!!!!!!!!
        var span=document.createElement("span");
        span.appendChild(document.createTextNode(range));
        span.style.fontSize = elem.getAttribute("fsize") + "px";
        range.deleteContents();
        range.insertNode(span);

        hydra.hide_block("elem-fontsize-window");
        return true;
        ////////////////////////////////

        var span = document.createElement("span");
        span.style.fontSize = elem.getAttribute("fsize") + "px";
        range.surroundContents(span);
        return true;
    }
    ///////////////////////////////////////////////////////

    var obj = this.get_selected_object();
    // Если у нас выделен текст
    if (obj.nodeType == 3) {
        // Проверяем, а вдруг этот текст лежит в спане
        if (obj.tagName == "span") {
            obj.style.fontSize = elem.getAttribute("fsize") + "px";
            return true;
        }

        this.wrap_selection_by_tag("span", false, {"fontSize":elem.getAttribute("fsize") + "px"});
        return true;
    }

    obj.style.fontSize = elem.getAttribute("fsize") + "px";
    
    hydra.hide_block("elem-fontsize-window");
    //alert(obj);
}

HydraEditorToolbar.prototype.fill_elem_properties = function()
{
    if (!editor_toolbar.last_selected_object) {
        return false;
    }

    hydra.get("elem-properties-alt").value = editor_toolbar.last_selected_object.getAttribute("alt");
    hydra.get("elem-properties-padding").value = editor_toolbar.last_selected_object.getAttribute("padding");
    hydra.get("elem-properties-margin").value = editor_toolbar.last_selected_object.getAttribute("margin");
    hydra.get("elem-properties-width").value = editor_toolbar.last_selected_object.getAttribute("width");
    hydra.get("elem-properties-height").value = editor_toolbar.last_selected_object.getAttribute("height");
}


HydraEditorToolbar.prototype.apply_elem_properties = function()
{
    hydra.hide_block('elem-properties-window');
    
    var obj = this.last_selected_object;
    if (obj) {
        var alt = hydra.get("elem-properties-alt").value;
        if (alt != "") {
            obj.setAttribute("alt", alt);
        }

        var padding = hydra.get("elem-properties-padding").value;
        if (padding != "") {
            obj.setAttribute("padding", padding);
        }

        var margin = hydra.get("elem-properties-margin").value;
        if (margin != "") {
            obj.setAttribute("margin", margin);
        }

        var width = hydra.get("elem-properties-width").value;
        if (width != "") {
            obj.setAttribute("width", margin);
        }

        var height = hydra.get("elem-properties-height").value;
        if (height != "") {
            obj.setAttribute("height", height);
        }
    }
}

/**
 * Создает текстовую область для заданного контейнера
 */
function create_textarea_for(container_id)
{

    var editor_div = hydra.get(container_id);
    if (!editor_div) {
        alert("Немогу найти элемент с контентом");
        return false;
    }

    // Создаем текстовую область
    var textarea = document.createElement("textarea");
    textarea.setAttribute("id", container_id+"-html");
    textarea.style.width = editor_div.clientWidth+"px";

    var height = editor_div.clientHeight;
    if (height < 20) {
        height = 250;
    }
    textarea.style.height = height+"px";
    textarea.innerHTML = editor_div.innerHTML;
    textarea.style.display  = "none";

    editor_div.parentNode.insertBefore( textarea, editor_div );

    return textarea;
}


 function RGBtoHex(R,G,B) {return toHex(R)+toHex(G)+toHex(B)}
 function toHex(N) {
        if (N==null) return "00";
        N=parseInt(N);
        if (N==0 || isNaN(N)) return "00";
       N=Math.max(0,N);
        N=Math.min(N,255);
        N=Math.round(N);
       return "0123456789ABCDEF".charAt((N-N%16)/16)
      + "0123456789ABCDEF".charAt(N%16);
 }



editor_toolbar = new HydraEditorToolbar();

/*
hydra_add_event(window, "mouseup", function() {
        debugger;
        var obj = editor_toolbar.get_selected_object();
        var a = 1;
    });*/