CCIDS = 10000;

function Menu() {
    this.init();

    this.cfg = { 
        hasSizeBtn: false,
        hasRefreshBtn: false,
        hasSettingsBtn: false,
        hasDrag: false,
        isOpenHidden: true,
        isSystem: true,
        title: loc.text("menu_title"),
        module: "Menu",
        uniqueId: SYS_WIDGETS_ID + 3
    }



    this.defaultProfile["catalog"] = [];

    this.widget = null;

    this.catalog = [];

    this.catalog[CCIDS] = {categories: [{id: CCIDS+1, name: loc.text("menu_cutom_channels")}], items: []};
    this.catalog[CCIDS+1] = {categories: [], items: []};


    this.domModelContent = [
        { tag: "div", className: "menu_panel", id: "addFeedMenuItem",
          childs: [createButtonDom(loc.text("menu_add_feed"), "showAddFeedPanel()", "widgets/menu/img/plus.gif")] },
        { tag: "div", className: "menu_hr"},

        { tag: "div", className: "menu_panel", id: "cat_content"+CCIDS, display: false },

        { tag: "div", className: "menu_hr"},

        { tag: "div", className: "menu_panel", id: "cat_content0", display: false },

        { tag: "div", className: "menu_hr"}
    ]


    this.domModelAdditional = [
      { tag: "div", className: "panel", id: "preview", display: false, style: {position: "absolute", left: "0px", top: "0px", width: "300px"},
        childs: [
          { tag: "div", className: "panel_section",
            childs: [createTableDom([{content: createButtonDom("<b>" + loc.text("menu_add2desktop") + "</b>", "addToDesktop()", "widgets/menu/img/plus.gif"), width: "99%"},
                                     {content: {tag: "a", href: "void", events: {onclick: "closePreview()"}, innerHTML: "<img src='static/client/close.gif'>"}, width: "1%"}
                                    ]),
                     { tag: "div", id: "preview_panel", style: {width: "100%", height: "auto", padding: "0", margin: "0"} }
                    ]
          }
        ]
      },
      { tag: "div", className: "panel", id: "addFeedPanel", display: false, style: {position: "absolute", left: "0px", top: "0px", width: "340px"},
        childs: [
          { tag: "div", className: "caption",              
            childs: [ createTableDom([{content: "<img src='widgets/menu/img/item.gif' style='vertical-align: middle'> &nbsp;<b>" + loc.text("menu_add_feed") + "</b>", width: "99%"},
                                      {content: createButtonDom(false, "closeAddFeedPanel()", "static/client/close.gif"), width: "1%"}
                                     ]),
            
                      createTableDom([{content: { tag: "div", innerHTML: loc.text("menu_inp_url"), style: {paddingTop: "15px", paddingBottom: "15px"}}, width: "1%"},
                                      {content: { tag: "input", type: "text", size: "40", id: "selectFeedUrl"}, width: "100%"},
                                      {content: { tag: "input", type: "button", id: "addFeedButton", events: {onclick: "addFeed()"}, value: loc.text("btn_add")}, width: "1%"}
                                     ]),
                      { tag: "div", display: false, id: "addFeedStatus", className: "menu_panel", style: {paddingBottom: "15px"}, align: "center"}
            ]
          }
        ]
      },
      { tag: "div", className: "panel", id: "item_menu", display: false, style: {padding: "6px", position: "absolute", left: "0px", top: "0px", verticalAlign: "middle"},
        childs: [
            { tag: "span", id: "item_menu_actions",
              childs: [
                createButtonDom("<b>"+loc.text("menu_rename")+"</b>", "showRenameItemSection()", "static/client/edit.gif"),
                { tag: "br"},
                createButtonDom("<b>"+loc.text("menu_delete")+"</b>", "showDeleteItemSection()", "static/client/delete_link.gif")
              ]},
            { tag: "span", id: "item_menu_rename",
              display: false,
              innerHTML: "<b>" +loc.text("menu_rename_to")+"</b> &nbsp;",
              childs: [
                { tag: "input", type: "text", id: "new_item_title", style: {width: "190px"}},
                { tag: "input", type: "button", value: loc.text("btn_ok"), events: {onclick: "renameItem()"}},
                { tag: "input", type: "button", value: loc.text("btn_cancel"), events: {onclick: "hideItemMenu()"} }
              ]},
            { tag: "span", id: "item_menu_delete",
              display: false,
              innerHTML: "<b>"+loc.text("menu_delete_prompt")+"</b> &nbsp;",
              childs: [
                { tag: "input", type: "button", value: loc.text("btn_yes"), events: {onclick: "deleteItem()"} },
                { tag: "input", type: "button", value: loc.text("btn_no"), events: {onclick: "hideItemMenu()"} }
              ]}
        ]
      }
    ]


    this.menuItemId = 0;

    this.getMenuItemId = function(id) {
        var res = "menu_item_";
        if(id) {
            res = res + id;
        } else {
            this.menuItemId ++;
            res = res + this.menuItemId;
        }
        return res;
    }


    this.folder_o = new Image();
    this.folder_o.src = "static/client/folder-o.gif";
    this.folder_s = new Image();
    this.folder_s.src = "static/client/folder-s.gif";

    this.onBuildInterface = function() {
        this.elements.window.style.position = "absolute";
        this.elements.window.style.margin = "2px";
        this.elements.window.style.top = "0px";
        this.elements.window.style.left = "0px";
        this.elements.window.style.width = "235px";
        this.buildDomModel(this.elements.content, this.domModelContent);
        this.buildDomModel(document.body, this.domModelAdditional);

        this.setTitle(this.cfg.title);
        for(w in menuWidgets) {
            if(menuWidgets[w] == "-") {
                this.buildDomModel(this.elements["content"], { tag: "div", className: "menu_hr"});
            } else {
                var mid = this.getMenuItemId();
                var wname = menuWidgets[w].className.toLowerCase();

                this.buildDomModel(document.body, 
                    { tag: "div", className: "hint", id: "hint_"+wname, display: false, 
                      style: {position: "absolute", left: "0px", top: "0px", width: "280px", padding: "8px"},
                      innerHTML: loc.text(wname + "_hint").replace(/\n/g, "<br>") } );

                var m = { tag: "div", className: "menu_panel",
                          events: {
                            onmouseover: "showHint('" + wname + "', '"+mid+"')",
                            onmouseout: "hideHint('" + wname + "')"},
                          childs: [
                            createButtonDom(loc.text(wname + "_title"), "openWidget('" + menuWidgets[w].className + "', '"+mid+"')", "widgets/" + wname + "/ico.gif", mid)
                          ]
                        }
                this.buildDomModel(this.elements["content"], m);
            }
        }

        // HTML Widgets
        this.buildDomModel(this.elements["content"], [
            { tag: "div", className: "menu_hr"},
            { tag: "div", id: "html_widgets",
              html: loc.text("msg_loading") }
        ]);
        request.send({ act: "get_html_widgets" }, this);


        // Load feeds catalog
        this.switchCategory(0);

        // Custom feeds
        var tmp = [];
        for(var i=0; i<this.profile.catalog.length; i++) {
            if(this.profile.catalog[i] != -1) {
                tmp.push(this.profile.catalog[i]);
            }
        }
        this.profile.catalog = null;
        this.profile.catalog = tmp;


        for(var i in this.profile.catalog) {
            this.catalog[CCIDS+1].items[i] = clone(this.profile.catalog[i]);
            this.catalog[CCIDS+1].items[i].id = CCIDS + 2 + parseInt(i);
        }

        this.renderCategory(CCIDS);
    }



    // open/close sub menus
    this.switchPanel = function(name) {
        with (this.elements[name].style) {
            display = (display == 'none' ? 'block' : 'none');
        }
    }


    this.show = function() {
        if(!desktop.isMenuShow) {
            showEl(this.elements.window);
            desktop.elements.pager.style.marginLeft = this.elements.window.offsetWidth + 2 + "px";
            desktop.elements.pager.style.width = "auto";
            desktop.isMenuShow = true;
        }
    }


    this.hide = function() {
        if(desktop.isMenuShow) {
            hideEl(this.elements.window);
            desktop.elements.pager.style.marginLeft = 0;
            desktop.isMenuShow = false;
        }
    }

    this.close = function() {
//        hideEl(desktop.elements.menu);
        this.hideItemMenu();
        this.closePreview();
        this.closeAddFeedPanel();
        this.hide();
    }



//---------------------------------------------
// PREVIEW
//---------------------------------------------
//dimk
    this.openWidget = function(widgetClass, mid, params) {
        this.hideItemMenu();
        this.hideHint();
        desktop.showPage("panels");
        this.closePreview();
        showEl(this.elements.preview);

        var pos = {left: getLeft(this.elements.window) + this.elements.window.offsetWidth + 12, 
                   top:  getTop(this.elements[mid])};
        setElPos(this.elements.preview, pos);
        this.widget = kernel.runWidget(widgetClass, this.elements["preview_panel"], false, params, { isPreview: true});
        this.oldDisableOnClosePrompt = this.widget.disableOnClosePrompt;
        this.widget.disableOnClosePrompt = true;

        pos.top = pos.top - Math.round(this.elements.preview.offsetHeight / 2);
        setElPos(this.elements.preview, pos);
    }

    this.closePreview = function() {
        if(this.widget) {
            this.widget.close();
        }
        this.widget = null;
        hideEl(this.elements.preview);
        this.elements.preview_panel.innerHTML = '';
    }


    this.addToDesktop = function() {
        if(this.widget) {
            this.widget.setParent(desktop.getTinyPanel());
            this.widget.save();
            this.widget.isPreview = false;
            this.widget.initDtagAndDrop();
            this.widget.disableOnClosePrompt = this.oldDisableOnClosePrompt;
            this.widget = null;
            this.closePreview();
            desktop.savePanels();
        }
    }


//---------------------------------------------
// HINTS
//---------------------------------------------
    this.currentHint = null;
    this.showHint = function(wname, mid) {
        if(!this.widget) {
            var pos = {left: getLeft(this.elements.window) + this.elements.window.offsetWidth + 12, 
                       top:  getTop(this.elements[mid])};
            setElPos(this.elements["hint_"+wname], pos);
            showEl(this.elements["hint_"+wname]);
            this.currentHint = wname;
            this.hideItemMenu();
        }
    }


    this.hideHint = function(wname) {
        if(wname) {
            hideEl(this.elements["hint_"+wname]);
        } else if (this.currentHint) {
            hideEl(this.elements["hint_"+this.currentHint]);
        }
    }


//---------------------------------------------
// ADD CHANNELS
//---------------------------------------------
    this.setAddFeedStatus = function(html) {
        if(html) {
            showEl(this.elements.addFeedStatus);
            this.elements.addFeedStatus.innerHTML = html;
        } else {
            clearEl(this.elements.addFeedStatus);
            hideEl(this.elements.addFeedStatus);
        }
    }

    this.addFeedPanelVisible = false;

    this.showAddFeedPanel = function() {
        this.hideItemMenu();
        if(!this.addFeedPanelVisible) {
            desktop.showPage("panels");
            this.setAddFeedStatus(null);
            showEl(this.elements.addFeedPanel);
            showEl(this.elements.addFeedButton);
            var pos = {left: getLeft(this.elements.window) + this.elements.window.offsetWidth + 12, 
                       top:  getTop(this.elements.addFeedMenuItem)};

            setElPos(this.elements.addFeedPanel, pos);
            this.elements.selectFeedUrl.focus();
            this.addFeedPanelVisible = true;
        }
    }


    this.closeAddFeedPanel = function() {
        if(this.addFeedPanelVisible) {
            hideEl(this.elements.addFeedPanel);
            this.addFeedPanelVisible = false;
        }
    }


    this.addFeed = function() {
        var url = trim(this.elements.selectFeedUrl.value);
        if(url!="") {
            hideEl(this.elements.addFeedButton);
            this.setAddFeedStatus("<b>"+loc.text("menu_msg_cc")+"</b>");
            if(url.indexOf("http://") == -1) {
                url = "http://"+url;
            }
            this.newFeedUrl = url;
            xmlRequest.send(url, this, "addFeedDispatch");
        }
    }


    this.registerFeed = function(title, url) {
        var cn = this.catalog[CCIDS+1].items.length;
        this.profile.catalog[cn] = {title: title, url: url};
        var newItem = {id: CCIDS+cn+2, title: title.substr(0,25), url: url, icon: ''};
        this.catalog[CCIDS+1].items[cn] = newItem;

        this.renderCategory(CCIDS+1, true);

        this.save();
    }

    this.addFeedDispatch = function(response) {
        if(response.responseXML.documentElement) {
            var channel = XMLParser.xml2hash(response.responseXML.documentElement);
            if(channel) {
                this.setAddFeedStatus("<b>"+loc.text("menu_msg_added", channel.title)+"</b>");
                this.elements.selectFeedUrl.value = '';
//        this.profile.catalog[cn] = {title: channel.title, url: this.newFeedUrl};
                this.registerFeed(channel.title, this.newFeedUrl);

                showEl(this.elements.addFeedButton);

                var w = kernel.runWidget("Rss", desktop.getTinyPanel(), false, {url: this.newFeedUrl});
                w.save();
                desktop.savePanels();
                this.closeAddFeedPanel();
                return;
            }
        }
        this.setAddFeedStatus("<b>"+loc.text("menu_msg_no_responce")+ "</b>");
        showEl(this.elements.addFeedButton);
    }



//---------------------------------------------
// ITEM MENU
//---------------------------------------------
    this.activeItemId = null;
    this.showItemControl = function(id) {
        this.hideItemControl();
        showEl(this.elements["item_control"+id]);
        this.activeItemId = id;
    }

    this.hideItemControl = function() {
        if(this.activeItemId != null) {
            hideEl(this.elements["item_control"+this.activeItemId]);
        }    
    }

    this.showItemMenu = function(mid) {
        if(!this.widget && !this.addFeedPanelVisible) {
            hideEl(this.elements.item_menu_rename);
            hideEl(this.elements.item_menu_delete);
            showEl(this.elements.item_menu_actions);
            showEl(this.elements.item_menu);

            var pos = {left: getLeft(this.elements.window) + this.elements.window.offsetWidth + 2, 
                       top:  getTop(this.elements[mid]) - 10};
            setElPos(this.elements.item_menu, pos);        
        }
    }

    this.hideItemMenu = function() {
        hideEl(this.elements.item_menu);
    }

    this.showRenameItemSection = function() {
        var n = this.getItemNum(this.activeItemId);
        this.elements.new_item_title.value = this.profile.catalog[n].title;

        hideEl(this.elements.item_menu_actions);
        showEl(this.elements.item_menu_rename);
    }

    this.showDeleteItemSection = function() {
        hideEl(this.elements.item_menu_actions);
        showEl(this.elements.item_menu_delete);
    }

    this.getItemNum = function(itemId) {
        for(var i=0; i<this.catalog[CCIDS+1].items.length; i++) {
            if(this.catalog[CCIDS+1].items[i] != -1 && this.catalog[CCIDS+1].items[i].id == itemId) {
                return i;
            }
        }
    }

    this.renameItem = function() {
        var title = trim(this.elements.new_item_title.value);
        if(title != "") {
            var n = this.getItemNum(this.activeItemId);
            this.profile.catalog[n].title = title;
            this.catalog[CCIDS+1].items[n].title = title;
            this.elements["cat_item_title"+this.activeItemId].innerHTML = title;
            this.save();
            this.hideItemMenu();
        }
    }

    this.deleteItem = function() {
        var n = this.getItemNum(this.activeItemId);
        this.profile.catalog[n] = -1;
        this.catalog[CCIDS+1].items[n] = -1;
        this.elements["cat_item"+this.activeItemId].parentNode.removeChild(this.elements["cat_item"+this.activeItemId]);
        this.elements["cat_item"+this.activeItemId] = null;
        this.save();
        this.hideItemMenu();
    }






//---------------------------------------------
// CATALOGS
//---------------------------------------------
    this.switchCategory = function(catId) {
        this.hideItemMenu();
        var el = this.elements["cat_content"+catId];
        if(el.style.display == 'none') {
            if(this.catalog[catId]) {
                if(this.catalog[catId].rendered) {
                    showEl(el);
                } else {
                    this.renderCategory(catId);
                }
            } else {
                if(catId < CCIDS) {
                    el.innerHTML = loc.text("msg_loading");
                    showEl(el);
                    request.send({act: "get_category", cat_id: catId}, this);
                }
            }
            if(catId != "0") {
                this.elements["fico_" + catId].setAttribute("src", this.folder_o.src);
            }
        } else {
            if(catId != "0") {
                this.elements["fico_" + catId].setAttribute("src", this.folder_s.src);
            }
            hideEl(el);
        }
    }


    this.tmpIcons = {};
    this.renderCategory = function(catId, silent) {
        el = this.elements["cat_content"+catId];
        el.innerHTML = '';

        with(this.catalog[catId]) {
            if(categories) {
                for(var i in categories) {
                    this.buildDomModel(el, 
                      { tag: "div", className: "menu_panel", id: "cat"+categories[i].id, 
                        childs: [
                          createButtonDom(categories[i].name, 
                                          "switchCategory("+categories[i].id+")", 
                                          this.folder_s.src,
                                          false,
                                          "fico_" + categories[i].id
                                          ),
                          { tag: "div", id: "cat_content"+categories[i].id, className: "menu_sub_panel", display: false }
                        ]
                      });
                }
            }

            if(items) {
                var m = null;
                for(var i in items) {
                    if(items[i] == -1) {
                        continue;
                    }
                    var ico_id = "item_icon_"+items[i].id;

                    m = { tag: "div", id: "cat_item"+items[i].id, 
                          style: {width: "100%", padding: "0px"},
                          childs: []}

                    var cells = [
                        {content: createButtonDom(items[i].title, 
                                                  "openWidget('Rss', 'cat_item"+items[i].id+"', {url: '"+items[i].url + "'" + (items[i].icon ? ", icon: '"+items[i].icon+"'" : "") + "})", 
                                                  "widgets/menu/img/item.gif", 
                                                  "cat_item_title"+items[i].id,
                                                  ico_id),
                                  width: "99%"}];


                    if(items[i].id > CCIDS) {
                        m.events = {onmouseover: "showItemControl('"+items[i].id+"')", onmouseout: "hideItemControl()"};
                        cells.push({content: 
                                      { tag: "img", src: "static/client/right_arrow.gif",
                                        id: "item_control"+items[i].id,
                                        style: {verticalAlign: "middle", cursor: "pointer"},
                                        display: false,
                                        events: {onmouseover: "showItemMenu('cat_item"+items[i].id+"')"}
                                      },
                                      width: "99%"});
                    }

                    m.childs.push(createTableDom(cells));

                    this.buildDomModel(el, m);


                    var icons = [
                        items[i].icon,
                        getDomain(items[i].url) + "/favicon.ico",
                        getDir(items[i].url) + "/favicon.ico"
                    ];

                    with(this.elements[ico_id].style) {
                        width = "16px";
                        heigth = "16px";
                    }

                    loadIcon(this.elements[ico_id], icons);
                }
            }  


            if(!items  &&  !categories) {
                el.innerHTML = loc.text("msg_empty");
            }

            rendered = true;
        }

        if(!silent) {
            el.style.display = 'block';
        }
        this.catalog[catId].rendered = true;
    }




//---------------------------------------------
// HTML WIDGETS
//---------------------------------------------
    this.renderHTMLWidgetsList = function(data) {
        if(data) {
            this.elements["html_widgets"].innerHTML = "";
            for(var i in data) {
                var mid = this.getMenuItemId();
                var m = { tag: "div", className: "menu_panel",
                          childs: [
                            createButtonDom(data[i].title, 
                                            "openHTMLWidget('" + data[i].id + "', '"+mid+"')", "var/hwicons/" + data[i].icon, mid)
                          ]}

                this.buildDomModel(this.elements["html_widgets"], m);
            }
        }
    }


    this.openHTMLWidget = function(hwId, mid) {
//    this.openWidget = function(widgetClass, mid, params) {
        this.openWidget("HTMLWidget", mid, { id: hwId });
    }



//---------------------------------------------
// DISPATCHER
//---------------------------------------------
    this.dispatchMsg = function(msg) {
        switch (msg.status) {
            case "category_data":
                this.catalog[msg.cat_id] = { categories: msg.categories, items: msg.items};
                this.renderCategory(msg.cat_id);
                break;


            case "html_widgets":
                this.renderHTMLWidgetsList(msg.data);
                break;
        }
    }

}
Menu.prototype = new Widget();