///////////////////////////////////////////////////////////////
//
//  Script: Random Projects for Associations
//  Version: 1.0
//
//  Notes: oo version with dynamic html output
//

  var Ascribe = Ascribe || {};

  Ascribe.RandomProjects = function (config) {
    // data and general configs
    this.projects = config.projects; // raw project data
    this.randomNumbers = []; // to hold our random/unique numbers
    this.totalProjects;
    this.projectsToDisplay = config.projectsToDisplay || 4;
    this.projectsOutput = '';
    this.randomizeProjects;

    // ids
    this.outputElementID = config.outputElementID || 'recent-projects-container';

    // methods
    this.getprojectsToDisplay = function () {
      var randNum;
      var found;
      for (var i=0; i<this.projectsToDisplay; i++) {
        found = false;
        randNum = Math.floor(Math.random() * this.totalProjects);
        for (var j=0; j<this.randomNumbers.length; j++) {
          if (this.randomNumbers[j] == randNum) {
            found = true;
            break;
          }
        }
        (found) ? i-- : this.randomNumbers.push(randNum); // keep repeating loop if found == true
      }
    };
    
    this.projectsHTMLOutput = config.projectsHTMLOutput || function (aProjects) {
      var projectsToDisplay = (this.randomizeProjects) ? this.projectsToDisplay : this.totalProjects;
      output = '<ul class="portfolio">';
      for (var k=0; k<projectsToDisplay; k++) {
        var x = (this.randomizeProjects) ? this.randomNumbers[k] : k;
        output += '<li><a href="' + aProjects[x].projectPath + '" title="View"><img src="' + aProjects[x].projectThumbnailPath + '" alt="' + aProjects[x].projectTitle + '" /></a><h3>' + aProjects[x].projectTitle + '</h3></li>';
      }
      output += '</ul><!-- #recent-projects -->';
      return output;
    };
    
    this.projects = this.filterProjects(this.projects);
    this.totalProjects = this.projects.length;
    this.randomizeProjects = (this.totalProjects > this.projectsToDisplay) ? true : false;
    if (this.randomizeProjects) {
      this.getprojectsToDisplay();
    }
    this.projectsOutput = this.projectsHTMLOutput(this.projects);
    $(this.outputElementID).update(this.projectsOutput);
  }; // constructor
  
  Ascribe.RandomProjects.prototype = {
    filterProjects: function (aProjects) {
    ///////////////////////////////////////////
    //  removes all items from the projects collection that have no marks or no images.
    //  returns new colection/array.
      aProjects.each(function (item) {
        if (item.projectMarks === 0 || item.projectSelectedPhotos === 0) {
          aProjects = aProjects.without(item);
        }
      });
      return aProjects;
    } // removeNoMarks()
  }; // prototype
