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

  $lst = Listopia::getInstance();

  $goPublic = isset($_GET['public']);
  $listID = $_GET['id'];

  $publicKey = 0;

  if (isset($listID))
  {
    $m = 0x5bd1e995;
    $k = (int)$listID;
    $k = ($k * $m) & 4294967295;
    $publicKey = ($k ^ ($k >> 24)) & 4294967295;

    if ($goPublic === TRUE && $publicKey != $_GET['public'])
    {
      $goPublic = FALSE;
    }
  }

  // -------------------------------
  if (!$lst->isLoggedIn() && $goPublic === FALSE)
  {
    $lst->unloggedInPage();
    return;
  }
  // -------------------------------

  // try to get the list requested, or fallback to a 404
  
  $listData = NULL;
  $listTitle = LS_LIST_404_TITLE;
  $listDesc = LS_LIST_404_DESC;
  if (isset($listID))
  {
    $query = $lst->getListData($listID);
                        
    if (!empty($query[0]))
    {
      $listData = $query[0];
      
      $listTitle = StringWordBreak(stripslashes($listData['t_lists']['list_headline']), 15);
      $listDesc = stripslashes($listData['t_lists']['list_standfirst']);
    }
  }
  
  $lst->pageBegin("Listopia - ".$listTitle, $listDesc, array("js/listopia-lists.js"));
  
  $sidebar = array();

  if ($goPublic === TRUE)
  {
    array_push($sidebar, SideBarItem::PublicDisplayStub);
  }
  else
  {
    // only add the "Add" panel if the list existed
    if ($listData != NULL)
      array_push($sidebar, SideBarItem::AddToList);

    // standard side-bar things for list displays
    array_push($sidebar, SideBarItem::BasicListNavigator);
    array_push($sidebar, SideBarItem::Profile);
  }
 
  $lst->contentsBeginWithSidebar($sidebar, $listTitle, $listDesc, $goPublic);

  if ($listData != NULL)
  {
    $loggedIn = $lst->isLoggedIn();
    $sesh = Session::getInstance();
    
    if ($loggedIn)
    {
      // record the visit
      $lst->incListVisitCount($sesh->gl_userid, $listID);
    }
    
    $stats = $lst->getListStats($listID);
    $listVotes = $lst->getListVote($listID);
    
    $dontDisplayPublic = (($listVotes['upvote'] + $listVotes['downvote']) < 0) && (!$loggedIn || $lst->isUserOnProbation());
    
    
    // figure out ordering choices
    $sortDisplays = array(
      'default-open' => '<strong>',   'default-close' => '</strong>',
      'score-open' => '',             'score-close' => '',
      'time-open' => '',              'time-close' => '',
      'newest-open' => '',            'newest-close' => '',
      'worst-open' => '',             'worst-close' => '',
      'user-open' => '',              'user-close' => ''
      );

    $sortPublicNames = array(
      'score' => 'Best',
      'time' => 'Oldest',
      'newest' => 'Newest',
      'worst' => 'Worst',
      'user' => 'Username'
      );
      
    $listDefaultOrdering = $listData['t_lists']['list_orderby'];
    
    $listFeat     = $listData['t_lists']['list_featured'];
    $listSub      = $listData['t_lists']['list_submission'];
    $listCreated  = $listData['t_lists']['list_createdby'];
    $listType     = $listData['t_lists']['list_type'];
    
    // we remove which of the sort options are the list's default choice
    $sortDisplays[$listDefaultOrdering.'-open'] = '<span style="display:none">';
    $sortDisplays[$listDefaultOrdering.'-close'] = '</span>';
          
    // .. then check to see if the session has an override
    if (isset($sesh->list_order))
    {
      $listDefaultOrdering = $sesh->list_order;
      
      // remove default highlight
      $sortDisplays['default-open'] = '';
      $sortDisplays['default-close'] = '';
      
      $sortDisplays[$listDefaultOrdering.'-open'] = '<strong>';
      $sortDisplays[$listDefaultOrdering.'-close'] = '</strong>';
    }
    
    $showRejects = isset($_GET['rejects']);
    
    // pull list entries
    $entries = $lst->getListEntries($listID, $listDefaultOrdering, $showRejects);
    $numEntries = count($entries);
    $numRejects = $lst->getRejectedItemCount($listID);
    
    // get the discussion items into a multidimensional array
    $entryComments = $lst->getListEntryComments($listID);
    $listComments = $lst->getListComments($listID);
    $listCommentCount = 0;
    if (isset($listComments))
      $listCommentCount = count($listComments);
    
    // create other bits of data for stats display
    $unixCreate = strtotime($listData['t_lists']['list_created']);
    $createdDate = date("F j, Y", $unixCreate);
    $profileLink = ProfileLink($listData['users']['user_id'], '#PageContent');
    
    $rules = UnStarr(stripslashes($listData['t_lists']['list_blurb']));
    if (substr($rules, 0, 2) !== "<p")
      $rules = "<p>" . $rules . "</p>";
    $rules = MakeClickableLinks($rules);
    
    $rejectOptions = "";
    if ($numRejects > 0)
    {
      $selfLink = ListLink($listID, "&rejects#PageContent");
      $rejectOptions = sprintf(", %d <a %s>rejects</a>,", $numRejects, $selfLink);
    }

    if ($goPublic === FALSE) 
    {
?>

  <div id="accordion">
    <h3><a href="#" style="padding-top:0.25em; padding-bottom:0.25em;">Info n' Chat (<?=$listCommentCount?>)</a></h3>
    <div class="lst-listinfo" style="display:none">
      <div id="rules"><?=$rules?></div>
      <div id="stats">
      <p>Created on <strong><?=$createdDate?></strong> by <a <?=$profileLink?>><?=$listData['users']['user_name']?></a></p>
      <p>It has <strong><?=$numEntries?></strong> entries<?=$rejectOptions?> and has had <strong><?=$stats['visits']?></strong> visits from Listopia members</p>
      <p>You can share it for guest viewing with <a target="_blank" href="http://www.listopia.co.uk/list.php?id=<?=$listID?>&public=<?=$publicKey?>">this link</a></p>

      <div class="lst-comment-pile-list">
        <div id="lst-comment-replacable-<?=$listID?>">
<?php
        if ($listCommentCount > 0)
        {
          foreach ($listComments as &$comment)
          {
            echo $lst->generateDiscussionCommentHTML($comment);
          }
        }
        else
        {
          print("<div class='lst-comments lst-comment-entry'>");
          print("<p>No chat here.</p>");
          print("</div>");
        }
        print("</div>"); // close lst-comment-replacable- before the add-new-comment stuff
        
      if ($lst->isLoggedIn())
      {
        // 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 112.");      
          
        print("<div class='lst-comments lst-comment-addbox' style='padding:8px'>");
        $lst->UI_Misc()->GenTextEntry("addComment", LS_LIST_COMMENT_ADD_BUTTON, 250, 3);
        print("<a id='UIAddCommentButton' title='list_AddComment($(\"#UIAddCommentButton\"), -1, $listID, $listID, \"$cookieCodeStamp\");' style='cursor:pointer;' class='full-width button'>Add</a>");
        print("</div>");
      }          
?>
      </div>
    
    </div>
    </div>
  </div>
  &nbsp;
  <div class="lst-list-sortopts"><p>
<?php if ($lst->isLoggedIn()) : ?>
  Sort by 
  <?=$sortDisplays['default-open']?>[<a href="#" onclick="list_SetSortOption(''); return false">List Default - <?=$sortPublicNames[$listData['t_lists']['list_orderby']]?></a>]<?=$sortDisplays['default-close']?> or 
  <?=$sortDisplays['score-open']?>[<a href="#" onclick="list_SetSortOption('score'); return false">Best</a>]<?=$sortDisplays['score-close']?> 
  <?=$sortDisplays['time-open']?>[<a href="#" onclick="list_SetSortOption('time'); return false">Oldest</a>]<?=$sortDisplays['time-close']?> 
  <?=$sortDisplays['newest-open']?>[<a href="#" onclick="list_SetSortOption('newest'); return false">Newest</a>]<?=$sortDisplays['newest-close']?>
  <?=$sortDisplays['worst-open']?>[<a href="#" onclick="list_SetSortOption('worst'); return false">Worst</a>]<?=$sortDisplays['worst-close']?>
  <?=$sortDisplays['user-open']?>[<a href="#" onclick="list_SetSortOption('user'); return false">Username</a>]<?=$sortDisplays['user-close']?>
<?php else: ?>
  Default display. Log in to get freaky with the sorting.
<?php
  endif;
?>
  </p></div>

<?php
    }

    // Bring forth The List

    if ($dontDisplayPublic == true)
    {
      $lst->UI_Misc()->AddCenteredMessageBlock("<img src='images/crow-alert.png'><br/><strong>CROW XING</strong><br/><br/>This list is only visible to registered users.<br/><br/>This might be because it's terrible, or that it's a bit 'rich' for public consumption.");
    }    
    else if ($listType == 'video')
    {
      $lst->UI_Misc()->AddCenteredMessageBlock("Sadness!<br/>Video lists are no longer supported");
    }
    else if ($listFeat != 'deleted')
    {
      $minimumEntries = $lst->getListMinimumEntries($listID);
      
      if ($showRejects)
      {
?>
        <div class='ui-corner-all lst-not-open-yet'>
          <p><strong>THE REJECTS</strong></p>
        </div>
        <br/>
<?php      
      }
      
      // we wrap the list data in a div that will be used to replace it all if we add a new item to it
      echo "<div id='lst-list-replacable'>";
      {
        $listHTML = $lst->generateListEntriesHTML($listID, $entries, $entryComments, $listData, $showRejects, $goPublic);
        echo $listHTML;
      }
      echo "</div>";

      // show the control panel for immature lists
      if ($lst->isListOnlyOpenToAuthor($listFeat, $listSub) && $listCreated == Session::getInstance()->gl_userid)
      {
?>    
      <div class='ui-corner-all lst-not-open-yet'>
        <p><strong>This list is not open to the public yet</strong></p>

        <div id='UIControlBox-not-open' <?php if ($numEntries >= $minimumEntries) echo "style='display:none'"; ?> >
          <p>Add at least <?=$minimumEntries?> entries, then you can open it up.</p>
        </div>

        <div id='UIControlBox-is-open' <?php if ($numEntries < $minimumEntries) echo "style='display:none'"; ?> >
          <p>... But it could be. Tap below to permanently open it up and let people contribute.</p>
          <a tabindex='0' href='#' id='UIOpenListButton' style='cursor:pointer;' class='half-width button'>Open</a><br/>
        </div>

        <br/><p><strong>Alternatively if it's all gone wrong, you can delete it</strong></p>
        <p>Drugs worn off, eh? Careful - deletion is permanent.</p>
        <a tabindex='0' href='#' id='UIDeleteListButton' style='cursor:pointer;' class='half-width button'>Destroy</a>
      </div>

<?php
      }
      else if ($lst->isAdminUser())
      {
?>      
      <br/>
      <div id="adminAccordion">
        <h3><a href="#" style="padding-top:0.25em; padding-bottom:0.25em;">Admin Tools (<?php echo $listFeat?>, <?php echo $listSub?>)</a></h3>
        <div class="lst-listinfo" style="display:none">
          <a tabindex='0' href='#' id='UIDeleteListButton' style='cursor:pointer;' class='half-width button'>Delete This List</a>
          <a tabindex='0' href='#' id='UISealListButton' style='cursor:pointer;' class='half-width button'>Seal/Archive</a>
          <a tabindex='1' href='#' id='UIChangeSortingBest' style='cursor:pointer;' class='half-width button'>Sort: Best</a>
          <a tabindex='2' href='#' id='UIChangeSortingTime' style='cursor:pointer;' class='half-width button'>Sort: Time</a>
        </div>
      </div>
<?php
      }
    }
    else
    {
      $lst->UI_Misc()->AddCenteredMessageBlock("IT'S DEAD, JIM");
    }
    
    if ($listType == 'image')
    {
      // dialog block used for scribbling
      $lst->UI_Misc()->GenScribblerDialogCode();  
    }    
  }
  
?>
  <br/>
  <br/>
  <div id="UIRejectionDialog" title="Reject This?" style="display:none">
    <form id="Reject" action="">
      <label for="Reason">Reason</label><input type="text" id="Reason" />
    </form>
  </div>
<?php
  
  $lst->contentsEnd();

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

<!-- Local JS -->
<script type="text/javascript" src="js/listopia-scribbler.js<?=__VERSUFFIX__?>"></script>
<script type="text/javascript" src="js/jquery.jeditable.mini.js<?=__VERSUFFIX__?>"></script>
<script type="text/javascript">
$(function() {
  
  <?php // fix a bug on iPad where page scrolling gets reset to the top of the page when we use #PageContent anchors
        if (strpos($_SERVER['HTTP_USER_AGENT'],'iPad')) : ?>
  var removeHash = function() {
    window.location.hash = "Done";
  }
  setTimeout(removeHash, 100);
  <?php endif; ?>
  
  $("#accordion").accordion({
    active: false,
    collapsible: true,
    autoHeight: false
    });
  $("#adminAccordion").accordion({
    active: false,
    collapsible: true,
    autoHeight: false
    });    
    
  list_TagEditableItems();
  
  function handleListStateChangeButton(thisButton, opmod)
  {    
    // disable the button while we work
    var prevOnclick = thisButton.attr('onclick'); 
    thisButton.attr('onclick','');
    thisButton.fadeTo('fast', 0.5);
    thisButton.html('<img src="images/ajax-loader-fb.gif"/>');
    {
      // request creation
      $.post(
        "php/ajax_listOpen.php", 
        { 
          id: <?=$listID?>, op: opmod
        },
        function(data) 
        { 
          // we're done, re-enable the button
          thisButton.fadeTo('fast', 1.0);
        
          if (data['success'] == undefined)
          {
            thisButton.html(data['result']);
          }
          else
          {
            location.reload();
          }
          
          thisButton.attr('onclick', prevOnclick);
        },
        "json");  
    }
  }
  function handleListSealButton(thisButton, opmod)
  {    
    // disable the button while we work
    var prevOnclick = thisButton.attr('onclick'); 
    thisButton.attr('onclick','');
    thisButton.fadeTo('fast', 0.5);
    thisButton.html('<img src="images/ajax-loader-fb.gif"/>');
    {
      // request creation
      $.post(
        "php/ajax_listSeal.php", 
        { 
          id: <?=$listID?>, op: opmod
        },
        function(data) 
        { 
          // we're done, re-enable the button
          thisButton.fadeTo('fast', 1.0);
        
          if (data['success'] == undefined)
          {
            thisButton.html(data['result']);
          }
          else
          {
            location.reload();
          }
          
          thisButton.attr('onclick', prevOnclick);
        },
        "json");  
    }
  }
  
  $("#UIOpenListButton").click(function(ev)
  {
    handleListStateChangeButton( $(this), "everyone" );
    ev.preventDefault();
    ev.stopPropagation();
  });  
  
  $("#UIDeleteListButton").click(function(ev)
  {
    if (confirm("Delete? You Sure, Buddy?") == true)
      handleListStateChangeButton( $(this), "deleted" );
    ev.preventDefault();
    ev.stopPropagation();
  });

  $("#UISealListButton").click(function(ev)
  {
    if (confirm("SEAL IT UP? LOCK IT DOON?") == true)
      handleListSealButton( $(this), 1 );
    ev.preventDefault();
    ev.stopPropagation();
  });
  
  $("#UIChangeSortingBest").click(function(ev)
  {
    if (confirm("Switch to sorting-by-best?") == true)
    {
      var thisButton = $(this);
      var prevOnclick = thisButton.attr('onclick'); 
      thisButton.attr('onclick','');
      thisButton.fadeTo('fast', 0.5);    
      
       // request creation
      $.post(
        "php/ajax_listModify.php", 
        { 
          id: <?=$listID?>,
          sortorder: 'score'
        },
        function(data) 
        { 
          // we're done, re-enable the button
          thisButton.fadeTo('fast', 1.0);
        
          if (data['success'] == undefined)
          {
            thisButton.html(data['result']);
          }
          else
          {
            location.reload();
          }
          
          thisButton.attr('onclick', prevOnclick);
        },
        "json");  
    }
    ev.preventDefault();
    ev.stopPropagation();
  });  
  
  $("#UIChangeSortingTime").click(function(ev)
  {
    if (confirm("Switch to sorting-by-time?") == true)
    {
      var thisButton = $(this);
      var prevOnclick = thisButton.attr('onclick'); 
      thisButton.attr('onclick','');
      thisButton.fadeTo('fast', 0.5);    
      
       // request creation
      $.post(
        "php/ajax_listModify.php", 
        { 
          id: <?=$listID?>,
          sortorder: 'time'
        },
        function(data) 
        { 
          // we're done, re-enable the button
          thisButton.fadeTo('fast', 1.0);
        
          if (data['success'] == undefined)
          {
            thisButton.html(data['result']);
          }
          else
          {
            location.reload();
          }
          
          thisButton.attr('onclick', prevOnclick);
        },
        "json");  
    }
    ev.preventDefault();
    ev.stopPropagation();
  });  
  
  
  var imagePostBtn = $('#UIAddImagePostButton');
  if (imagePostBtn.get() != undefined)
  {
    imagePostBtn.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: 
            {
              "Add": function(event) 
              {
                $( this ).dialog( "close" );
                if (!canvasIsBlank())
                {
                  list_AddPost(imagePostBtn, <?=$listID?>, "<?=$listDefaultOrdering?>", "<?=$_COOKIE[__LAUTH_KEY__]?>");
                }
                else
                {
                  window.alert("You drew nothing, chico.");
                }
              },
              "Cancel": function() {
                $( this ).dialog( "close" );
              }
            }
        });
    });  
  }
});
</script>

<?php
  $lst->pageEnd();

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