CCIDS = 10000;

function Menu() {
    this.init();

    this.cfg = { hasSizeBtn: false,
                 hasRefreshBtn: false,
                 hasSettingsBtn: false,
                 hasDrag: false,
                 isOpenHidden: true,
                 isSystem: true,
                 title: "Add stuff",
                 module: "Menu"
    }



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

    this.widget = null;

    this.catalog = [];

    this.catalog[CCIDS] = {categories: [{id: CCIDS+1, name: "Custom channels"}], items: []};
    this.catalog[CCIDS+1] = {categories: [], items: []};


    this.domModelContent = [
        { tag: "div", className: "menu_panel", id: "addFeedMenuItem",
          childs: [createButtonDom("Add Custom Feed", "showAddFeedPanel()", "widgets/menu/img/plus.gif")] },
        { tag: "hr", width: "100%"},

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

        { tag: "hr", width: "100%"},

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

        { tag: "hr", width: "100%"},

        { tag: "div", className: "menu_panel", id: "panel_widgets"},
    ]


    this.domModelAdditional = [
      { tag: "div", className: "panel", id: "preview", display: false, style: {position: "absolute", left: "0px", top: "0px", width: "280px"},
        childs: [
          { tag: "div", className: "caption",
            childs: [createTableDom([{content: createButtonDom("<b>Add To Desktop</b>", "addToDesktop()", "widgets/menu/img/plus.gif"), width: "100%"},
                                     {content: {tag: "a", href: "void", events: {onclick: "closePreview()"}, innerHTML: "<img src='"+theme.icons.close+"'>"}, width: "1%"}
                                    ]),
                     { tag: "div", id: "preview_panel", style: {height: "auto"} }
                    ]
          }
        ]
      },
      { tag: "div", className: "panel", id: "addFeedPanel", display: false, style: {position: "absolute", left: "0px", top: "0px", width: "320px"},
        childs: [
          { tag: "div", className: "caption",              
            childs: [ createTableDom([{content: "<img src='widgets/menu/img/item.gif' style='vertical-align: middle'> &nbsp;<b>Add custom feed</b>", width: "99%"},
                                      {content: createButtonDom(false, "closeAddFeedPanel()", theme.icons.close), width: "1%"}
                                     ]),
            
                      createTableDom([{content: { tag: "div", innerHTML: "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: " 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>Rename</b>", "showRenameItemSection()", theme.icons.edit),
                { tag: "br"},
                createButtonDom("<b>Delete</b>", "showDeleteItemSection()", theme.icons.delete_link)
              ]},
            { tag: "span", id: "item_menu_rename",
              display: false,
              innerHTML: "<b>Rename to:</b> &nbsp;",
              childs: [
                { tag: "input", type: "text", id: "new_item_title", style: {width: "190px"}},
                { tag: "input", type: "button", value: " Ok ", events: {onclick: "renameItem()"}},
                { tag: "input", type: "button", value: " Cancel ", events: {onclick: "hideItemMenu()"} }
              ]},
            { tag: "span", id: "item_menu_delete",
              display: false,
              innerHTML: "<b>Are you sure you want to delete this?</b> &nbsp;",
              childs: [
                { tag: "input", type: "button", value: " Yes ", events: {onclick: "deleteItem()"} },
                { tag: "input", type: "button", value: " No ", events: {onclick: "hideItemMenu()"} }
              ]}
        ]
      }
    ]


    this.getSignature = function() {
        return SYSWIDGET_WKEY+3;
    }

    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.onBuildInterface = function() {
// preload icons
	kernel.imgCache.menu = {};
	kernel.imgCache.menu.folder = new Image();
	kernel.imgCache.menu.folder.src = "widgets/menu/img/folder.gif";
	kernel.imgCache.menu.plus = new Image();
	kernel.imgCache.menu.plus.src = "widgets/menu/img/plus.gif";
	kernel.imgCache.menu.item = new Image();
	kernel.imgCache.menu.item.src = "widgets/menu/img/item.gif";


        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 = "220px";
	this.elements.window.className += " menu_links_fix";
	this.elements.settings.removeChild(this.elements.settings.lastChild);
        this.buildDomModel(this.elements.content, this.domModelContent);
        this.buildDomModel(document.body, this.domModelAdditional);
	this.elements.window.style.borderWidth="2px";
        this.setTitle(this.cfg.title);

        for(h in menuHints) {
            this.buildDomModel(document.body, 
                { tag: "div", className: "hint", id: "hint_"+h, display: false, 
                  style: {position: "absolute", left: "0px", top: "0px", width: "280px", padding: "8px"},
                  innerHTML: unescape(menuHints[h]) } );
        }

        for(w in menuWidgets) {
            var mid = this.getMenuItemId();
            var wname = menuWidgets[w].className.toLowerCase();
            var m = { tag: "div", className: "menu_panel",
                      childs: [
                        createButtonDom(menuWidgets[w].title, "openWidget('" + menuWidgets[w].className + "', '"+mid+"')", "widgets/" + wname + "/ico.gif", mid)
                      ]
                    }
            if(menuHints[wname]) {
                m.events = {
                    onmouseover: "showHint('" + wname + "', '"+mid+"')",
                    onmouseout: "hideHint('" + wname + "')"
                }
            }
            this.buildDomModel(this.elements.panel_widgets, m);
        }
        this.switchCategory(0);

        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(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() {
        showEl(this.elements.window);
        desktop.elements.pager.style.paddingLeft = this.elements.window.offsetWidth + 4 + "px";
        desktop.elements.pager.style.width = "100%";
        desktop.isMenuShow = true;
    }


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

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



//---------------------------------------------
// PREVIEW
//---------------------------------------------
    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);
    }

    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 = 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>Checking channel...</b>");
            if(url.indexOf("http://") == -1) {
                url = "http://"+url;
            }
            this.newFeedUrl = url;
            xmlRequest.send(url, this, "addFeedDispatch");
        }
    }


    this.addFeedDispatch = function(response) {
        if(response.responseXML.documentElement) {
            var channel = XMLParser.xml2hash(response.responseXML.documentElement);
            if(channel) {
                this.setAddFeedStatus("<b>Channel "+channel.title+" added.</b>");
                this.elements.selectFeedUrl.value = '';

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

                this.renderCategory(CCIDS+1, true);

                this.save();
                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>Channel does not response.</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();
    }

    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;
        }
    }




//---------------------------------------------
// 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 = 'Loading...';
                    showEl(el);
                    request.send({act: "get_category", cat_id: catId}, this);
                }
            }
        } else {
            hideEl(el);
        }
    }


    this.tmpIcons = {};
    this.renderCategory = function(catId, silent) {
        el = this.elements["cat_content"+catId];
        el.innerHTML = '';
        with(this.catalog[catId]) {
            if(categories) {
                for(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+")", "widgets/menu/img/folder.gif"),
                          { tag: "div", id: "cat_content"+categories[i].id, className: "menu_sub_panel", display: false }
                        ]
                      });
                }
            }
	    
            if(items) {
                var m = null;
                for(i in items) {
                    if(items[i] == -1) {
                        continue;
                    }
                    var ico_id = "cat_item_img"+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", */
						  "http://"+getDomain(items[i].url) + "/favicon.ico",
                                                  "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: theme.icons.right_arrow,
                                        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 = [
                    "http://"+getDomain(items[i].url) + "/favicon.ico",
                    getDir(items[i].url) + "/favicon.ico",
		    "http://www.loonstart.com/img/rss.gif"
                ];
		 loadIcon(menu.elements[ico_id], icons);


/*                    var a = new Image();
                    if(items[i].icon && items[i].icon != undefined) {
                        a.imgId = ico_id;
			a.src=items[i].icon;
                        a.onload = function() {
                            menu.elements[this.imgId].src = this.src;
                        }
                        a.src = items[i].icon;
                    } else {
                        a.imgId = ico_id;

                        a.src = "http://"+getDomain(items[i].url) + "/favicon.ico";
                        a.onload = function() {
                            menu.elements[this.imgId].src = this.src;
                        }
                        a.onerror = function() {
                            if(this.url2 != null) {
                                this.src = this.url2;
                                this.url2 = null;
                            } else {
                                this.onerror = null;
                            }
                        }
                        a.src = getDir(items[i].url) + "/favicon.ico";
                    }*/

                }
            }  

            if(!items  &&  !categories) {
                el.innerHTML = "Empty...";
            }

            rendered = true;
        }

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


}
Menu.prototype = new Widget();
