var ResultBrowser = Class.create({
  initialize : function(webservice, category, sorting, resultsPerPage, thumbnailSize, options) {
    this.webservice = webservice;
    this.category = category;

    this.config = {
      sorting : sorting,
      resultsPerPage : resultsPerPage,
      thumbnailSize : thumbnailSize,
      page : 1
    };

    if(Object.isArray(options.parameters))
      this.parameters = options.parameters;

    if(!Object.isUndefined(options.onStartBrowse))
      this.onStartBrowse = options.onStartBrowse;

    if(!Object.isUndefined(options.onBrowseComplete))
      this.onBrowseComplete = options.onBrowseComplete;

    if(!Object.isUndefined(options.delay))
      this.delay = options.delay;

    this.browse();
  },

  setSorting : function(value) {
    this.config.sorting = value;
    this.config.page = 1;
    this.browse();
  },

  setResultsPerPage : function(value) {
    this.config.resultsPerPage = value;
    this.config.page = 1;
    this.browse();
  },

  setThumbnailSize : function(value) {
    this.config.thumbnailSize = value;
    this.browse();
  },

  previousPage : function() {
    if(this.info.currentPage == 1)
      return;
    this.config.page--;
    this.browse();
  },

  nextPage : function() {
    if(this.info.currentPage == Math.ceil(this.info.totalResults / this.info.resultsPerPage))
      return;
    this.config.page++;
    this.browse();
  },

  browse : function() {
    this.onStartBrowse();
    if(!Object.isUndefined(this.delay))
      this.doBrowse.delay(this.delay, this);
    else
      this.doBrowse();
  },

  doBrowse : function(self) {
    if(Object.isUndefined(self))
      self = this;

    var url = self.webservice + '/' + self.category + '/' + self.config.sorting + '/' + self.config.resultsPerPage + '/' + self.config.thumbnailSize + '/' + self.config.page;
    for(var i = 0; i < self.parameters.length; i++) {
      url += '/' + self.parameters[i];
    }

    new Ajax.Request(url, {
      method : 'get',
      evalJSON : true,
      onSuccess : function(transport) {
        var response = transport.responseJSON;
        self.content = response.content;
        self.info = {
          totalResults : parseInt(response.info.totalResults),
          resultsPerPage : parseInt(response.info.resultsPerPage),
          currentPage : parseInt(response.info.currentPage),
          thumbnailSize : response.info.thumbnailSize,
          sorting : response.info.sorting
        };
        self.onBrowseComplete();
      }
    });
  }
});
