(function($){
  
  var cachedSections = {};
  var cachedAllItems = {};
  
  var first = function(array, where){
    for(var i=0; i<array.length; i++){
      if(where(array[i])) return array[i];
    }
  };
  
  var trimEnd = function(string, char){
    while(string.length > 0 && (string.lastIndexOf(char) + 1) == string.length){ 
      string = string.substr(0, string.lastIndexOf(char));
    }
    return string;
  };
    
  function padNumber(number, to){
    var string = number.toString();
    while(string.length < to) string = "0" + string;
    return string; 
  }

  function loadId(path, callback){
    if(cachedSections[path]){
      callback(cachedSections[path]);
      return;
    }
    window.pixelsilk2.getAllSections(function(home){
      var findSection = function(section, find){
        if(trimEnd(section.urlRelative.toLowerCase(), "/") == trimEnd(find.toLowerCase(), "/")) 
          return section;
        for(var i=0; i<section.children.length; i++){
          var innerSection = findSection(section.children[i], find);
          if(innerSection) return innerSection;
        }
      };
      var section = findSection(home, path);
      if(section){
        cachedSections[path] = section.id;
        callback(section.id);
      }
    });
  }
  
  var getAllItems = function(path, callback){
    if(false && cachedAllItems[path]){
      callback(cachedAllItems[path]);
      return;
    }
    window.pixelsilk2.getListItems({sorts: [], filters: [], filterrel: "", pagesize: 9999, page: 1, path: path}, function(items){
      cachedAllItems[path] = items;
      callback(items);
    });
  };
 
  window.pixelsilk2.addListItem = function(input, callback){
    var options = $.extend({}, {path: "/", data: {}, sectionId: null}, input);
   
    var doPost = function(id){
      postUrl += "EditListItem.aspx?action=add&update=true&sectionId=" + id;
      $.post(postUrl, options.data, callback);
    };
    if(options.sectionId){
      doPost(options.sectionId);
    }else{
      loadId(options.path, doPost);
    }
  }
    
  window.pixelsilk2.editListItem = function(input, callback){
    var path = input.path;
    var data = input.data;
    var strippedPath = path.substr(0, path.lastIndexOf("/"));
    var itemPath = path.substr(path.lastIndexOf("/") + 1);

    getAllItems(strippedPath, function(items){
      var desiredItem = first(items, function(x){return x.PagePath == itemPath;});
      if(!desiredItem){
        if(window.console) console.log("Unable to find the list item with the path " + itemPath + ", maybe you used the section path instead?");
        return;
      }
      
      var postUrl = strippedPath + "/EditListItem.aspx?action=edit&update=true&itemId=" + desiredItem.id + "&sectionId=";
      
      loadId(strippedPath, function(id){
        postUrl += id;
        var clone = $.extend({}, desiredItem, data);

        var toDelete = ["ItemPageURL","id","seriesId"]
        for(var i=0; i<toDelete.length; i++) 
          delete clone[toDelete[i]];

        for(var key in clone){
          if(key.indexOf("Date") == -1) continue;
          var date = new Date(parseInt(clone[key].substr(6)));
          clone[key] = padNumber(date.getMonth() + 1, 2) + "/" + padNumber(date.getDate(), 2) + "/" + date.getFullYear();
          clone[key + "Yes"] = false;
        }
        $.post(postUrl, clone, callback);
      });
      
    });
  };

})(jQuery);
