<?php
  require("php/common_begin.php");

  $lst = Listopia::getInstance();
  // -------------------------------
  if (!$lst->isLoggedIn())
  {
    $lst->unloggedInPage();
    return;
  }
  // -------------------------------


  $lst->pageBegin(
    LS_MESSAGES_DOCUMENT_TITLE, 
    "It's good to talk", 
    array("js/listopia-messages.js"));

    
  $sidebar = array(
    SideBarItem::Messages,
    SideBarItem::BasicListNavigator,
    SideBarItem::Profile
    );

  $msgBoxName = array(
    'inbox' => "Inbox",
    'archived' => "Archive",
    'sent' => "Sent",
    'compose' => "Compose"
    );
  $msgBoxDesc = array(
    'inbox' => LS_INBOX_DESC,
    'archived' => LS_ARCHIVE_DESC,
    'sent' => LS_SENT_DESC,
    'compose' => LS_COMPOSE_DESC
    );
  $msgBoxSQL = array(
    'inbox' => "unread",
    'archived' => "archived",
    'sent' => "sent",
    'compose' => ""
    );
    
  // check the box choice, or default to the inbox
  $msgBox = strtolower( $_GET['box'] );
  if (!isset($msgBox) || !array_key_exists($msgBox, $msgBoxName))
    $msgBox = 'inbox';
    
  $lst->contentsBeginWithSidebar($sidebar, "Private Messages - ".$msgBoxName[$msgBox], $msgBoxDesc[$msgBox]);
  
  if ($lst->isLoggedIn())
  {
    // COMPOSE mode; offer the user a choice of user_names in an autocomplete box. once chosen
    //  let them post a text or picture message
    if ($msgBox == 'compose')
    {
      $lst->UI_Misc()->openGenericBlock("New Message");
      {
        print("<div style='padding: 10px'>");

        print("<div><label for='users'>Recipient:</label><input id='users' /></div><br/>");
        
        print("<div id='UIComposeBox' style='display:none'>");
        // encode the cookie auth key, the message sending ajax thing requires it
        $cookieCodeStamp = $_COOKIE[__LAUTH_KEY__];
        if (!isset($cookieCodeStamp))
          die("No cookie key? At this point? Smashing.");
        
        // create a message box and a button to post 
        {
          $lst->UI_Misc()->GenTextEntry("newMessage", "Your Message", 1000);
          print("<a id='UIProfilePostMessage' title='stubSendComposedMessage(\"$cookieCodeStamp\");' style='cursor:pointer;' class='full-width button'>Send</a>");
        }
       
        print("<div style='padding-top: 10px; text-align: center'>");
        print("<p class='smaller-centered'>Or, if you're feeling sketchy, why not");
        print("<a tabindex='0' id='UIImageMessageButton' style='cursor:pointer; margin-left: 10px;' class='button'>Send A Picture...</a>");
        print("</p></div>");
        
        print("</div>");
        
        print("</div>");
      }      
      $lst->UI_Misc()->closeGenericBlock();
      
      // dialog block used for scribbling
      $lst->UI_Misc()->GenScribblerDialogCode();
    }
    else
    {
      $userID = -1;
      if (isset($_GET['testID']))
        $userID = $_GET['testID'];
        
      $messages = $lst->getMessageData($msgBoxSQL[$msgBox], $userID);
      
      $viewingSentMessages = ($msgBox == 'sent');
      $messageDirection = $viewingSentMessages ? "to" : "from";
      
      if (!empty($messages[0]))
      {
        $lastMonthSeen = '';
        
        foreach ($messages as &$msg)
        {
          $messageID = $msg['messages']['mess_id'];
          $messageDate = $msg['messages']['mess_sent'];
          $messageMonth = date("F, Y", strtotime($messageDate));
          
          $userName = $msg['users']['user_name'];
          $userID = $msg['users']['user_id'];
          
          $messageContent = $msg['messages']['mess_content'];
          if (isContentImageStream($messageContent, $lst->Database()))
          {
            $messageContent = "<div id='UIImageMessageRep_".$messageID."'><img class='tmp-load' style='margin:0px auto; display:block' src='images/ajax-loader-small.gif'/></div>";
            $messageContentTrunc = "[Image Message]";
            $isTruncated = true;
            $isPictureMessage = true;
          }
          else
          {
            $messageContent = ConditionTextForDisplay($messageContent);
            $messageContent = str_replace("\n", "<br/>", $messageContent);
            
            $messageContentTrunc = Truncate(stripslashes($msg['messages']['mess_content']), 60);
            $isTruncated = (substr($messageContentTrunc, -3) == '...');
            $isPictureMessage = false;
          }
          
          if ($lastMonthSeen != $messageMonth)
          {
            printf("<p class='lst-message-datelrg'>$messageMonth</p>");
            $lastMonthSeen = $messageMonth;
          }
          
          printf("<div class='lst-message'><a name='msg_%s'></a>\n", $messageID);
          {
            // left-hand side of header: from/to <name>
            $profileLink = ProfileLink($userID, '#PageContent');
            
            printf("<div class='lst-message-header ui-corner-bottom'>$messageDirection <a %s>%s</a>", 
              $profileLink, 
              $userName);
              
            // rhs: date, archive button
            $archiveButtonHTML = $viewingSentMessages ? "" : 
            (
              ($msgBox == 'inbox') ? 
                "<img onclick='messages_ModifyItem(this, $messageID, \"archived\"); return false' src='images/msg_to_archive.png' alt='Move to archive'/>" : 
                "<img onclick='messages_ModifyItem(this, $messageID, \"unread\"); return false' src='images/msg_to_unread.png' alt='Move to inbox'/>"
            );
                
            printf("<code><span>%s</span> $archiveButtonHTML</code></div>", $messageDate);
              
            print("<div style='padding: 4px'>");
            {
              printf("<div id='msg-truncated_%s'><p>%s ", $messageID, $messageContentTrunc);
              if ($isPictureMessage)
              {
                printf("<a class='lst-more' href='#' onclick='messages_ExpandAndFetchImageContent(%s); return false'>[ SHOW ]</a>", $messageID);
              }
              else
              {
                if ($isTruncated || !$viewingSentMessages)
                  printf("<a class='lst-more' href='#' onclick='messages_ExpandFull(%s, true); return false'>[ MORE ]</a>", $messageID);
              }
              print("</p></div>");
              
              // create a block, initially hidden, with the full message text in
              printf("<div id='msg-full_%s' style='display:none'>", $messageID);
              printf("<p>%s<br><a class='lst-more' href='#' onclick='messages_ExpandFull(%s, false); return false'>[ LESS ]</a></p>", $messageContent, $messageID);

              // encode the cookie auth key in there as a tiny bit of spam protection (we check it in the ajax php)
              $cookieCodeStamp = $_COOKIE[__LAUTH_KEY__];
              if (!isset($cookieCodeStamp))
                die("AUTH ERROR 82.");
              
              if ($isPictureMessage)
              {
                print("<div style='padding: 10px'>");
                print("<a id='UIMakeThisMyAvatar_$messageID' title='messages_SetImageMessageAsAvatar($(\"#UIMakeThisMyAvatar_$messageID\"), $messageID, \"$cookieCodeStamp\");' style='cursor:pointer;' class='full-width button'>Set This As My Avatar Picture</a>");
                print("</div>");
              }
                                        
              // add the reply box if we're in Inbox or Archived
              if (!$viewingSentMessages)
              {
                // create a reply box and a button to post messages
                print("<div style='padding: 10px'>");
                {
                  $lst->UI_Misc()->GenTextEntry("reply".$messageID, "Dearest $userName,", 1000);
                  print("<a id='UISendMessageButton_$messageID' title='messages_SendFromForm($(\"#UISendMessageButton_$messageID\"), $userID, \"$cookieCodeStamp\");' style='cursor:pointer;' class='full-width button'>Reply</a>");
                }
                print("</div>");
              }

              // close up
              print("</div>\n"); // msg-full
            }
            print("</div>\n"); // padding div
          }
          print("</div>\n"); // lst-message
        }
      }
      else
      {
        $lst->UI_Misc()->AddCenteredMessageBlock(LS_MESSAGES_NOTHING_IN_THE_BOX);
      }
    }
  }
  else
  {
    $lst->UI_Misc()->AddCenteredMessageBlock(LS_MESSAGES_WHEN_LOGGEDOUT);
  }

  $lst->contentsEnd();

  $lst->UI_Login()->GenLoginDialog();
  
  // default script loading
  $lst->pageEndScripts();
  
  $lst->UI_Login()->GenLoginScripting();
?>

<!-- Local JS -->
<style>
.ui-autocomplete-loading { background: white url('images/ajax-loader-small.gif') right center no-repeat; }
</style>
<script type="text/javascript" src="js/listopia-scribbler.js<?=__VERSUFFIX__?>"></script>
<script type="text/javascript">
messages_UpdateBoxCounters();

function stubSendComposedMessage(auth)
{
  var userID = $('#UIComposeBox').attr('title');
  var postButton = $('#UIProfilePostMessage');
  
  messages_SendFromForm(postButton, userID, auth);
}

$(document).ready(function() 
{ 
<?php if (strpos($_SERVER['HTTP_USER_AGENT'],'iPad')) : ?>
  var removeHash = function() {
    window.location.hash = "Done";
  }
  setTimeout(removeHash, 100);
<?php endif; ?>
  

<?php
  if ($lst->isLoggedIn())
  {
    if ($msgBox == 'compose')
    {
      print('var authToken = "' . $_COOKIE[__LAUTH_KEY__] . '";');
?>
  // the users box in COMPOSE mode will show the name matches as the user types letters
  $( "#users" ).autocomplete({
        source: "php/ajax_msgACUsers.php",
        minLength: 2,
        select: function( event, ui ) {
          $('#users').attr('readonly', 'true');
          $('#UIComposeBox').show("blind").attr('title', ui.item.id);
        }
      });

  // image posting handler
  $('#UIImageMessageButton').click(function()
  {
    var userID = $('#UIComposeBox').attr('title');
    
    // build the pop-up dialog for the image message box
    var sketchCanvas = $('#UISketchCanvas').get(0);
    $('#UISketcher').dialog({
          modal: true,
          resizable: false,
          width: 410,
          open: function(event, ui) 
          { 
            init_AvatarScribbler( sketchCanvas ); 
          },
          beforeClose: function(event, ui) 
          { 
            term_AvatarScribbler( sketchCanvas ); 
            return true;
          },           
          buttons: 
          {
            "Send": function(event) 
            {
              if (!canvasIsBlank())
              {
                var theDlg = $(this);
                $.post(
                  "php/ajax_msgSendImage.php", 
                  { id: userID, imgdata: sketchCanvas.toDataURL('image/png'), auth: authToken },
                  function(data) 
                  { 
                    window.alert("Image message sent!");
                    messages_UpdateBoxCounters();
                    theDlg.dialog( "close" );
                  },
                  "json");
              }
              else
              {
                window.alert("You drew nothing, chico.");
              }                
            },
            "Cancel": function() {
              $( this ).dialog( "close" );
            }
          }
      });
  });
  

<?php
    } // is compose mode
  } // is logged in
?>
  
});

</script>

<?php
  $lst->pageEnd();

  require("php/common_end.php");
?>
