/* @author Russ Tennant (russ@i2rd.com)
* @require logger.js
*/

if(typeof AC != 'undefined') {
	log4js.logger.error("Redefining ArticleContainer library.");
}
AC = {};
AC.getElementsByTagName = function(tagName, start) {
    if(!start){start = document;} // All variables are in function scope.
    var elements = start.getElementsByTagName(tagName);
    if(!elements || elements.length === 0){
        elements = start.getElementsByTagName(tagName.toUpperCase());
	}
    return elements;
};
AC.countWords = function(text) {
	var count = 0;
	if(text) {
		var list = text.split(/\s+/);
		for(var h = 0; h < list.length; h++) {
			if(!(list[h] == '')) {
				count++;
			}
		}
	}
	//log4js.logger.info("Found " + count + " words in: " + text);
	return count;
};
AC.Article = function(li, wpm) {
	this.article = li;
	var text = "";
	
	var components = AC.getElementsByTagName("div", li);
	for(var el = null, idx = 0; (el = components[idx]); idx++) {
		var cn = el.className || "";
		if(cn.match(/article_heading/)
            || cn.match(/article_subheading/) 
            || cn.match(/article_teaser/)
            || cn.match(/article_post_time/)
            || cn.match(/article_link_read_more/)
            || cn.match(/article_byline/)
            || cn.match(/article_content/)
            ) {
			text = text + this.getText(el);
		} else if(cn != '') {
			log4js.logger.info("Unexpected component with classname: " + cn);
		}
	}
	this.wordCount = AC.countWords(text);
	// 100-200 WPM + acquire time
	wpm = wpm || 120.0;
	var t1 = (this.wordCount / wpm);
	t1 = Math.ceil(t1 * 60) * 1000; 
	this.minShowTime = t1 + 2000 /* Acquire Time */;
	//log4js.logger.info("ShowTime: " + this.minShowTime + " for " + li.id + ", wordcount = " + this.wordCount + ", WPM = " + wpm + ", t1 = " + t1);
};
AC.Article.prototype = {
	getRecommendedInterval : function() {
		return this.minShowTime;
	},
	show : function(cb) {
		var opacity = this.getOpacity();
		if(this.article.style.display != 'block') {
            opacity = 0.0;
            this.setOpacity(opacity);
			this.article.style.display = 'block';
		}
		if(opacity > 0.9) {
            if(cb){cb.apply(this);}
		} else {
			opacity = opacity + 0.1;
			//log4js.logger.info("SHOW: Opacity is " + opacity);
			this.setOpacity(opacity);
			if(parseInt(opacity * 100) != parseInt(this.getOpacity() * 100)) {
				if(cb){cb.apply(this);}
			}
            else
			    window.setTimeout(i2rd.bind(this.show, this, cb), 100);
		}
	},
	hide : function(cb) {
		var opacity = this.getOpacity();
		if(opacity < 0.1) {
            if(cb){cb.apply(this);}
		} else {
			opacity = opacity - 0.1;
			//log4js.logger.info("HIDE: Opacity is " + opacity);
			this.setOpacity(opacity);
			if(parseInt(opacity * 100) != parseInt(this.getOpacity() * 100)) { // Check if we are spinning our wheels
				if(cb){cb.apply(this);}
			}
            else
			    window.setTimeout(i2rd.bind(this.hide, this, cb), 100);
		}
	},
	getText : function(el) {
		if(!el){return el;}
		if (typeof el == "string"){return el;}
		var str = "", children = el.childNodes;
		var cn, i;
		for	(i = 0; (cn = children[i]); i++) {
			switch (cn.nodeType) {
				case 1:
					str += this.getText(cn);
					break;
				case 3:
					if(cn.nodeValue) {
						str += cn.nodeValue;
					} else if(str.length > 0 && str[str.length - 1] != "") {
						str += " ";
					}
					break;
			}
		}
		return str;
	},
	setOpacity : function(value) {
        if (value >= 1) {
          value = (/Gecko/.test(navigator.userAgent) &&
            !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ? 0.999999 : 1.0;
          if(/MSIE/.test(navigator.userAgent) && !window.opera) {
            this.article.style.filter = this.article.style.filter.replace(/alpha\([^\)]*\)/gi,'');
          }
        } else {
          if(value < 0.00001) value = 0;
          if(/MSIE/.test(navigator.userAgent) && !window.opera) {
            this.article.style.filter = this.article.style.filter.replace(/alpha\([^\)]*\)/gi,'') +
              'alpha(opacity='+ parseInt(value * 100) +')';
           }
        }
        this.article.style.opacity = value;
	},
	getOpacity : function() {
		var value = this.article.style.opacity;
        if(this.article.style.filter) {
            value=/alpha\(opacity=([^\)]+)\)/gi.exec((this.article.style.filter||''));
            if(value && value[1]) {value=parseFloat(value[1]) / 100.0;}
        }	
		if(value) return parseFloat(value);
		return  this.article.style.filter ? 100 : 1.0;
	}
};

AC.RotatingHeadline = function(ol) {
	this.container = ol;
    var articleContainer = ol.parentNode;
    while (articleContainer && 
        (articleContainer.className || "").toLowerCase().indexOf('articlecontainer') == -1) {
        articleContainer = articleContainer.parentNode;
    }
    if(!articleContainer) {
        log4js.logger.error("Unable to find article container.");
        return;
    }
    var article, idx, el, lis = AC.getElementsByTagName("var", articleContainer), wpm = 95.0;
    for (el = null, idx = 0; (el = lis[idx]); idx++) {
        if (el.className == "wpm") {wpm = parseFloat(el.innerHTML+"");}
    }    
	this.containerId = articleContainer.id;
	this.articles = [];
	this.paused = false;
	lis = AC.getElementsByTagName("li", ol);
    if(lis.length <= 1) {return;}
	for(el = null, idx = 0; (el = lis[idx]); idx++) {
		article = new AC.Article(el, wpm);
		this.articles[this.articles.length] = article;
		article.article.style.display = 'none';
	}

	this.currentIdx = 0;
	i2rd.addEvent(ol, "mouseover", i2rd.bind(this.pause, this));
	i2rd.addEvent(ol, "mouseout", i2rd.bind(this.start, this));
	
	var startIdx = 0;
	if(this.containerId) {
		var articleId = i2rd.getCookie(this.containerId + "-la");
		for(var el = null, idx = 0; (el = lis[idx]); idx++) {
			var article = this.articles[idx];
			if(article.article.id == articleId) {
				startIdx = idx;
				break;
			}
		}
	}
	this.currentArticle = this.articles[startIdx];
	this.currentIdx = startIdx;
	this.currentArticle.show();
	//log4js.logger.info("Showing next article in " + this.currentArticle.getRecommendedInterval());
	window.setTimeout(i2rd.bind(this.showNextArticle, this), 
			this.currentArticle.getRecommendedInterval());
};
AC.RotatingHeadline.prototype = {
	pause : function() {
		this.paused = true;
	},
	start : function() {
		this.paused = false;
	},
	showNextArticle : function() {
		if(this.paused) {
			window.setTimeout(i2rd.bind(this.showNextArticle, this), 750);
			return;
		}
		this.prevArticle = null;
		this.currentIdx++;
		if(this.currentIdx >= this.articles.length) this.currentIdx = 0;
		if(this.currentIdx == 0) this.prevArticle = this.articles[this.articles.length - 1];
		else this.prevArticle = this.articles[this.currentIdx - 1];
		this.currentArticle = this.articles[this.currentIdx];
		//log4js.logger.info("showNextArticle. current = " + this.currentArticle.article.id 
		//	+ ", prev = " + this.prevArticle.article.id);
		this.prevArticle.hide(i2rd.bind(this.showNext, this));
		
		if(this.containerId) {
			var time = new Date();
			time.setHours(time.getHours() + 48);
			i2rd.setCookie(this.containerId + "-la", this.currentArticle.article.id, time);
		}
	},
	showNext : function(nextFunc) {
        if(this.prevArticle)
            this.prevArticle.article.style.display = 'none';
		this.currentArticle.show(i2rd.bind(this.startTimer, this));
	},
	startTimer : function() {
		window.setTimeout(i2rd.bind(this.showNextArticle, this), 
			this.currentArticle.getRecommendedInterval());
	}
};

AC.init = function(evt) {
  // Find ac_style_stock_ticker
  var lists = AC.getElementsByTagName("ol");
  for(var el = null, idx = 0; (el = lists[idx]); idx++) {
  	var cn = el.className || "";
  	if(cn.match(/ac_style_rotating_headline/)) {
  		new AC.RotatingHeadline(el);
  	}
  }
};

i2rd.addEvent(window, 'load', AC.init);
