/**
 * CSHA Search Classes
 * Author: Eihab Ibrahim
 * © 2008 Wallrich Landi Inc.
 */

/**
 * Controller class
 * Responsible of keeping track of all issues
 * and issuing search and render commands
 */
var csha_controller = function() {
  this.loadingIcon = 'loadimg'; // Where's our loading icon?
  this.ref = 'rs_div';          // Where to render our output?
  this.catRef = 'srch_cats_a';    // Where should we render the categories? (column a)
  this.catRef2 = 'srch_cats_b';    // Where should we render the categories? (column b)
  this.catBox = 'rs_catFilter';
  this.highlight = true;       // Highlight search keywords in titles?
  this.autoShow = true;         // Automatically filter by category when clicked
  this.regex = '';
  this.issues = new Array();
  this.categories = new Array();
  this.cat = new Array(); // Selected categories
  this.status = 'rs_status';
  this.status = document.getElementById(this.status);
  this.rendered = false;
  /**
   * Show a specific category
   *
   * @param cat[] string     Array of category IDs to show
   */
  this.show = function() {
	for (var i=0; i<this.issues.length; i++)
		this.issues[i].show(this.cat);
	this.render();
  };
  
  /**
   * Search titles
   *
   * @param keywords string  Search string 
   */
  this.search = function(keywords) {
    this.isLoading(true);
    if (!keywords) keywords = '';
    this.regex = keywords;
    this.isLoading(true);
    if (keywords[0] != '"') {
      keywords = keywords.replace(/\s+/,'|');
    } else { // Exact match
      
    }
    
    var re = new RegExp(keywords, 'gi');
    for (var i=0; i<this.issues.length; i++) {
	  this.issues[i].search(re);
	}
	this.render();
  };
  
  /**
   * Render output
   */
  this.render = function() {
    this.isLoading(true);
    this.status.innerHTML = '';
    var count = 0;
    for (var i=0; i<this.issues.length; i++) {
      if (!this.issues[i].id) this.issues[i].id = 'is_'+i;
      count += this.issues[i].render(this.ref, this.highlight, this.regex);
	}
	if (this.rendered) {
		if (count > 0) {
		this.status.innerHTML = 'Found '+count+' issues.';
		} else {
		this.status.innerHTML = 'No articles found, please modify your search keywords and/or filters.';
		}
	}
	if (!this.rendered) {
	  // Render categories selection boxes
	  if (this.categories && this.categories.length>0) {
		var col_cut = (this.categories.length%2==0)?this.categories.length:this.categories.length+1;
		col_cut /= 2;
		var c_ref = this.catRef;
		for (var i=0; i<this.categories.length; i++) {
			if (i==col_cut) c_ref = this.catRef2;
			this.categories[i].render(c_ref);
		}
	  }
	  if (document.getElementById(this.catBox))
		document.getElementById(this.catBox).style.display = '';
	}
	this.rendered = true;
	this.isLoading(false);
  };
  
  /**
   * Show loading status
   */
  this.isLoading = function(loadStatus) {
    var l = document.getElementById(this.loadingIcon);
    var rs = document.getElementById(this.ref);
    l.style.display = (loadStatus)?'':'none';
    rs.style.display = (loadStatus)?'none':'';
  };
  
  /**
   * Set Category Toggle
   *
   * @param string cid   Category ID
   * @param bool add     Add specified category to filter
   */
  this.setCat = function(cid, add) {
	if (!add) {
	  for (var i=0; i<this.cat.length; i++) {
	    if (this.cat[i] == cid) {
	      this.cat.splice(i,1);
	      break;
	    }
	  }
	} else {
	  this.cat.push(cid);
	}
	if (this.autoShow) this.show();
  };
}

/**
 * Issue class
 * Data class representing an Issue and its articles
 */
var csha_issue = function(title, pdfName, pdfLink) {
  this.id = 0;           // Pointer to target div
  this.rendered = false; // Were we rendered before?
  this.title = title;       // Issue Title (e.g. Spring 2008)
  this.pdfName = pdfName;     // Issue PDF Name (e.g. Volume XXVI, Issue 2)
  this.pdfLink = pdfLink;     // Link to the PDF file
  this.articles = new Array();
  this.baseHref = "/publications/getFile.aspx?file=";     // PDF Files location
  this.render = function (ref, highlight, regex) {
    if (!this.rendered) {
		var h = document.createElement('H1');
		h.className = 'issue_title';
		h.innerHTML = this.title;
	    
		var h2 = document.createElement('H1');
		h2.className = 'pdf_title';
	    
	    if (this.pdfLink && this.pdfLink.length > 0) {
			var a = document.createElement('A');
			a.href = this.baseHref+this.pdfLink;
			a.target = '_blank';
			a.innerHTML = this.pdfName;
	    } else {
			var a = document.createElement('P');
			a.innerHTML = this.pdfName;
	    }
		h2.appendChild(a);
	    
		var d = document.createElement('DIV');
		d.id = this.id;
		d.appendChild(h);
		d.appendChild(h2);
		document.getElementById(ref).appendChild(d);
    } else {
        // Check if we have at least 1 article matching
        var ws = false;
        for (var i=0; i<this.articles.length; i++) {
          if(this.articles[i].willShow) {
            ws = true;
            break;
          }
        }
        if (!ws) {
          document.getElementById(this.id).style.display = 'none';
          return 0;
        } else {
          document.getElementById(this.id).style.display = '';
        }
    }

    var l_ref = false;
    for (var i=0; i<this.articles.length; i++) {
      if (this.articles[i].type != 'Feature Article'
          && this.articles[i].type != l_ref 
          && !this.rendered) {
          l_ref = this.articles[i].type;
          var h2 = document.createElement('h2');
          h2.className = 'catType';
          h2.innerHTML  = l_ref;
          document.getElementById(this.id).appendChild(h2);
      } else if (this.articles[i].type == 'Feature Article'
				 && !this.rendered) {
		var h2 = document.createElement('h2');
          h2.className = 'catType';
          h2.innerHTML  = 'Feature Article';
          document.getElementById(this.id).appendChild(h2);
      }
      if (!this.rendered) this.articles[i].id = this.id+'_'+i;
      this.articles[i].render(this.id, highlight, regex);
    }
    if (this.rendered)
      this.cleanTitles();
    this.rendered = true;
    return 1;
  };
  
  this.search = function(regex) {
    for (var i=0; i<this.articles.length; i++)
      this.articles[i].search(regex);
  }
  
  this.show = function(cat) {
	for (var i=0; i<this.articles.length; i++)
		this.articles[i].show(cat);
  };
  
  this.cleanTitles = function() {
    var children = document.getElementById(this.id).childNodes;
    for (var i=0; i<children.length; i++) {
      if (children[i].tagName == 'H2') {
		var p = children[i];
		var hide = true;
		i++;
		while (children[i] && children[i].tagName != 'H2') {
		  if (children[i].style.display != 'none')
			hide = false;
		  i++;
		}
		i--;
		p.style.display = (hide)?'none':'';
      }
    }
  };
}


/**
 * Article class
 * Data class representing an article
 */
var csha_article = function(title,by,cats,type) {
  this.id = 0;             // Pointer to target div
  this.rendered = false;   // Were we rendered before?
  this.title = title;         // Article title
  this.author = by;            // Article Author(s)
  this.type = type;       // Article Type
  this.cats = (cats)?cats:new Array(); // Category IDs we belong to
  this.searchShow = true;  // Do we match keywords?
  this.catShow = true;     // Do we match categories?
  this.willShow = (this.searchShow && this.catShow);
  this.highlight = false;  // Highlight text?
  if (!this.type) this.type = 'Feature Article';
  this.render = function (ref, highlight, regex) {
    // Don't waste cycles
    if (this.rendered) {
	  this.showHide();
	  if (this.highlight == highlight)
		return;
    }
	  var d = document.createElement('DIV');
	  d.id = this.id;
	  d.className = 'article';
	  var p = document.createElement('p');
	  p.innerHTML = (highlight)?this.highlight(this.title,regex):this.title;
	  d.appendChild(p);
	  if (this.author && this.author.length > 0) {
	    var p2 = document.createElement('p');
	    p2.className = 'author';
	    p2.innerHTML = this.author;
	    d.appendChild(p2);
	  }
	  if (!this.rendered) {
		document.getElementById(ref).appendChild(d);
	    this.rendered = true;
	  } else {
	    document.getElementById(ref).replaceChild(d,document.getElementById(this.id));
	    this.showHide();
	  }
  };
  
  this.showHide = function() {
    if (this.willShow) {
	  document.getElementById(this.id).style.display = '';
	} else {
	  document.getElementById(this.id).style.display = 'none';
	}
  };
  
  this.highlight = function (title, regex) {
	if (!regex || regex.length < 1) return title;
	while (regex.indexOf(' ')>-1) regex = regex.replace(' ','|');
	regex = new RegExp('('+regex+')','i');
	title = title.split(' ');
	if (title && title.length) {
	  ft = '';
	  for (var i=0; i<title.length; i++) {
	    if (!title[i].length || title[i].length<1) continue;
	    if (regex.exec(title[i])) {
	      ft += '<span class="srch_match">'+title[i]+'</span> ';
	    } else {
	      ft += title[i]+' ';
	    }
	  }
	} else {
	  ft = title;
	}
	return ft;
  }
  
  this.search = function (regex) {
      this.searchShow = this.title.match(regex);
      this.updateShowStatus();
  }
  
  this.show = function(cat) {
	this.catShow = false;
	for (var i=0; i<this.cats.length; i++) {
	  
	  for (j=0; j<cat.length; j++) {
	    if (this.cats[i] == cat[j]) {
  	      this.catShow = true;
  	      this.updateShowStatus();
	      break;
	    }
	    if (this.catShow) break;
	  }
	}
	
	if (cat.length < 1) this.catShow = true;
	this.updateShowStatus();
  };
  
  this.updateShowStatus = function() {
	this.willShow = (this.searchShow && this.catShow);
  }
}

var csha_category = function(title, id) {
  this.id = id;
  this.title = title;
  this.render = function(ref) {
    var d=document.createElement('div');
    var c = 'cat'+this.id;
    d.innerHTML = '<input type="checkbox" name="'+c+'" value="'+c+'" id="'+c+'" onclick="c.setCat('+this.id+',this.checked);"/> '+
	'<label for="'+c+'">'+this.title+'</label>';
	document.getElementById(ref).appendChild(d);
  };
}