
xyzzy = 0;

// Works out which filters are working. Empty array means show everything, otherwise each element is a page_type to show.
var activeClasses = new Array();

var page_date = '';                         // The publish date of the current box. Used to set first/last dates and to fetch additional boxes. 
var last_visible_item = '';                 // The publish date of the last box on the page, used for pagination.
var first_visible_item = '';                // The publish date of the first box on the page, used for pagination.
var first_item_selected = false;            // Used to keep track on whether the first item on the page has been placed yet.
var previous_visible_items = new Array();   // The publish date of the first box on the previous pages, used for pagination.
                                            // When the next page is called the current value of first_visible_item is pushed to the array.
                                            // When the previous page is called, if this array is not empty, the last element is poped from the array,
                                            // removing it and giving a reference point to fetch from.
var completedCols = 0;                      // Number of columns in page
var colHeight = 0;                          // Height of the current column, when this is above [minColHeight] then the column is completed

var colHeightNeeded = 0;
var persistentColHeightNeeded = 0;
    
var col;                            // The current column element
var container;                      // The container for the current column, just for layout

var selector = '.box:not(.invis)';  // used to select elements visible to the user

var minColHeight = 400;             // minumum column height, static for now.
var cols = 0;

var boxesNext = 0;

$(document).ready(function() {
  
  $fullwall = $('.box-parent-main').first();    // The full collection
  $wall = $('.box-parent').first();             // The currently visible collection

  var BOXWIDTH = 180;                     // The width of each box. Used to calculate columns on page
  var BOXMARGIN = 6;                      // The margin on each side of each box. Also used to calculate columns on page
  
  /** Calculate number of columns and height of each column **/
  var spaceX = $('.box-parent').first().width();                              // width of container  
  cols = Math.floor(spaceX / (BOXWIDTH + (2*BOXMARGIN) - BOXMARGIN));     // number of columns, taking into account box width and margins.
  
  $.get("/ajax-cookie.php", { retrieve: 1 }, function(data) {
	  activeClasses = JSON.parse(data);
	  
	  if (window.location.hash && window.location.hash != '#') {
      var requestedTag = window.location.hash.substring(1);
      var key = array_search(requestedTag, activeClasses);
      if (key === false) activeClasses.push(requestedTag);
    }
	  
    syncBoxActiveStates();
    
    colHeightNeeded = minColHeight * cols;
    persistentColHeightNeeded = colHeightNeeded;
    $('#loading-feature-content-bar').css('width', '0%');
    $('#loading-feature-content').show();

    xyzzy = 0;
    addExtraIfNeeded();
  });
  
});

/** Check if any extra boxes needs to be added to the wall, fetch them if they do.**/
function addExtraIfNeeded() {
  if (xyzzy > 100) return false;
  
  var poststr = 'ajax=1&getNewBoxes=1&number=1&tags='+JSON.stringify(getActiveClasses());    // params to send to fetch boxes

  if (page_date != '') { poststr2 = poststr + '&offset='+page_date; }                   // add offset onto string if available
  else poststr2 = poststr;
    
  /** make the post **/
  $.post(
    'index.php',
    poststr2,
    function (r) {
      if (r != 'false') {
        page_date = $(r).find('.page_date').html();
        
        $fullwall.find('li.col:first-child > ul').append($(r));                            // append fetched box to the [fullwall], li.col is the container, and the ul is the column.
        
        $fullwall.find('li.col:first-child > ul').css('display', 'block');
        colHeightNeeded -= $fullwall.find('li.col:first-child > ul li:last-child').height();
        
        var percentLoaded = (persistentColHeightNeeded - colHeightNeeded) / (persistentColHeightNeeded / 100);
        if (percentLoaded > 99.2) percentLoaded = 99.2;
        $('#loading-feature-content-text').html('<img src="/images/cdf-loadingIcon.png" />');
        $('#loading-feature-content-bar').css('width', percentLoaded+'%');
        
        paramstr = 'ajax=1&getNewBoxes=1&number=1&dir=forward&tags='+JSON.stringify(getActiveClasses());
        if (page_date != '') {
          paramstr += '&datestamp='+page_date;
        }
        
        $.post(
          '/ajax/countPagesLeft.php',
          paramstr,
          function (r) {
              if (r == 0) $('#more-boxes').hide();
              else $('#more-boxes').show();
            xyzzy++;
            boxesNext = r;
              if (colHeightNeeded <= 0 || xyzzy >= 100 || boxesNext == 0) { $('#loading-feature-content').fadeOut(); resizeCallback(true);  }
              else addExtraIfNeeded();
          },
          'html'
        );
      }
      else {
        $('#loading-feature-content-bar').css('border-width', '0');
        $('#loading-feature-content-text').html('<img src=\"/images/cdf-noContent.png\" />');
      }
      
    },
    'html'
  );
  
  return true;
}

/**
 * Will add items to columns.
 * If the column is taller than the [minColHeight] then it will add the column to the page and create a new column.
 * If the number of columns equals [cols] then the script is done.
 * Else if all of the boxes are processed before the number of columns equals [cols] then try to fetch more via ajax
 * 
 * If [reset] is true then start with the collection from [$fullwall], otherwise start with the collection from [$wall].
 **/
function resizeCallback(reset_me) {

  $fullwall = $('.box-parent-main').first();    // The full collection
  $wall = $('.box-parent').first();             // The currently visible collection
  
  /** Whether to reset the [$wall] or the [$fullwall] **/
  if (reset_me === false) {
    $fullwall.find('.col ul').empty();
    $wall.find(selector).clone().appendTo($fullwall);
  
  }
  
  $boxes = $fullwall.find(selector);      // Current collection
  
  var number = $boxes.length;         // Number of boxes in the current collection
    
  // add all items in the boxes collection to the wall
  addItems($boxes);
  
  // remove the mention links, another piece of code handles that.
  var twitterAtRegex = '@(.*)';
  $('.box.twitter a').each(function(i, that) {
    var txt = $(that).text();
    if (txt.search(twitterAtRegex) != -1) {
      var $t = jQuery(this);
      $t.after($t.text());
      $t.remove();
    }
  });
  
  twttr.anywhere(function (T) {
    T.hovercards();
  });
}

/** Adds an item to a column, the column to a container, and the container to the wall **/
function addItem(box, colHeight, completedCols, aca) {
  // If colHeight is 0 it means there isn't a column (either because it hasn't been created or because the last one was just added to the wall) so create one
  if (colHeight == 0) {
    
    container = document.createElement('li');       // create container
    container.setAttribute('class', 'col');
    col = document.createElement('ul');             // create column
  }

  page_date = $(box).find('.page_date').text();     // get the date of the current box
  
  if (first_item_selected === false) {              /** Keep track of the first item on the page for purposes of pagination**/
    first_item_selected = true;                     // set the flag
    first_visible_item = page_date;                 // keep track of this, it gets added to the [previous_visible_items] array if the next page button is clicked
  }

  $(box).clone().appendTo($(col));
  
  colHeight += $(box).height();                     // track how long this column is
  
  if (colHeight >= minColHeight || aca == true) {                /** Column is tall enough **/
    last_visible_item = $(col).find('li:last-child .page_date').html();
    completedCols++;                              // increase the completed column count
    colHeight = 0;                                // reset col height to force a new column to be made
    $(container).append($(col));                  // append the column to its container
    $wall.append($(container));                   // append the container to the wall
  }
  
  return new Array(colHeight, completedCols);     // return the required values
}

/** adds all items in given collection to columns on the wall **/
function addItems($collection) {
  var addColAnyway = false;
  $.each($collection, function(index, box){                       // loop the collection
    if (completedCols == cols) $(box).remove();                   // if all columns are displaying then remove the box from the page
    else {
      if (index == ($collection.length-1)) addColAnyway = true;
      else addColAnyway = false;
      
      var returned = addItem(box, colHeight, completedCols, addColAnyway);      // else add the box to the wall and update variables
      colHeight = returned[0]; completedCols = returned[1];
    }
  });
}
  
function syncBoxActiveStates() {

  //if (activeClasses.length == 0) return true;

  // reset everything
  $('.box-filters > ul.contains-filters > li > a').removeClass('active');
  $('#sub-nav.box-filters > ul.contains-filters > li').css('background-image', 'none');
  $wall.find('.box').not('.invis').toggleClass('invis');

  if (activeClasses.length == 0) {
    $wall.find('.box.invis').toggleClass('invis');
    $('#sub-nav.box-filters > ul.contains-filters > li > a.all').addClass('active');
    $('#sub-nav.box-filters > ul.contains-filters > li > a.all').parent().css('background-image', 'url(/images/nav-1.png)');
  }
  else {
    $.each(activeClasses, function(i, that) {
      $('.box-filters > ul.contains-filters > li > a.'+that).addClass('active');
      // show hidden boxes
      $wall.find('.'+that+'.invis').toggleClass('invis');
      if ($('#sub-nav.box-filters > ul.contains-filters > li a.'+that).length > 0) {
        var nav_image_pos = $('#sub-nav.box-filters > ul.contains-filters > li a.'+that).parent().index('#sub-nav.box-filters > ul.contains-filters > li');
        nav_image_pos += 1;
        $('#sub-nav.box-filters > ul.contains-filters > li a.'+that).parent().css('background-image', 'url(/images/nav-'+nav_image_pos+'.png)');
      }
    });
	}

}

/*** PAGINATION ***/
$(document).ready(function() {

  $('#less-boxes').click(function (e) {
    e.preventDefault();
    var $tmp = $('.box-parent-main').find('.col ul');
    $tmp.empty();
    $wall.empty();
    completedCols = 0;
    
    paramstr = 'ajax=1&getNewBoxes=1&number=1&dir=back&tags='+JSON.stringify(getActiveClasses());
    if (previous_visible_items.length > 0) {
      paramstr += '&datestamp='+previous_visible_items.pop();
    }
    $.post(
      'index.php',
      paramstr,
      function (r) {
        first_item_selected = false;
          if (previous_visible_items.length == 0) $('#less-boxes').hide();
        page_date = $(r).find('.page_date').html();
        $tmp.append(r);
        colHeightNeeded = ((minColHeight * cols) - $tmp.parent().height());
        persistentColHeightNeeded = colHeightNeeded;
        $('#loading-feature-content-bar').css('width', '0%');
        $('#loading-feature-content').show();
        
        xyzzy = 0;
        addExtraIfNeeded();
      },
      'html'
    );
  });

  $('#more-boxes').click(function (e) {
    e.preventDefault();
    var $tmp = $('.box-parent-main').find('.col ul');
    $tmp.empty();
    $wall.empty();
    completedCols = 0;
    
    paramstr = 'ajax=1&getNewBoxes=1&number=1&dir=forward&tags='+JSON.stringify(getActiveClasses());
    if (last_visible_item != '') {
      paramstr += '&datestamp='+last_visible_item;
    }
    $.post(
      'index.php',
      paramstr,
      function (r) {
        console.log(r);
        previous_visible_items.push(first_visible_item);
        $('#less-boxes').show();
        first_item_selected = false;
        page_date = $(r).find('.page_date').html();
        $tmp.append($(r));
        
        paramstr = 'ajax=1&getNewBoxes=1&number=1&dir=forward&tags='+JSON.stringify(getActiveClasses());
        if (page_date != '') {
          paramstr += '&datestamp='+page_date;
        }
        
        $.post(
          '/ajax/countPagesLeft.php',
          paramstr,
          function (s) {
            boxesNext = s;
            
            xyzzy = 0;
            if (s == 0) { console.log(s); $('#more-boxes').hide(); resizeCallback(); }
            else {
              colHeightNeeded = ((minColHeight * cols) - $tmp.parent().height());
              persistentColHeightNeeded = colHeightNeeded;
              $('#loading-feature-content-bar').css('width', '0%');
              $('#loading-feature-content').show();
              $('#more-boxes').show();
              addExtraIfNeeded();
            }
            
          },
          'html'
        );
        
      },
      'html'
    );
	});
	
});

function filteredBoxes() {
  
  var $tmp = $('.box-parent-main').find('.col ul');
  $tmp.empty();
  $wall.empty();
  completedCols = 0;
  
  previous_visible_items = new Array();
  first_item_selected = false;
  page_date = '';
  colHeightNeeded = (minColHeight * cols);
  persistentColHeightNeeded = colHeightNeeded;
  $('#loading-feature-content-bar').css('width', '0%');
  $('#loading-feature-content').show();
  xyzzy = 0;
  addExtraIfNeeded();
  
  /*
  paramstr = 'ajax=1&getNewBoxes=1&number=1&tags='+JSON.stringify(getActiveClasses());
  
  $.post(
    'index.php',
    paramstr,
    function (r) {
      previous_visible_items = new Array();
      first_item_selected = false;
      page_date = $(r).find('.page_date').html();
      $tmp.append($(r));
      colHeightNeeded = ((minColHeight * cols) - $tmp.parent().height());
      persistentColHeightNeeded = colHeightNeeded;
      $('#loading-feature-content-bar').css('width', '0%');
      $('#loading-feature-content').show();
      
      xyzzy = 0;
      addExtraIfNeeded();
    },
    'html'
  );*/
}

/*** FILTERS ***/
$(document).ready(function() {
  
  $('#sub-nav.box-filters > ul.contains-filters > li > a').click(function(e){
    if (!$(this).hasClass('active')) {
      
      $('#sub-nav.box-filters > ul.contains-filters > li > a').each(function (i, that) {
        
        $(that).removeClass('active');
        $(that).parent().css('background-image', 'none');

        var key = array_search($(that).attr('class'), activeClasses);
        if (key !== false) {
          activeClasses.splice(key, 1);
        }
      });
      
      var nav_image_pos = $(this).parent().index('#sub-nav.box-filters > ul.contains-filters > li');
      nav_image_pos += 1;
      $(this).parent().css('background-image', 'url(/images/nav-'+nav_image_pos+'.png)');
      activeClasses.push($(this).attr('class'));
    }
    else {
      $(this).parent().css('background-image', 'none');
    }
  });
  
  
  $.each(activeClasses, function(i, that) {
    $('#filters > ul#more-contains-filters > li > a.'+that).addClass('active');
  });
  
  $('.box-filters > ul.contains-filters > li > a').click(function(e){
    
  	e.preventDefault();
  
    $(this).toggleClass('active');
  
  	colorClass = 'all';
    var classes = $(this).attr('class');
    classes = classes.split(' ');
  
    for (var i = 0; i < classes.length; i++) {
      if (classes[i] != 'active') { colorClass = classes[i]; break }
    }
  
    var key = array_search (colorClass, activeClasses);
    if (!$(this).hasClass('active') && key !== false) {
      activeClasses.splice(key, 1);
    }
    else if ($(this).hasClass('active') && key === false){
      activeClasses.push(colorClass);
    }
  
  	if (activeClasses.length == 0) {
  	  colorClass = 'all';
  	}
  
    colorClass = '.' + colorClass;
  
    if(colorClass == '.all') {
      // everything is active, reset filters
      $('.box-filters > ul.contains-filters > li > a').removeClass('active');
      $('#sub-nav.box-filters > ul.contains-filters > li > a.all').parent().css('background-image', 'none');
      $('#sub-nav.box-filters > ul.contains-filters > li > a.all').addClass('active');
      $('#sub-nav.box-filters > ul.contains-filters > li > a.all').parent().css('background-image', 'url(/images/nav-1.png)');
  
  	  activeClasses = new Array();
  
      // show all hidden boxes
      $wall.find('.invis').toggleClass('invis');
    } else {
      $('#sub-nav.box-filters > ul.contains-filters > li > a.all').removeClass('active');
      $('#sub-nav.box-filters > ul.contains-filters > li > a.all').parent().css('background-image', 'none');
  
      // hide visible boxes
      $wall.find('.box').not('.invis').toggleClass('invis');
      // show hidden boxes
      $.each(activeClasses, function(index, classname) {
        $wall.find('.'+classname+'.invis').toggleClass('invis');
      });
    }
  
    last_visible_item = '';
    first_visible_item = '';
    first_item_selected = false;
    previous_visible_items = new Array();
    page_date = '';
    xyzzy=0;
    filteredBoxes();
    return false;
  });


  $('.save').click(function(e) {
    e.preventDefault();
    var tags = JSON.stringify(getActiveClasses());
    $.get('/ajax-cookie.php', 'tags='+tags);
    $('#morefilter').click();
  });
  
});
  
function getActiveClasses() {
  var returnClasses = new Array();
  $.each(activeClasses, function(i, that) {
    returnClasses.push(that.replace(/_/g, ' '));
  });
  return returnClasses;
}
