var carousel;
var baseArticleLink;
var baseRelatedImageLink;
var defaultRelatedImageLink;
var newsImageWidth;
var headlines = new Array();
var headlinesCategory;
var headlinesCount;
var mouseoverTimer = null;
var animationPaused = false;
var animationStopped = false;
var rotateInterval = 5000;
var updateInterval;
var maxUpdates = -1;
var updateIntervalTimer;

function Headline(title, subtitle, summary, product, page, riCategory, riSymbolicName, riCaption, timestamp) {
	this.title = title;
	this.subtitle = subtitle;
	this.summary = summary;
	this.product = product;
	this.page = page;
	this.riCategory = riCategory;
	this.riSymbolicName = riSymbolicName;
	this.riCaption = riCaption;
	this.timestamp = timestamp;
}

function addHeadline(title, subtitle, summary, product, page, riCategory, riSymbolicName, riCaption, timestamp) {
	var headline = new Headline(title, subtitle, summary, product, page, riCategory, riSymbolicName, riCaption, timestamp);
	headlines[headlines.length] = headline;
}

// Build the article: image, title, subtitle, timestamp, summary
function buildArticle(index) {
	var headline = headlines[index];
	var page = new Array();
	page.push('<div id="news_top_headlines_article" style="width: ' + newsImageWidth + 'px;">');
	var articleLink = buildArticleLink(headline);
	page.push('<a href="');
	page.push(articleLink);
	page.push('">');
	page.push('<img src="');
	page.push(buildRelatedImageLink(headline));
	page.push('" border="0"');
	page.push(' onclick="javascript: document.location=\'');
	page.push(articleLink);
	page.push('\'"');
	if ( (headline.riCaption != null) && (headline.riCaption.length > 0) ) {
		page.push(' title="');
		page.push(headline.riCaption);
		page.push('"');
	}
	page.push(' border="0" />');
	page.push('</a>');
	page.push('<div class="title">');
	page.push(headline.title);
	page.push('</div>');
	page.push('<div class="subtitle"><a href="');
	var articleLink = buildArticleLink(headline);
	page.push(articleLink);
	page.push('">');
	page.push(headline.subtitle);
	page.push('</a>');
	page.push('</div>');
	if ( (headline.timestamp != null) && (headline.timestamp.length > 0) ) {
		page.push('<div class="datetime">');
		page.push(headline.timestamp);
		page.push('</div>');
	}
	page.push('<div class="summary">');
	page.push(headline.summary);
	page.push('</div>');
	page.push('</div>');
	return page.join("");
}

function buildHeadlines() {
	var tbl = document.getElementById("headlines");
	var inner = new Array();
	for (var i = 0; i < headlines.length; i++) {
		inner.push(buildHeadlineRow(i));
	}
	tbl.innerHTML = inner.join("");
}
function clearHeadlines() {
	var el = document.getElementById("headlines");
	var n = el.childNodes.length - 1;
	for (var i = n; i >= 0; i--) {
		el.removeChild(el.childNodes[i]);
	}
}

// Build a row for the list of headlines
function buildHeadlineRow(index) {
	var headline = headlines[index];
	var result = new Array();
	result.push('<span onmouseover="stopAnimation(); mouseoverTimer=setTimeout(\'changePage(');
	result.push("" + (index + 1));
	result.push(')\', 500);" ');
	result.push('onmouseout="clearTimeout(mouseoverTimer); resumeAnimation();">');
	result.push("<dt");
	if (index == 0) {
		result.push(" class='current'");
	}
	result.push(" id='headline_row_dt_");
	result.push("" + index);
	result.push("'>");
	result.push(headline.title);
	result.push("</dt>");
	result.push("<dd");
	if (index == 0) {
		result.push(" class='current'");
	}
	result.push(" id='headline_row_dd_");
	result.push("" + index);
	result.push("'>");
	var articleLink = buildArticleLink(headline);
	result.push("<a href='");
	result.push(articleLink);
	result.push("'>");
	result.push(headline.subtitle);
	result.push("</a></dd>");
	result.push("</span>");
	return result.join("");
}

function buildArticleLink(headline) {
	var result = new Array();
	result.push(baseArticleLink);
	result.push("&product=");
	result.push(headline.product);
	result.push("&vendorReference=");
	result.push(headline.page);
	return result.join("");
}
function buildRelatedImageLink(headline) {
	var result = new Array();
	var riCategory = headline.riCategory;
	if ( (riCategory != null) && (riCategory.length > 0) ) {
		result.push(baseRelatedImageLink);
		result.push("&category=");
		result.push(headline.riCategory);
		result.push("&symbolicName=");
		result.push(headline.riSymbolicName);
	}
	else {
		result.push(defaultRelatedImageLink);
	}
	return result.join("");
}

/**
 * Custom inital load handler. Called when the carousel loads the initial
 * set of data items. Specified to the carousel as the configuration
 * parameter: loadInitHandler
 **/
var loadInitialItems = function(type, args) {
	var start = 1;
	var last = headlines.length;
	var alreadyCached = args[2];

	load(this, start, last);
};

/**
 * Custom load next handler. Called when the carousel loads the next
 * set of data items. Specified to the carousel as the configuration
 * parameter: loadNextHandler
 **/
var loadNextItems = function(type, args) {

	var start = args[0];
	var last = args[1];
	var alreadyCached = args[2];

	if(!alreadyCached) {
		load(this, start, last);
	}
};

/**
 * Custom load previous handler. Called when the carousel loads the previous
 * set of data items. Specified to the carousel as the configuration
 * parameter: loadPrevHandler
 **/
var loadPrevItems = function(type, args) {
	var start = args[0];
	var last = args[1];
	var alreadyCached = args[2];

	if(!alreadyCached) {
		load(this, start, last);
	}
};

var load = function(carousel, start, last) {
	for(var i=start;i<=last;i++) {
		carousel.addItem(i, buildArticle(i-1));
	}
	buildHeadlines();
};

function changePage(pageNum) {
	carousel.moveTo(pageNum);
}

var animComplete = function(type, args) {
	var direction = args[0]; // string either: 'next' or 'prev'

	setCurrentArticle();
	if ( (!animationPaused) && (!animationStopped) && (!carousel.isAutoPlayEnabled()) ) {
		// If we got here, the user clicked prev or next, so we must re-enable
		// auto play
		carousel.startAutoPlay();
	}
};

function setCurrentArticle() {
	var index = carousel.getProperty("firstVisible");
	index -= 1;
	var el1, el2;
	for (var i = 0; i < headlines.length; i++) {
		el1 = document.getElementById("headline_row_dt_" + i);
		el2 = document.getElementById("headline_row_dd_" + i);
		if (i == index) {
			el1.className = "current";
			el2.className = "current";
		}
		else {
			el1.className = "";
			el2.className = "";
		}
	}
}
function pauseAnimation(pauseControl) {
	if (animationStopped) {
		return;
	}

	if (!animationPaused) {
		stopUpdates();
		carousel.stopAutoPlay();
		animationPaused = true;
		pauseControl.title = "Resume Animation";
	}
	else {
		carousel.startAutoPlay();
		startUpdates();
		animationPaused = false;
		pauseControl.title = "Pause Animation";
	}
}

function pauseOver(pauseButton) {
	if (!animationPaused) {
		pauseButton.src = jsContextPath + "/images/common/layout/v4/controls/pause_over.gif";
	}
	else {
		pauseButton.src = jsContextPath + "/images/common/layout/v4/controls/pause.gif";
	}
}

function pauseOut(pauseButton) {
	if (!animationPaused) {
		pauseButton.src = jsContextPath + "/images/common/layout/v4/controls/pause.gif";
	}
	else {
		pauseButton.src = jsContextPath + "/images/common/layout/v4/controls/pause_over.gif";
	}
}

function stopAnimation() {
	if (animationPaused) {
		return;
	}

	if (!animationStopped) {
		carousel.stopAutoPlay();
		animationStopped = true;
	}
}
function resumeAnimation() {
	if (animationPaused) {
		return;
	}

	if (animationStopped) {
		carousel.startAutoPlay();
		animationStopped = false;
	}
}

/**
 * You must create the carousel after the page is loaded since it is
 * dependent on an HTML element (in this case 'news-carousel'.)
 **/

var pageLoad = function() {
	carousel = new YAHOO.extension.Carousel("news-carousel",
		{
			numVisible:        1,
			animationSpeed:    0.4,
			scrollInc:         1,
			size:              headlines.length,
			navMargin:         0,
			autoPlay:          rotateInterval,
			loadInitHandler:   loadInitialItems,
			animationCompleteHandler: animComplete,
			animationMethod: YAHOO.util.Easing.easeNone,
			prevElement:"prev-arrow",
			nextElement:"next-arrow",
			wrap: true,
			wrapMove: true
		}
	);
	startUpdates();
};

function startUpdates() {
	if (maxUpdates >= 0) {
		updateIntervalTimer = setInterval("getHeadlines('" + headlinesCategory + "', '" + headlinesCount + "')", updateInterval);
	}
}
function stopUpdates() {
	clearInterval(updateIntervalTimer);
}
function getHeadlines(category, count) {
	var ts=new Date();
	var path = jsContextPath+
		"/view/news/topHeadlinesUpdate.do?updateHeadlines=true" +
		"&category=" + category +
		"&count=" + count +
		"&ts=" + ts.getTime();
	loadXMLDoc(path, "", showHeadlines);
	if (maxUpdates >= 0) {
		--maxUpdates;
		if (maxUpdates < 0) {
			stopUpdates();
		}
	}
}

function showHeadlines() {
	// if xmlhttp shows "loaded"
	if (xmlhttp.readyState==4) {
		// if "OK"
		if (xmlhttp.status==200) {
			updateHeadlines(xmlhttp.responseXML.documentElement);
		}
	}
}

function updateHeadlines(response) {
	var xmlObj = response.getElementsByTagName("headline");
	var iCount = xmlObj.length;
	if (iCount == 0) {
		return;
	}

	carousel.stopAutoPlay();
	this.finish = function() {
		setTimeout(finishUpdateHeadlines, 1000);
	}
	this.finish();

	function finishUpdateHeadlines() {
		clearHeadlines();
		carousel.clear();
		headlines.length = 0;

		//loop through xml array obj and get the new headlines
		for(var i=0;i<iCount;i++) {
			var headline = xmlObj[i];
			updateHeadline(headline);
		}
		carousel.load();
		if (animationPaused) {
			carousel.stopAutoPlay();
		}
		setCurrentArticle();
		animationStopped = false;
	}
}

function updateHeadline(headline) {
	var title;
	var subtitle;
	var summary;
	var product;
	var page;
	var riImageCategory;
	var riSymbolicName;
	var riCaption;
	var timestamp;
	try {
		if (headline.getElementsByTagName('title')[0]) {
			title = headline.getElementsByTagName('title')[0].firstChild.data;
		}
		if (headline.getElementsByTagName('subtitle')[0]) {
			subtitle = headline.getElementsByTagName('subtitle')[0].firstChild.data;
		}
		if (headline.getElementsByTagName('summary')[0]) {
			summary = headline.getElementsByTagName('summary')[0].firstChild.data;
		}
		if (headline.getElementsByTagName('product')[0]) {
			product = headline.getElementsByTagName('product')[0].firstChild.data;
		}
		if (headline.getElementsByTagName('page')[0]) {
			page = headline.getElementsByTagName('page')[0].firstChild.data;
		}
		if (headline.getElementsByTagName('related-image-category')[0]) {
			riImageCategory = headline.getElementsByTagName('related-image-category')[0].firstChild.data;
		}
		if (headline.getElementsByTagName('related-image-symbolic-name')[0]) {
			riSymbolicName = headline.getElementsByTagName('related-image-symbolic-name')[0].firstChild.data;
		}
		if (headline.getElementsByTagName('related-image-caption')[0]) {
			riCaption = headline.getElementsByTagName('related-image-caption')[0].firstChild.data;
		}
		if (headline.getElementsByTagName('timestamp')[0]) {
			timestamp = headline.getElementsByTagName('timestamp')[0].firstChild.data;
		}
	}
	catch (e) {
		var msg = "updateHeadline: error message = "+e + ", description: " + e.description;
		logError(msg);
	}
	addHeadline(title, subtitle, summary, product, page, riImageCategory, riSymbolicName, riCaption, timestamp);
}
