// $Id: AdvertLib.js,v 1.2 2009-11-20 11:59:16 jbesson Exp $

function AdvertLib() {

	var __pub = {};

	var _popupVisible = false;
	var _oneTimeAds = [];
	var _maxLineWidth = 40;


function handleAdverts(adverts) {

	var i;
	var newOneTimeAd = false;
	var newTickerAd = false;
	var tickerHtml = '';

	if (!_popupVisible) {
		_oneTimeAds = [];
	}

	for (i = 0; i < adverts.length; ++i) {

		if (adverts[i].sort == 'T') {
			// ticker
			if (tickerHtml != '') {
				tickerHtml += '&nbsp;|&nbsp;';
			}
			tickerHtml += adverts[i].content;

		} else if (!_popupVisible && adverts[i].sort == 'O') {
			// one-time
			adverts[i].content = _wrapText(adverts[i].content);
			_oneTimeAds.push(adverts[i]);
		}
	}

	if (!_popupVisible && _oneTimeAds.length) {
		_displayOneTime();
	}

	if (tickerHtml != '') {

		// is the ticker txt to display different from what we last remember it to be?
		var cookieText = get_cookie(document.ticker_ads_cookie);
		if(cookieText == null) {
			cookieText = '';
		}
		if(tickerHtml != cookieText) {
			set_cookie(document.ticker_ads_cookie, tickerHtml, '', '/', '', '');
			sky.overlay.ticker(tickerHtml);
		}

	} else {

		//expire the ticker ad cookie
		var expireDate = new Date(0);
		set_cookie(document.ticker_ads_cookie, '', expireDate, '/', '', '');

		// and hide the ticker pop-up
		_hideTicker();
	}
}

function _displayOneTime() {

	sky.overlay.getChoice(
		'Message',
		_oneTimeAds[0].content,
		_oneTimeAds.length > 1
			? [sky.overlay.button('Next', _viewNext), sky.overlay.button('Done', _dismissOneTime)]
			: [sky.overlay.button('Done', _dismissOneTime)]
	);

	_popupVisible = true;
}

function _viewNext() {

	_removeOneTime();
	_displayOneTime();
}

function _dismissOneTime() {

	_removeOneTime();
	_popupVisible = false;
}

function _removeOneTime() {

	// remove the current message
	var ad = _oneTimeAds.shift();

	// we're done with this ad, never fetch it again
	set_cookie(
		document.max_ad_id_cookie,
		ad.id,
		oneYearFromNow(),
		'/',
		'',
		''
	);
}

function _hideTicker() {

	// if the ticker msg is the pop-up showing, hide it
	if (document.fixedMsgRemove && document.fixedMsgType && document.fixedMsgType == 'soft') {
		document.fixedMsgRemove();
	}
}

function _wrapText(text) {
	// IE handles pre-wrap properly, but firefox doesn't!

	if (is_ie) {
		return text;
	}

	var origLines = text.split(' ');
	var newLines = [], i, c;

	for (i = 0; i < origLines.length; i++) {
		c = 0;
		while (c <= origLines[i].length) {
			newLines.push(origLines[i].substring(c, c + _maxLineWidth));
			c += _maxLineWidth;
		}
	}

	return newLines.join(' ');
}

	var _this = {
		pub : __pub,
		handleAdverts : handleAdverts
	};

	return _this;
}
