
   /*****************************************************************************/
   /*                                                                           */
   /*  MessageBox: (Instant)Messanger System                                    */
   /*                                                                           */
   /*  Methods:                                                                 */
   /*                                                                           */
   /*  getActiveMessageId()             -  returns id of current message        */
   /*  getActiveMessageSenderId()       -  returns id of current sender         */
   /*  getReplyRecipient()              -  returns recipient Id                 */
   /*  setReplyRecipient()              -  set recipient Id                     */
   /*  storeReplyRecipient()            -  store sender of msg for reply        */
   /*  fetchStoredReplyRecipient()      -  return stored sender id              */
   /*  getReplyText()                   -  returns replytext.value              */
   /*  setReplyText(val)                -  updates replytext.value              */
   /*  getCurrentLength()               -  return string length of reply text   */
   /*  setMessage(message)              -  fill input box with text             */
   /*  messageSetStatus(message, stat)  -  set status of message                */
   /*  messageMarkAsRead(message)       -  set status of message to read        */
   /*  messageMarkAsAswered(message)    -  set status of message to answ.       */
   /*  replyPrepare(message_id)         -  toggle display of input area         */
   /*  replyCancel()                    -  clear and hide input area            */
   /*  messageIsLegal(messagetext)      -  validates input text                 */
   /*  showBuddyList()                  -  unhide buddy selector                */
   /*  hideBuddyList()                  -  hide buddy selector                  */
   /*  updateBuddyList(recipient) (opt) -  load buddies into selector           */
   /*  writeNewPrepare(recipient)       -  compose a new message                */
   /*  settexpand()                     -  set texpand status                   */
   /*  messageIsReply()                 -  is message to be sent a reply?       */
   /*  replySend(sender_id)             -  sends message to recipient           */
   /*  sendContactRequest(recipient_id) -  send a contact request               */
   /*  acceptContactRequest(sender_id)  -  accept a contact request             */
   /*  denyContactRequest(sender_id)    -  deny a contact request               */
   /*                                                                           */
   /*****************************************************************************/

   var MessageBox = Class.create();
   
   MessageBox.prototype = {
   
      // constructor
      initialize: function(user_id) {
         this.id = user_id;
         this.message_container   = "messagebox_text";
         this.reply_container     = "messagebox_reply";
         this.reply_textfield     = "messagebox_replytext";
         this.buddylist_select    = "messagebox_buddylist";
         this.buddylist_container = "recipient_chooser";

         this.refreshtime = 10;
         this.lastmessage = "";
         this.firstcall = true;
         this.message_maxlength = 64000;
         
         this.replyrecipient = null;
         this.replymessageid = null;
         
         this.randomnumber = Math.random();
         //alert(this.randomnumber);
         
         this.texpand = false;
         
         this.getLatest();
         new PeriodicalExecuter(function(pe) {
            this.getLatest();
         }.bind(this), this.refreshtime);
         

         /*
         // use a periodical updater to update messagebox
         var url = 'ajax/messagebox-getlatest.php';
         new Ajax.PeriodicalUpdater(this.message_container, url, {
            frequency: this.refreshtime,
            decay: 1,
            parameters: { 
                  user_id: this.id
            },
            onSuccess: function(transport) {
               
               if (this.lastmessage != transport.responseText) {
                  this.lastmessage = transport.responseText;
                  
                  // on first call of updater don't flash the message
                  if (this.firstcall) {
                     this.firstcall=false;
                  } else {
                     new Effect.Highlight(this.message_container);
                  }
               }
               
            }.bind(this)
         });
         */
         
      },
      hello: function() {
         alert('hello from class-messagesbox.js');
      },
      
      
      // update message box, check for mails and buddy status
      getLatest: function() {
         
         //try {
         //   dump.add("getlatest from messagebox: " + this.randomnumber);
         //} catch(e) {}
         
         var url = 'ajax/messagebox-getlatest.php';
         
         var pars = {
            user_id: this.id
         };
         
         new Ajax.Request(url, {
                  method: 'post',
                  parameters: pars, 
                  onSuccess: function(transport) {
                        var response = transport.responseJSON;
                        
                        gui.handleResponse(response);
                        
                        if (response.whoison_more > 0) {
                           $('whoison_container').show();
                        }
                        
                        if (response.whoison_more) {
                           var number = response.whoison_more;
                           var kollegin = "Kolleginnen";
                           
                           if (number == 1) { 
                              number = "eine"; 
                              kollegin = "Kollegin";
                           }
                           
                        } else {
                           var number = "keine";
                           var kollegin = "Kollegin";
                        }
                           
                        
                        if (response.on_buddies) {
                           
                           var on_buddies = response.on_buddies.evalJSON(true);
                           
                           try {
                              $('whoison_list_buddies').update();
                           } catch(e) {}
                           
                           if (on_buddies.length>0) {
                              
                              on_buddies.each(function(buddy) {
                                    try {
                                       
                                       var li_buddy = new Element('li', {
                                          id: "messagebox_buddylist_entry_"+buddy.user_id,
                                          title: "Kontakt "+buddy.vorname+" "+buddy.nachname+" ist online", 
                                          className: 'buddy'
                                       }).update(buddy.nickname);
                                       
                                       li_buddy.observe('click', function(event) {
                                          user.messagebox.writeNewPrepare(buddy.user_id);
                                       }.bind(this));
                                       
                                       $('whoison_list_buddies').insert(li_buddy);
                                       
                                    } catch(e) { }
                              });
                           
                              var status = "Sowie " + number + " weitere " + kollegin + ".";
                              
                           } else {
                           
                              if (response.whoison_more + on_buddies.length) {
                                 var status = "Keiner deiner Kontakte online.";
                                 status += " Jedoch " + number + " andere " + kollegin + ".";
                              } else {
                                 var status = "Zurzeit ist keiner deiner Kontakte in Hebiana online.";
                              }
                              
                           }
                           if (response.whoison_more + on_buddies.length) {
                              status += ' <a href="http://'+baseurl+'user/online" title="Übersicht aller aktuell in Hebiana aktiven Kolleginnen." >Liste anzeigen...</a>';
                           }
                           
                           try {
                              $('whoison_status').update(new Element('p').update(status));
                           } catch(e) {}
                           
                        }
                        
                        
                        // if message is new...
                        if (this.lastmessage != response.html) {
                           this.lastmessage = response.html;
                          
                           if (response.html && response.buttons) {
                              try {
                                 $(this.message_container).update(response.html);
                                 $(this.message_container).insert(response.buttons);
                              } catch(e) {}
                           }

                           // on first call of updater don't flash the message
                           if (this.firstcall) {
                              this.firstcall=false;
                           } else {
                              try {
                                 new Effect.Highlight(this.message_container);
                              } catch(e) {}
                           }
                        }
                        
                  }.bind(this)
         });
         
      },
      
      
      
      // return id of messageboxes user
      getUserId: function() {
         return this.id;
      },
      
      
      // return id of currently displayed message
      getActiveMessageId: function() {
         return $('message_id').innerHTML;
      },
      
      // return sender id of currently displayed message
      getActiveMessageSenderId: function() {
         return $('message_sender_id').innerHTML;
      },
      
      
      // retreives UserId of "actual"!! message from HTML box (invisible div) or Buddylist
      // this id may be updated while the user is writing a reply!!
      
      getReplyRecipient: function() {
         
         if ($(this.buddylist_container).visible()) {
            var recipient = $(this.buddylist_select).value;
         } else {
            var recipient = $('message_sender_id').innerHTML;
         }
         
         return recipient;
      },
      
      setReplyRecipient: function(replyrecipient) {
         this.replyrecipient = replyrecipient;
      },
      
      
      
      // store sender of message to which a reply is about to be written
      storeReplyRecipient: function() {
         this.replyrecipient = this.getReplyRecipient();
      },
      
      // return previously stored reply recipient
      fetchStoredReplyRecipient: function() {
         return this.replyrecipient;
      },
      
      
      // store id of message to which a reply is about to be written
      storeReplyMessageId: function() {
         this.replymessageid = $('message_id').innerHTML;
      },
      

      // return previously stored if of message to reply to
      fetchStoredReplyMessageId: function() {
         return this.replymessageid;
      },

      
      getReplyText: function() {
         return $(this.reply_textfield).value;
      },
      
      setReplyText: function(sValue) {
         try {
            $(this.reply_textfield).value = sValue;
         } catch(e) {}
      },
      
      // return string length of reply text
      getCurrentLength: function() {
         return $(this.reply_textfield).value.length;
      },
      
      // returns max. allowes length for message text
      getMaxLength: function() {
         return this.message_maxlength;
      },
      
      
      // write something into message container, highlight it
      setMessage:function(message) {
         $(this.message_container).update(message);
         new Effect.Highlight(this.message_container);
      },
      
      
      
      messageSetStatus:function(message_id, status) {
         
         var url = 'ajax/messagebox-setstatus.php';
         var pars = {
            message_id: message_id,
            status: status
         };
            
         new Ajax.Request(url, {
                  method: 'post',
                  parameters: pars, 
                  onComplete: function(transport) {
                        var response = transport.responseJSON;
                        if (response.success) {
                           
                           // todo: provide feedback
                           // alert("und jetzt die Message irgendwie farblich markieren und die Anzahl der ungelesenen Messages refreshen!");
                           try {
                              $('messagebox_info_unread').setStyle({ textDecoration:'line-through' });
                           } catch(e) {}
                           try {
                              $('messagebox_text_p').setStyle({ color:'#666' });
                           } catch(e) {}
                           
                           /*
                           // refresh mailbox list also
                           try {
                              user.mailbox.updateList();
                           } catch(e) {}
                           */
                           
                        }
                  }.bind(this)
         });
         
      },
      
      
      messageMarkAsUnread:function(message_id) {
         this.messageSetStatus(message_id, 0);
      },
      
      messageMarkAsRead:function(message_id) {
         this.messageSetStatus(message_id, 1);
      },
      

      messageMarkAsAnswered:function(message_id) {
         dump.add("Messagebox:messageMarkAsAnswered() setting id=" +message_id+ " to 2");
         this.messageSetStatus(message_id, 2);
      },

      
      // toggle display of input area for replies
      replyPrepare:function(message_id) {
         
         // store sender of current! message for later use (even if a new message arrives in the meantime)
         this.storeReplyRecipient();
         this.storeReplyMessageId();
         
         // this.messageMarkAsRead(message_id);
         this.hideBuddyList();
         new Effect.BlindDown(this.reply_container, {duration:0.5});
      },
      
      
      // cancel the typing of a reply (close input area)
      replyCancel:function() {
         this.setReplyText("");
         this.hideBuddyList();
         new Effect.BlindUp(this.reply_container, {duration:0.5});
      },
      
      
      // validates if a messagetext is okay for sending
      messageIsLegal:function(messagetext) {
        
         if (messagetext.length > this.getMaxLength()) {
            alert("Nachricht zu lang!");
            return false;
         } else if(messagetext.length<1) {
            alert("Bitte erst die Nachricht schreiben, dann senden.");
            return false;
         } else return true;
         
      },

      
      showBuddyList:function() {
         try {
            $(this.buddylist_container).show();
         } catch(e) {}
      },
      
      hideBuddyList:function() {
         try {
            $(this.buddylist_container).hide();
         } catch(e) {}
      },
      
      
      // fill buddylist select box with actual values
      // optional parameter: recipient_id for pre-selection
      // optional parameter: addnull (bool) to add a --------- line
      updateBuddyList:function(recipient_id, addnull) {
         
         var url = 'ajax/socialcontacts-buddyselect.php';
         var pars = {
            user_id: this.getUserId()
         };
         
         if (recipient_id) {
            pars.recipient_id = recipient_id;
         }
         if (addnull) {
            pars.addnull = true;
         }
            
         new Ajax.Request(url, {
                  method: 'post',
                  parameters: pars, 
                  onComplete: function(transport) {
                        var response = transport.responseJSON;
                        if (response.html) {
                           try {
                              $(this.buddylist_select).update(response.html);
                           } catch(e) {}
                           
                        }
                  }.bind(this)
         });
                              
         
      },
      
      
      // compose a new message
      // optional parameter: recipient_id
      writeNewPrepare:function(recipient_id) {
                 
         if (recipient_id) {
            this.updateBuddyList(recipient_id);
         } else {
            this.updateBuddyList();
         }
         //alert('container' +this.reply_container);   
         this.showBuddyList();
         if ($('messagebox_reply').visible() == false) {
            new Effect.BlindDown(this.reply_container, {
                  duration: 0.5,  
                  afterFinish: function() {                  
                     if (this.texpand != true) {
                        new Texpand(this.reply_textfield);
                        this.settexpand();                        
                        $(this.reply_textfield).focus();                        
                     }
                  }.bind(this)  
            });
         } else {
            $(this.reply_textfield).focus();
         }
      },
      
      settexpand: function () {
         this.texpand = true;
      },

      
      
      // returns true if message to be sent is a real reply
      messageIsReply: function() {
         // if buddy selector is NOT visible it's a reply 
         // return( !($('recipient_chooser').visible()) );
         return( !($(this.buddylist_container).visible()) );
      },
      
      
      
      // really send the message (write to db)
      sendMessage: function(recipient_id, sender_id, message_text) {
         
         // dump.add("Messagebox:sendMessage()");
         // dump.add("isReply? " + this.messageIsReply() );
         
         var url = 'ajax/messagebox-reply.php';
         
         var pars = {
            recipient_id: recipient_id,
            sender_id: sender_id,
            messagetext: message_text
         };
         
         new Ajax.Request(url, {
                  method: 'post',
                  parameters: pars, 
                  onComplete: function(transport) {
                        // this.workingindicator.switchOff();
                        var response = transport.responseJSON;
                        
                        if (response.success) {
                           
                           // write feedback into text field
                           this.setReplyText("Nachricht gesendet.");
                           
                           // mark message as read and answered
                           if (this.messageIsReply()) {
                              
                              if (this.fetchStoredReplyMessageId()) {
                              this.messageMarkAsAnswered(this.fetchStoredReplyMessageId());
                              } else {
                              this.messageMarkAsAnswered(this.getActiveMessageId());
                              }
                              
                           } else {
                              
                              // this.needs_refresh = true;
                              
                           }
                             
                           // close, than clear reply drawer
                           new Effect.BlindUp(this.reply_container, {
                              duration: 0.5,
                              afterFinish: function() {
                                 this.setReplyText("");
                                 
                                 // refresh mailbox list also
                                 // if (this.needs_refresh) {
                                    try {
                                       user.mailbox.updateList();
                                    } catch(e) {}
                                 // }
                                 
                                 
                              }.bind(this)
                           });
                           
                        } else {
                           alert("Error writing message to database!");
                        }
                        
                  }.bind(this)
         });
      
         
      },
      
      
      
      // send a reply to recipient_id
      replySend: function() {
         
         if (this.messageIsReply()) {
            var recipient_id = this.fetchStoredReplyRecipient();
         } else {
            var recipient_id = this.getReplyRecipient();
         }         
        
         var message_text = this.getReplyText();
         
         if (this.messageIsLegal(message_text)) {
            this.sendMessage(recipient_id, this.getUserId(), message_text);
         }
         
      },
      
      
      
      // send a contact request message (special cmd type)
      sendContactRequest: function(recipient_id) {
         
         var url = 'ajax/messagebox-contactrequest-send.php';
         var pars = {
            recipient_id: recipient_id,
            sender_id: this.getUserId()
         };
         
         new Ajax.Request(url, {
               method: 'post',
               parameters: $H(pars).toQueryString(), 
               onComplete: function(transport) {
                     var response = transport.responseJSON;
                     
                     gui.handleResponse(response);
                     
                     if (response.success) { 
                        this.setReplyText("");
                        new Effect.BlindUp(this.reply_container, {duration:0.5});
                        
                        alert("Der Eintrag als Kontakt muß jetzt von der anderen Seite angenommen werden. Bitte habe etwas Geduld, bis dies passiert.");
                        
                     } else {
                        
                        if (response.errortype == "accepted") {
                           alert("Ooops. Dieser Kontakt ist bereits in der Kontaktliste.");
                        } else
                        
                        if (response.errortype == "waiting") {
                           alert("Dieser Kontakt wurde bereits angefragt und muß nur noch von der anderen Seite bestätigt werden.");
                        } else
                        
                        alert("Error writing message to database!");
                     }
                     
               }.bind(this)
         });
         
         
      },
      
      
      
      // accept a contact request, add to social contacts, send confirmation
      acceptContactRequest:function(sender_id) {        
         if (!sender_id) { sender_id = this.getActiveMessageSenderId(); }         
         // let user know that adding a new contact has been triggered
         this.storeReplyRecipient();
         this.setReplyText("Systemmeldung: Das Hinzufügen zur Kontaktliste wurde soeben von mir bestätigt.");
         this.replySend(sender_id);
         
         // create new social contact
         user.friends.createFriendship(sender_id);
         
         this.messageMarkAsAnswered(this.getActiveMessageId());
         this.setMessage('<p>Anfrage bestätigt.</p>');         
      },
      
      
      // deny a contact request, don't add to social contacts, send denial
      denyContactRequest:function(sender_id) {
         if (!sender_id) { sender_id = this.getActiveMessageSenderId(); }
         this.storeReplyRecipient();
         this.setReplyText("Systemmeldung: Das Hinzufügen zur Kontaktliste wurde von mir abgelehnt.");
         this.replySend(sender_id);
         
         // clear waiting status in table social contact
         user.friends.clearWaitingFriendship(sender_id);
         
         this.messageMarkAsAnswered(this.getActiveMessageId());
         this.setMessage('Anfrage abgelehnt.');      
      },
      
      
      notify_user_who_is_removed: function(sender_id) {
         this.setReplyRecipient(sender_id);
         this.setReplyText("Systemmeldung: Du wurdest aus der Kontaktliste entfernt.");
         this.replySend();
      }
      
   }
