// Array to hold the current status views
var categoryViews = new Array();

function populateCategoryViews() {
  categoryViews = Array(); // reset category views

  var images = $("div.category img");
  images.each(function(i,c){
    if(c.src.toString().indexOf('tree_open.gif')!=-1) {
      categoryViews[categoryViews.length] = c.parentNode.parentNode.id;
    }
  });
}

function populateCategoryViewsFromCookie() {
  var arr = new Array();
  var str = $.cookie('categoryViews');
  
  jQuery.each(str.split(','), function(i,c){
    categoryViews[categoryViews.length] = c;
  });
}

function setCategoryViewCookie() {
  var str = "";

  jQuery.each(categoryViews, function(i,c){
    str += (c.replace('category_', '')+',');
  });
 
  $.cookie('categoryViews', str, {'path':'/'});
}

function toggleCategoryTree(id) {
  var img = $("div#category_"+id+" img")[0];
  
  // Make sure the categoryView array is populated before we begin
  if(categoryViews.length==0){ populateCategoryViews(); }

  // Image urls
  var tree_open = 'http://media.snipesoft.net.nz/images/tree_open.gif';
  var tree_close = 'http://media.snipesoft.net.nz/images/tree_close.gif';

  // Get the child section
  var children = $('div#category_section_'+id);

  // If the tree is currently open, close it
  if(img.src.toString().indexOf('tree_close.gif')!=-1) {
    children.hide();
    img.src = tree_open;
  } else if(img.src.toString().indexOf('tree_open.gif')!=-1) {
    children.show();
    img.src = tree_close;
  }

  populateCategoryViews();
  setCategoryViewCookie();
}

function hideCategoryChildren(parent) {
  // Find the children
  var children = $("li[parent="+parent+"]");
  
  // Recursively look for any grandchildren, etc to hide also.
  children.each(function(i, c){
    hideCategoryChildren(c.id);
  });
  
  // Then hide the children.
  children.hide();
}

function showCategoryChildren(parent) {
  // Find the children
  var children = $("li[parent="+parent+"]");
  
  // Recursively look for any grandchildren, etc to hide also.
  children.each(function(i, c){
    if(categoryViews[c.id]==1) {
      showCategoryChildren(c.id);
    }
  });
  
  // Then hide the children.
  children.show();
}
