/**
 * Author: NoICE
 * License: MIT
 */

// TODO supports only one item now,
// if you supply more (or selector that selects more than one item)
// it would overwrite contents of all of them by the first one...
function Upcaser(selector) {
  // text taken from the selector
  this.sel = $(selector);
//  var self = this;
//  this.sel.upcaser = self;
//  this.sel.each(function () { this.upcaser = self; console.log('applying upcaser to'); console.log(this.upcaser); });
  // currently set text
  // position
  this.i = 0;
  this.elindex = 0;
  this.inter = 0;
  this.timer = 75;
  this.timer_round = 3000;
  this.tag = 'span';
  this.tag_class = 'upcaser-highlight';
  this.loop = false;
  // let's showoff
  this.start();
};

Upcaser.prototype.start = function() {
  self = this;
  self.process();
  self.inter = setInterval(function () { self.process(); }, this.timer);
};

Upcaser.prototype.stop = function () {
  clearInterval(this.inter);
};

Upcaser.prototype.current_element = function () {
  return $($(this.sel)[this.elindex]);
};

Upcaser.prototype.decorate = function () {
  var t = this.current_element().text();
  // ignore the ones that don't match
  if(this.i > t.length) {
    this.cur = t;
  } else {
    var current = t.substring(this.i, this.i + 1);
    var pre = t.substring(0, this.i - 1);
    if(this.i > 0) {
      var pre2 = t.substring(this.i-1, this.i);
    } else {
      var pre2 = '';
    }
    var post = t.substring(this.i + 1, t.length);
    pre2 = '<' + this.tag + ' class="' + this.tag_class + '2">' + pre2 + '</' + this.tag + '>';
    current = '<' + this.tag + ' class="' + this.tag_class + '">' + current + '</' + this.tag + '>';
    this.cur = pre + pre2 + current + post;
  }
};

Upcaser.prototype.process = function () {
  this.decorate();
  
  this.apply();
  
  // move pointer to current char
  this.i++;
  
  if(this.i > this.current_element().text().length) {
    this.i = 0;
    this.elindex++;
    if(this.elindex >= $(this.sel).length) {
      this.elindex = 0;
      // stop right there
      this.stop();
      var self = this;
      // and set the timeout for the next round
      if(this.loop) setTimeout(function () { self.start(); }, this.timer_round);
    }
  }
};

Upcaser.prototype.apply = function () {
  //console.log(this.current_element());
  this.current_element().html(this.cur);
};

