<?php
  require("php/common_begin.php");
  
  $lst = Listopia::getInstance();
  // -------------------------------
  if (!$lst->isLoggedIn())
  {
    $lst->unloggedInPage();
    return;
  }
  // -------------------------------


  // try to get the list requested, or fallback to a 404
  $userID = $_GET['id'];
  $userData = NULL;
  $userTitle = 'Nobody';
  $userDesc = 'This person doesn\'t exist';
  if (isset($userID))
  {
    $query = $lst->getUserData($userID);
                        
    if (!empty($query[0]))
    {
      $userData = $query[0];
      
      $userTitle = stripslashes($userData['users']['user_name']);
      $userDesc = stripslashes($userData['users']['user_description']);
    }
  }
  
  // is this our personal page?
  $thisPageBelongsToLoggedInUser = ($userData != NULL && ($userID == Session::getInstance()->gl_userid)) || $lst->isAdminUser();
  $thisUserIsBanned = $lst->isBannedUser($userID);
  
  $lst->pageBegin($userTitle."'s Page On Listopia", $userDesc, array("js/listopia-messages.js"));
  
  $sidebar = array(
    SideBarItem::BasicListNavigator,
    SideBarItem::Profile
    );
  
  $lst->contentsBeginWithSidebar($sidebar, $userTitle, $userDesc);
  
  if ($userData != NULL)
  {
    $stats = $lst->getUserStats($userID);
    $thumbKarma = $lst->getUserThumbKarma($userID, $stats);
    
    // if this isn't our profile, get the thumb-exchange stats
    if ($userID != Session::getInstance()->gl_userid)
    {
      $thumbExchange = $lst->getUserThumbExchange($userID, Session::getInstance()->gl_userid);

      $thumbExchangeText = sprintf(
        "<div><p>This person likes <strong>%s</strong> of your submissions and thumbed-down <strong>%s</strong> of them. You, on the other hand, like <strong>%s</strong> of their entries, and hate <strong>%s</strong> of them.</p></div>",
        $thumbExchange['a2b']['like'],
        $thumbExchange['a2b']['hate'],
        $thumbExchange['b2a']['like'],
        $thumbExchange['b2a']['hate']);
    }
    
    
    $itemsPosted = $stats['items'];
    
    if ($thisUserIsBanned)
    {
      print("<img style='float:right; padding: 1px; margin: 3px; border:2px #e0e0e0 solid;' src='images/BannedBox.jpg'/>");
      $lst->UI_Misc()->openGenericBlock("They Can't Come Out To Play");
      print("<strong>Youuuuuu stupid woman!</strong><p></p>This user got banned.<br>Their profile page is now open to abuse.");
      print("<div style='clear:right'></div>");
      $lst->UI_Misc()->closeGenericBlock();
    }    
    
    // ---------------------------------------------------------------------------------------------
    $query = $lst->Database()->select(array(
                            'table' => 'avatars',
                            'condition' => 'userid = '.$userID,
                            'limit' => 1
                            ));
    if (!empty($query[0]))
    {
      $imgSrc = $query[0]['avatars']['imagedata'];
      $lst->UI_Misc()->openGenericBlock("Self Portrait");
      {
        print("<div><img class='ui-corner-all lst-avatar-img' id='avatarImage' src='");
        print($imgSrc);
        print("' /></div>");
      }
  
      if ($thisPageBelongsToLoggedInUser || $thisUserIsBanned)
      {
        print("<a tabindex='0' id='UIAvatarEditButton' style='cursor:pointer;' class='button'>Re-Draw Your Avatar...</a>");
      }
      $lst->UI_Misc()->closeGenericBlock();
    }
    else
    {
      if ($thisPageBelongsToLoggedInUser || $thisUserIsBanned)
      {
        print("<p><a tabindex='0' id='UIAvatarEditButton' style='cursor:pointer;' class='button'>Draw An Avatar...</a></p>");
      }    
    }

    // ---------------------------------------------------------------------------------------------
    $lst->UI_Misc()->openGenericBlock("Vital Statistics");
    {
      $dateCreated = date_parse($stats['created']);
      
      $dateFrom = new DateTime("now");
      $dateTo = new DateTime($stats['last_login']);
      $interval = $dateTo->diff($dateFrom);
      if ($interval->d == 0)
        $daysElapsed = "today";
      else if ($interval->d == 1)
        $daysElapsed = "yesterday";
      else
        $daysElapsed = $interval->format('%a days ago');
        

      if (intval($userID) <= 5)
        $joinTime = "Founder member";
      else
        $joinTime = "Joined in <strong>".$dateCreated['year']."</strong>";
      
?>
      <p><?=$joinTime?>, last seen <strong><?=$daysElapsed?></strong>. <?=$userTitle?> has created <strong><?=$stats['lists']?></strong> lists, posted <strong><?=$itemsPosted?></strong> entries and <strong><?=$stats['discussions']?></strong> comments.</p>
      <p><?php if ($itemsPosted > 0) : ?><strong><?=$stats['faveday']?></strong> is their favorite day to post. <?php endif; ?>
         <?php if ($stats['views'] > 0) : ?>They have clocked in <strong><?=$stats['views']?></strong> visits to lists.<?php endif; ?></p>
      <div id="UIChart-posts-over-time"><img style="margin:0px auto; display:block;" src="images/ajax-loader.gif"/></div>
      <br/><div class="lst-pf-rating"><p>Quirks<br/><strong><?=($thumbKarma['karma'])?></strong></p></div>
<?php        

    }
    $lst->UI_Misc()->closeGenericBlock();
    
    // ---------------------------------------------------------------------------------------------
    $lst->UI_Misc()->openGenericBlock("Thumb Karma");
    {
      $RecvRatio  = number_format( floatval($thumbKarma['received']['like']) / (floatval($thumbKarma['received']['hate']) + 0.00001), 2);
      $GiveRatio  = number_format( floatval($thumbKarma['given']['like']) / (floatval($thumbKarma['given']['hate']) + 0.00001), 2);
      $PveRatio   = number_format( floatval($thumbKarma['received']['like'] / (floatval($itemsPosted) + 0.00001)), 2);
      $NegRatio   = number_format( floatval($thumbKarma['received']['hate'] / (floatval($itemsPosted) + 0.00001)), 2);

?>
      <div class="lst-pf-right-edge">
      <h5>Given</h5>
      <p class="lst-pf-thumbscore">
        <img src="images/thumb-up-big.png" /><?=($thumbKarma['given']['like'])?> 
        <span class="lst-pf-right-edge-alt"><img src="images/thumb-dn-big.png" /><?=($thumbKarma['given']['hate'])?></span>
      </p>
      <p style="font-size:0.8em">Ratio (U/D) : <strong><?=$GiveRatio?></strong></p>
      </div>

      <div>
      <h5>Received</h5>
      <p class="lst-pf-thumbscore">
        <img src="images/thumb-up-big.png" /><?=($thumbKarma['received']['like'])?> 
        <span class="lst-pf-right-edge-alt"><img src="images/thumb-dn-big.png" /><?=($thumbKarma['received']['hate'])?></span>
      </p>
      <p style="font-size:0.8em">
      Ratio (U/D) : <strong><?=$RecvRatio?></strong><br/>
      Thumb Ups / Posts : <strong><?=$PveRatio?></strong><br/>
      Thumb Downs / Posts : <strong><?=$NegRatio?></strong>
      </p>
      </div>
      
      <?=$thumbExchangeText?>
<?php
    }
    $lst->UI_Misc()->closeGenericBlock();

    // ---------------------------------------------------------------------------------------------
    if ($itemsPosted > 0 && !$thisUserIsBanned)
    {
      $lastPost = $lst->getUserMostRecentPost($userID);
      if (!empty($lastPost))
      {
        $lst->UI_Misc()->openGenericBlock("The Most Recent Thing What They Done (" . date("jS \of F Y", strtotime($lastPost['t_items']['item_created'])) . ")");
        {
          $lst->defaultFormatListPost($lastPost);

          printf("<p style='text-align:right'>... on <a %s>%s</a></p>", 
            ListLink($lastPost['t_lists']['list_id'], "#entry_" . $lastPost['t_items']['item_id']), 
            stripslashes($lastPost['t_lists']['list_headline']));
        }
        
        print("<a tabindex='0' href='activity.php?id=$userID' class='button'>View Their Activity Feed...</a>");

        $lst->UI_Misc()->closeGenericBlock();    
      }
      
      $firstPost = $lst->getUserFirstPost($userID);
      if (!empty($firstPost))
      {
        $lst->UI_Misc()->openGenericBlock("The Beginning Of Their End (" . date("l jS \of F Y h:i:s A", strtotime($firstPost['t_items']['item_created'])) . ")");
        {
          $lst->defaultFormatListPost($firstPost);

          printf("<p style='text-align:right'>... on <a %s>%s</a></p>", 
            ListLink($firstPost['t_lists']['list_id'], "#entry_" . $firstPost['t_items']['item_id']), 
            stripslashes($firstPost['t_lists']['list_headline']));
        }
        $lst->UI_Misc()->closeGenericBlock();          
      }
    }
    
    // ---------------------------------------------------------------------------------------------
    if ($lst->userHasAnyComments($userID) && !$thisUserIsBanned)
    {
      $lst->UI_Misc()->openGenericBlock("Their Recent Comments");
      {
        $lst->emitUserMostRecentDiscussions($userID, 5);

        printf("</div><a id='LoadMoreOldComments' style='cursor:pointer;' class='button'>More...</a>");
      }
      $lst->UI_Misc()->closeGenericBlock();
    }
   
    // ---------------------------------------------------------------------------------------------
    if (!$thisUserIsBanned)
    {
      $query = $lst->Database()->select(array(
                              'fields' => 'list_id, list_headline, list_featured, list_submission, list_type',
                              'table' => 't_lists',
                              'condition' => 'list_featured != "deleted" and list_type != "video" and list_createdby = '.$userID,
                              'order' => 'list_created desc'
                              ));
      if (!empty($query[0]))
      {
        $lst->UI_Misc()->openGenericBlock("The Lists They Started");
        print("<ul class='lst-pf-lists'>");
        
        foreach ($query as &$list)
        {
          $listID = $list['t_lists']['list_id'];
          $headline = stripslashes($list['t_lists']['list_headline']);
          $isOpened = !$lst->isListOnlyOpenToAuthor($list['t_lists']['list_featured'], $list['t_lists']['list_submission']);
          
          $suffix = "";
          if ($list['t_lists']['list_type'] == "image")
            $suffix = $lst->getImageListAdornmentHTML();
                  
          if ($thisPageBelongsToLoggedInUser || $isOpened)
            printf("<li><a %s>%s</a>%s%s</li>\n", ListLink($listID, "&tab=".SideBarItem::BasicListNavigator."#PageContent"), $headline, $isOpened ? "" : " [not opened]", $suffix);
        }
        
        print("</ul>\n");
        $lst->UI_Misc()->closeGenericBlock();
      } 
    }

    // ---------------------------------------------------------------------------------------------
    if (!$thisUserIsBanned)
    {
      $query = $lst->Database()->select(array(
                              'fields' => 't_lists.list_id, t_lists.list_headline, t_lists.list_type',
                              'table' => 't_items',
                              'join' => 't_lists on t_lists.list_id = t_items.item_list',
                              'condition' => DBQ_CONDITION_PUBLIC_LIST.'and t_items.item_createdby = '.$userID,
                              'group' => 't_items.item_list',
                              'order' => 't_lists.list_created desc',
                              'limit' => 20
                              ));
      if (!empty($query[0]))
      {
        $lst->UI_Misc()->openGenericBlock("Some Lists They Contributed To");
        print("<ul class='lst-pf-lists'>");
        
        foreach ($query as &$list)
        {
          $listID = $list['t_lists']['list_id'];
          $headline = stripslashes($list['t_lists']['list_headline']);
          
          $suffix = "";
          if ($list['t_lists']['list_type'] == "image")
            $suffix = $lst->getImageListAdornmentHTML();
                  
          printf("<li><a %s>%s</a>%s</li>\n", ListLink($listID, "&tab=".SideBarItem::BasicListNavigator."#PageContent"), $headline, $suffix);
        }
        
        print("</ul>\n");
        $lst->UI_Misc()->closeGenericBlock();
      }     
    }
    

    // ---------------------------------------------------------------------------------------------
    if (!$thisUserIsBanned)
    { // select * from listvotes where listvotes.user = 101 order by listvotes.timestamp desc limit 15
      $query = $lst->Database()->select(array(
                              'fields' => 't_lists.list_id, t_lists.list_headline, t_lists.list_type',
                              'table' => 'listvotes',
                              'join' => 't_lists on t_lists.list_id = listvotes.list',
                              'condition' => DBQ_CONDITION_PUBLIC_LIST.'and listvotes.vote = 1 and listvotes.user = '.$userID,
                              'order' => 'listvotes.timestamp desc',
                              'limit' => 20
                              ));
      if (!empty($query[0]))
      {
        $lst->UI_Misc()->openGenericBlock("Some Lists They Like");
        print("<ul class='lst-pf-lists'>");
        
        foreach ($query as &$list)
        {
          $listID = $list['t_lists']['list_id'];
          $headline = stripslashes($list['t_lists']['list_headline']);
          
          $suffix = "";
          if ($list['t_lists']['list_type'] == "image")
            $suffix = $lst->getImageListAdornmentHTML();
                  
          printf("<li><a %s>%s</a>%s</li>\n", ListLink($listID, "&tab=".SideBarItem::BasicListNavigator."#PageContent"), $headline, $suffix);
        }
        
        print("</ul>\n");
        $lst->UI_Misc()->closeGenericBlock();
      }     
    }    
    
    // ---------------------------------------------------------------------------------------------
    if (!$thisUserIsBanned)
    {
      $query = $lst->getUserGradedPosts($userID, "desc");
      if (!empty($query[0]))
      {
        shuffle($query);
        
        $lst->UI_Misc()->openGenericBlock("Popular Posts");

        $counter = 5;
        $firstEntry = null;
        foreach ($query as &$list)
        {
          if ($list[0]['score'] <=0 )
            continue;
        
          if ($firstEntry != null)
            print("<div style='border-top:1px dashed #ddd';><br>");
                  
          $lst->defaultFormatListPost($list);

          printf("<p style='text-align:right'>... on <a %s>%s</a></p>", 
            ListLink($list['t_lists']['list_id'], "#entry_" . $list['t_items']['item_id']), 
            stripslashes($list['t_lists']['list_headline']));

          if ($firstEntry != null)
            print("</div>");
          $firstEntry = $list;

          $counter--;
          if ($counter <= 0)
            break;
        }
        
        $lst->UI_Misc()->closeGenericBlock();
      }
      
      $query = $lst->getUserGradedPosts($userID, "asc");
      if (!empty($query[0]))
      {
        shuffle($query);
        
        $lst->UI_Misc()->openGenericBlock("Craptacular Fails");

        $counter = 5;
        $firstEntry = null;
        foreach ($query as &$list)
        {
          if ($list[0]['score'] >=0 )
            continue;
          
          if ($firstEntry != null)
            print("<div style='border-top:1px dashed #ddd';><br>");
                  
          $lst->defaultFormatListPost($list);

          printf("<p style='text-align:right'>... on <a %s>%s</a></p>", 
            ListLink($list['t_lists']['list_id'], "#entry_" . $list['t_items']['item_id']), 
            stripslashes($list['t_lists']['list_headline']));

          if ($firstEntry != null)
            print("</div>");
          $firstEntry = $list;

          $counter--;
          if ($counter <= 0)
            break;
        }
        
        $lst->UI_Misc()->closeGenericBlock();
      }
    }

    // ---------------------------------------------------------------------------------------------
    if ($lst->isLoggedIn() && !$thisUserIsBanned)
    {
      $lst->UI_Misc()->openGenericBlock("Messaging");
      {
        // encode the cookie auth key, the message sending ajax thing requires it
        $cookieCodeStamp = $_COOKIE[__LAUTH_KEY__];
        if (!isset($cookieCodeStamp))
          die("AUTH ERROR 919.");
        
        // create a reply box and a button to post messages
        print("<div style='padding: 10px'>");
        {
          $lst->UI_Misc()->GenTextEntry("reply", "Talk to $userTitle:", 1000);
          print("<a id='UIProfilePostMessage' title='messages_SendFromForm($(\"#UIProfilePostMessage\"), $userID, \"$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 Them A Picture...</a>");
        print("</p></div>");
        
        printf("</div>");        
      }
      $lst->UI_Misc()->closeGenericBlock();
    }
  }
  else
  {
    $lst->UI_Misc()->AddCenteredMessageBlock(LS_PROFILE_INVALID_USERID);
  }

  // dialog block used for scribbling
  $lst->UI_Misc()->GenScribblerDialogCode();
  

  $lst->contentsEnd();

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

<script type="text/javascript" src="js/listopia-scribbler.js<?=__VERSUFFIX__?>"></script>

<!-- add inplace editing stuff for the tagline -->
<?php if ($thisPageBelongsToLoggedInUser|| $thisUserIsBanned) : ?>
<script type="text/javascript" src="js/jquery.jeditable.mini.js<?=__VERSUFFIX__?>"></script>
<script type="text/javascript">
$(document).ready(function() 
{ 
  var editableBar = $('#ui-subtitle-bar');
  
  $("<img onclick='simulatedClick($(\"#ui-subtitle-bar\").get(0));' class='lst-ui-edit-item' src='images/edit_item.png'/>").insertBefore(editableBar);
  editableBar.editable('php/ajax_profileEdit.php?id=<?=$userID?>',
  { 
    indicator   : '<img src="images/ajax-loader-small.gif">',
    tooltip     : 'Click to edit tagline...',
    placeholder : 'Click to add tagline...',
    style       : 'display: inline;'
  });
  
  $('#UIAvatarEditButton').click(function()
  {
    // build the pop-up dialog for the avatar sketching stuff
    var sketchCanvas = $('#UISketchCanvas').get(0);
    $('#UISketcher').dialog({
          draggable: false,
          modal: true,
          resizable: false,
          width: 410,
          open: function(event, ui) 
          { 
            init_AvatarScribbler( sketchCanvas ); 
          },
          beforeClose: function(event, ui) 
          { 
            term_AvatarScribbler( sketchCanvas ); 
            return true;
          },          
          buttons: 
          {
            "Save": function(event) 
            {
              $.post(
                "php/ajax_profileUpdateAvatar.php", 
                { imgdata: sketchCanvas.toDataURL('image/png'), userid:<?=$userID?> ,auth: "<?php echo $_COOKIE[__LAUTH_KEY__]; ?>" },
                function(data) 
                { 
                  location.reload();
                },
                "html");
            },
            "Cancel": function() {
              $( this ).dialog( "close" );
            }
          }
      });
  });
  
});
</script>
<?php endif ?>

<!-- create the chart requests -->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">

$(document).ready(function() 
{ 
  $('#LoadMoreOldComments').click(function()
  {
      $.post(
      "php/ajax_profileGetMoreComments.php", 
      { id: <?=$userID?> },
      function(data) 
      { 
        $('#recent_comments').html(data);
      },
      "html");
      
      $('#LoadMoreOldComments').hide();
  });  
  
  $('#UIImageMessageButton').click(function()
  {
    // 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: "<?php echo $_COOKIE[__LAUTH_KEY__]; ?>" },
                  function(data) 
                  { 
                    window.alert("Image message sent!");
                    theDlg.dialog( "close" );
                  },
                  "json");
              }
              else
              {
                window.alert("You drew nothing, chico.");
              }              
            },
            "Cancel": function() {
              $( this ).dialog( "close" );
            }
          }
      });
  });
});

var UIChartBlock = $('#UIChart-posts-over-time');
if (UIChartBlock.css('display') != 'none')
{
  function drawChart() 
  {
    $.post(
      "php/ajax_profileChart.php", 
      { id: <?=$userID?> },
      function(jsonData) 
      { 
        if (jsonData && jsonData['rows'])
        {
          var data = new google.visualization.DataTable(jsonData);
          var chart = new google.visualization.AreaChart(document.getElementById('UIChart-posts-over-time'));
          chart.draw(data, 
            {
              hAxis: 
                {
                  slantedTextAngle: 45
                },
              vAxis:
                {
                  gridlines: { color:'#eee' }
                },
              width: UIChartBlock.css('width'), 
              height: 240, 
              backgroundColor: { fill:'transparent' }, 
              title: 'Recent Posting Frequency',
              legend: { position: 'none' },
              chartArea: {width:"90%", height:"65%"},
              colors: ['#d33682']
            });
        }
        else
        {
          // nix the loading bar thing, we got no stats to display
          UIChartBlock.html("");
        }
      },
      "json");
  }

  google.load('visualization', '1.0', {'packages':['corechart']});
  google.setOnLoadCallback(drawChart);
}
else
{
  // remove the ajax loading gif, we are not going to load a graph for this media resolution
  UIChartBlock.html("");
}
</script>

<?php
  $lst->pageEnd();

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