function Messenger() {
    this.init();


    this.cfg = {
        hasSettingsBtn: false,
        title: "Messenger",
        module: "Messenger"
    }


    this.domContent = [
        { tag: "div", className: "bevel_section", innerHTML: "Contact list",
          style: {cursor: "pointer"},
          events: {onclick: "switchSection('section_contact_list')"}
        },
        { tag: "div", className: "menu_panel", id: "section_contact_list", display: false,
          childs: [
            { tag: "div", className: "menu_panel", id: "contact_list"},
            { tag: "hr", width: "100%"},
            { tag: "div", className: "menu_panel", 
              childs: [
                createTableDom([{content: "Add&nbsp;contact:", width: "1%"},
                                {content: { tag: "input", type: "text", style: {width: "100%"}, id: "edit_user_id"}, width: "100%"},
                                {content: { tag: "input", type: "button", value: " Add ", events: {onclick: "addContact()"}}, width: "1%"}
                               ])
              ]
            }
          ]
        },


        { tag: "div", className: "bevel_section", innerHTML: "Compose message",
          style: {cursor: "pointer"},
          events: {onclick: "switchSection('section_compose')"}
        },
        { tag: "div", className: "menu_panel", id: "section_compose", display: false,
          childs: [
            { tag: "div", className: "menu_panel", innerHTML: "Recipient:",
              childs: [
                { tag: "input", type: "text", size: "30", id: "edit_recipient"}
              ]
            },
            { tag: "div", className: "menu_panel", innerHTML: "Text:<br>",
              childs: [
                { tag: "textarea", style: {width: "95%", height: "80"}, id: "edit_body"}
              ]
            },
            { tag: "input", type: "button", value: " Send ", id: "send_btn", events: {onclick: "sendMessage()"}},
            { tag: "div", id: "send_status"}
          ]
        },

        { tag: "div", className: "bevel_section", innerHTML: "Inbox",
          style: {cursor: "pointer"},
          events: {onclick: "switchSection('section_new_messages')"}
        },
        { tag: "div", className: "menu_panel", id: "section_new_messages", display: false,
          childs: [
            { tag: "div", id: "new_messages", className:"listBox", style: {width: "auto", height: "300px"}, innerHTML: "Loading..." },
            { tag: "div", id: "clear_new_messages", display: false, align: "right",
              childs: [
                createButtonDom("Clear inbox", "clearMessages()", "widgets/messenger/img/clear.gif")
              ]
            }
          ]
        },

        { tag: "div", id: "tmp", display: false}
    ]


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

    this.messages = [];
    this.isUpdating = false;

    this.switchSection = function(sid) {
        if(this.elements[sid].style.display == 'none') {
            showEl(this.elements[sid]);
        } else {
            hideEl(this.elements[sid]);
        }
    }




    this.onBuildInterface = function() {
        this.buildDomModel(this.elements.content, this.domContent);
        this.renderContactList();
        this.setTitle(this.cfg.title);
    }


    this.onOpen = function() {
        kernel.processTimer(this.id, 30000);
    }


    this.timerHandler = function() {
        this.refresh();
    }



    this.addContact = function() {
        var id = trim(this.elements.edit_user_id.value);
        if(id != "") {
            this.profile.contact_list[arrayFirstFree(this.profile.contact_list)] = id;
            this.save();
            this.renderContactList();
            this.elements.edit_user_id.value = '';
        }
    }

    this.deleteContact = function(num) {
        if(confirm("Delete contact \"" + this.profile.contact_list[num] + "\" ?")) {
            this.profile.contact_list[num] = undefined;
            this.renderContactList();
            this.save();
        }
    }


    this.renderContactList = function() {
	if(!this.profile.contact_list) {
		this.elements.contact_list.innerHTML = "Empty...";
		return;
	}
        this.elements.contact_list.innerHTML = "";
        for(var i=0; i<this.profile.contact_list.length; i++) {
           if(this.profile.contact_list[i] != undefined) {
               var itemDom = { tag: "div", className: "menu_panel", id: "contact"+i,
                               childs: [
                                 createTableDom([ {content: createButtonDom(this.profile.contact_list[i], "startNewMessage("+i+")", "widgets/messenger/img/user.gif"), width: "100%"},
                                                  {content: createButtonDom(false, "deleteContact("+i+")", theme.icons.delete_link), width: "1%"}
                                                ])
                               ]
                             }
               this.buildDomModel(this.elements.contact_list, itemDom);
           }
        }

/*        if(fl) {
            this.elements.contact_list.innerHTML = "Empty...";
        }*/
    }



    this.startNewMessage = function(contactNum) {
        hideEl(this.elements.section_contact_list);
        showEl(this.elements.section_compose);
        this.elements.edit_recipient.value = this.profile.contact_list[contactNum];
//        this.elements.edit_body.value = '';
        this.elements.edit_body.focus();
    }


    this.replyTo = function(email) {
        showEl(this.elements.section_compose);
        this.elements.edit_recipient.value = email;
        this.elements.edit_body.value = '';
        this.elements.edit_body.focus();
    }




    this.refresh = function() {
        if(!this.isUpdating) {
            request.send({act: "get_new_messages", user_id: auth.user.id}, this);
            this.isUpdating = true;
        }
    }



    this.sendMessage = function() {
        if((trim(this.elements.edit_recipient.value) == "") || 
           (trim(this.elements.edit_body.value) == "")) {
            this.elements.send_status.innerHTML = "<b>Error: </b> empty recipient or body ...";
            return;
        }
        hideEl(this.elements.send_btn);
        showEl(this.elements.send_status);
        this.elements.send_status.innerHTML = "Sending...";

        request.send({act: "send", 
                      user_id: auth.user.id, 
                      to: trim(this.elements.edit_recipient.value), 
                      body: this.elements.edit_body.value}, this);
    }



    this.firstRenderMessages = true;

    this.renderMessages = function() {
        if(this.messages.length > 0) {
            var time = new Date();
            if(this.firstRenderMessages) {
                this.elements.new_messages.innerHTML = '';
            }
            this.firstRenderMessages = false;

            var isNewMessages = false;
            for(var i=0; i<this.messages.length; i++) {
                if(this.messages[i].rendered) {
                    continue;
                }
                this.messages[i].rendered = true;
                isNewMessages = true;

                var from = (this.messages[i].from_email == "") ? 
                    { tag: "div", innerHTML: "<b>Anonymus</b>" }
                    :
                    createButtonDom("<b>"+this.messages[i].from_email+"</b>", "replyTo('"+this.messages[i].from_email+"')", "widgets/messenger/img/user.gif");
                
                this.buildDomModel(this.elements.tmp, 
                    { tag: "div", className: "menu_panel", id: "last_msg",
                      childs: [
                        from ,
                        { tag: "div", class_name: "menu_panel", innerHTML: '[' + time.toLocaleString() + ']'},
                        { tag: "div", className: "note", innerHTML: text2html(unescape(this.messages[i].body)) }
                      ]
                    });

                if(this.elements.new_messages.firstChild) {
                    this.elements.new_messages.insertBefore(this.elements.last_msg, this.elements.new_messages.firstChild);
                } else {
                    this.elements.new_messages.appendChild(this.elements.last_msg);
                }
            }
            if(isNewMessages) {
                showEl(this.elements.section_new_messages);
            }
            showEl(this.elements.clear_new_messages);
        } else {
            this.elements.new_messages.innerHTML = 'No new messages...';
        }
    }


    this.clearMessages = function() {
        this.firstRenderMessages = true;
        this.messages = [];
        this.renderMessages();
        hideEl(this.elements.clear_new_messages);
    }



    this.dispatchMsg = function(msg) {
        this.isUpdating = false;
        if(msg.status) {
            switch(msg.status) {
                case "new_messages":
                    if(msg.list.length > 0) {
                        var ids = [];
                        for(var i=0; i<msg.list.length; i++) {
                            this.messages.push(msg.list[i]);
                            ids.push(msg.list[i].id);
                        }
                        request.send({act: "set_received", user_id: auth.user.id, ids: ids.join("_")}, this);
                    }
                    this.renderMessages();
                    break;

                case "send_ok":
                    this.elements.edit_body.value = '';
                    showEl(this.elements.send_btn);
                    this.elements.send_status.innerHTML = "Message sent.";
                    break;

                case "send_error":
                    this.elements.send_status.innerHTML = "<b>Error:</b> Recipient not found...";
                    showEl(this.elements.send_btn);
                    break;
            }
        }
    }

}
Messenger.prototype = new Widget();
