//var curID;
/*
---------------------------------------------------------------------------
NAME:			teaserItem
PARAMETERS:		_id - an id
_isActive - true if the teaser should show in the live site
_isDefault - true if the teaser is designated as such & will go first   
_isAlert - true if teaser is an alert
_browseId - id for "read more"
_content - html content for the teaser
_readmoreTitle - title for "read more"
... other stuff
DESCRIPTION:	object to hold teaser data
--------------------------------------------------------------------------
*/
function teaserItem(_id, _isActive, _isDefault, _isAlert, _browseId, _content, _readmoreTitle) {
	try {
		// properties
		this.id = _id ? _id : '';
		this.isActive = _isActive;
		this.isDefault = _isDefault;
		this.isAlert = _isAlert;
		this.browseId = _browseId;
		this.content = _content ? _content : '';
		this.readmoreTitle = _readmoreTitle ? _readmoreTitle : '';
		this.error = '';
		this.topic = '';
		this.hotTopic = '';
		this.keyword = '';

		// methods
		this.hasSearch = teaserItem_hasSearch;
	}
	catch (err) {
		this.error = err.description;
	}
}

/*
---------------------------------------------------------------------------
NAME:			teaserItem_hasSearch
PARAMETERS:		void
DESCRIPTION:	returns true if there is a search defined for this teaser
--------------------------------------------------------------------------
*/
function teaserItem_hasSearch() {
	try {
		return (0 < this.hotTopic.length || 0 < this.topic.length || 0 < this.keyword.length)
	}
	catch (err) {
		this.error = err.description;
	}

	return false;
}

/*
---------------------------------------------------------------------------
NAME:			rotatingTeaser
PARAMETERS:		_teaserXml - xml to use as the teaser data source
DESCRIPTION:	object to help with rotating teaser content
--------------------------------------------------------------------------
*/
function rotatingTeaser(_teaserXml) {
	try {
		// static attributes
		this.debug = false;
		this.schema =
			{
				elementTag: "item"
			, idAttribute: "id"
			, activeAttribute: "active"
			, defaultAttribute: "default"
			, alertAttribute: "alert"
			, browseIdAttribute: "browseid"
			, contentTag: "content"
			, articleTag: "article"
			, topicTag: "topic"
			, readmoreTitleAttribute: "readmoreTitle"
			, hotTopicTag: "hottopic"
			, keywordTag: "keyword"
			, readmoreTag: "readmore"
			}

		// methods
		this.selectNodes = rotatingTeaser_selectNodes;
		this.newDocument = rotatingTeaser_newDocument;
		this.parse = rotatingTeaser_parse;
		this.randomItem = rotatingTeaser_randomItem;
		this.nextItem = rotatingTeaser_nextItem;
		this.createTeaserFromXml = rotatingTeaser_createTeaserFromXml;

		// create xml document from teaser xml
		this.xmlDoc = this.parse(_teaserXml);
		this.lastDefaultIndex = -1;
		this.lastAlertIndex = -1;
		this.lastTeaserIndex = -1;
	}
	catch (err) {
		if (this.debug) {
			alert(err.description);
		}
		this.error = err.description;
	}
}

/*
---------------------------------------------------------------------------
NAME:			rotatingTeaser_randomItem
PARAMETERS:		void
DESCRIPTION:	pulls teaser items out of xmlDoc and returns a random 
teaserItem object
--------------------------------------------------------------------------
*/
function rotatingTeaser_randomItem() {
	try {
		var xmlAlerts;
		var xmlTeasers;

		// get all of the alert elements
		xmlAlerts = this.selectNodes("//" + this.schema.elementTag + "[(@" + this.schema.alertAttribute + "='true' and (not(@" + this.schema.defaultAttribute + ") or @" + this.schema.defaultAttribute + "='true') ]");
		// get all of the teaser elements
		xmlTeasers = this.selectNodes("//" + this.schema.elementTag + "[(not(@" + this.schema.alertAttribute + ") or @" + this.schema.alertAttribute + "='false') and (not(@" + this.schema.defaultAttribute + ") or @" + this.schema.defaultAttribute + "='true') ]");

		// if we have no alerts & no teasers return "no data"
		if ((!xmlAlerts || 0 == xmlAlerts.length) && (!xmlTeasers || 0 == xmlTeasers.length)) {
			return new teaserItem('-1', false, false, false, 'No Data');
		}

		// if we don't have any teasers, and we've used all of the alerts, reset the alert counter
		if ((!xmlTeasers || 0 == xmlTeasers.length) && (this.lastAlertIndex >= xmlAlerts.length - 1)) {
			//this.lastAlertIndex = -1;
			this.lastAlertIndex = 1;
		}

		// if we have alerts (and we haven't already displayed them all), return the first alert we haven't already displayed
		if (xmlAlerts && (this.lastAlertIndex < xmlAlerts.length - 1)) {
			++this.lastAlertIndex;
			return this.createTeaserFromXml(xmlAlerts[this.lastAlertIndex]);
		}

		// if we have teasers & we don't have alerts (or we have displayed all of the alerts already) return a random teaser		

		var xmlTeaser = xmlTeasers[Math.floor(Math.random() * xmlTeasers.length)];

		if (xmlTeaser) {
			return this.createTeaserFromXml(xmlTeaser);
		}
	}
	catch (err) {
		if (this.debug) {
			alert(err.description);
		}
		this.error = err.description;
	}

	// return empty teaser object
	return new teaserItem('-1', false, false, false, 'Error');
}

/*
---------------------------------------------------------------------------
NAME:			rotatingTeaser_nextItem
PARAMETERS:		void
DESCRIPTION:	goes through all the teasers, default first, then alerts, rinse, lather, repeat
--------------------------------------------------------------------------
*/
function rotatingTeaser_nextItem() {
	try {
		var xmlDefault;
		var xmlAlerts;
		var xmlTeasers;
		var teaserReturn = null;

		// get any default elements (to show before alerts)
		//xmlDefault = this.selectNodes("//" + this.schema.elementTag + "[@" + this.schema.defaultAttribute + "='true']");
		xmlDefault = this.selectNodes("//" + this.schema.elementTag + "[@" + this.schema.defaultAttribute + "='true']");

		// get all of the alert elements
		//xmlAlerts = this.selectNodes("//" + this.schema.elementTag + "[@" + this.schema.alertAttribute + "='true']");
		xmlAlerts = this.selectNodes("//" + this.schema.elementTag + "[@" + this.schema.alertAttribute + "='true' and @" + this.schema.activeAttribute + "='true']");

		// get all of the teaser elements
		xmlTeasers = this.selectNodes("//" + this.schema.elementTag + "[(not(@" + this.schema.defaultAttribute + ") or @" + this.schema.defaultAttribute + "='false') and (not(@" + this.schema.alertAttribute + ") or @" + this.schema.alertAttribute + "='false')]");

		// if we have no alerts & no teasers return "no data"
		if ((!xmlDefault || 0 == xmlDefault.length) && (!xmlAlerts || 0 == xmlAlerts.length) && (!xmlTeasers || 0 == xmlTeasers.length)) {
			return new teaserItem('-1', false, false, false, 'No Data');
		}

		// if we have a default (and we haven't already displayed them all), return the first default we haven't already displayed
		if (xmlDefault && (this.lastDefaultIndex < xmlDefault.length - 1)) {
			++this.lastDefaultIndex;
			teaserReturn = this.createTeaserFromXml(xmlDefault[this.lastDefaultIndex]);
		}
		// if we have alerts (and we haven't already displayed them all), return the first alert we haven't already displayed
		else if (xmlAlerts && (this.lastAlertIndex < xmlAlerts.length - 1)) {
			++this.lastAlertIndex;
			teaserReturn = this.createTeaserFromXml(xmlAlerts[this.lastAlertIndex]);
		}
		else if (xmlTeasers && (this.lastTeaserIndex < xmlTeasers.length - 1)) {
			++this.lastTeaserIndex;
			teaserReturn = this.createTeaserFromXml(xmlTeasers[this.lastTeaserIndex]);
		}

		//reset the counters if we moved to the end
		if (xmlDefault && 0 < xmlDefault.length) {
			// reset to begining of alerts if we are at the end of the teasers 
			//if ( (!xmlTeasers || 0 == xmlTeasers.length || (this.lastTeaserIndex >= xmlTeasers.length-1)) && this.lastDefaultIndex >= xmlDefault.length-1)
			//	{
			//if (!(xmlTeasers && (this.lastTeaserIndex < xmlTeasers.length-1)))
			if ((!xmlTeasers || 0 == xmlTeasers.length || (this.lastTeaserIndex >= xmlTeasers.length - 1)) && (!xmlAlerts || 0 == xmlAlerts.length || (this.lastAlertIndex >= xmlAlerts.length - 1))) {
				this.lastDefaultIndex = -1;
			}
		}

		if (xmlAlerts && 0 < xmlAlerts.length) {
			// reset to begining of alerts if we are at the end of the teasers and the alerts
			if ((!xmlTeasers || 0 == xmlTeasers.length || (this.lastTeaserIndex >= xmlTeasers.length - 1)) && this.lastAlertIndex >= xmlAlerts.length - 1) {
				this.lastAlertIndex = -1;
			}
		}
		if (xmlTeasers && 0 < xmlTeasers.length) {
			// reset the teasers if we are at the end of them
			if (this.lastTeaserIndex >= xmlTeasers.length - 1) {
				this.lastTeaserIndex = -1;
			}
		}
		// return the teaser we found
		if (teaserReturn) {
			return teaserReturn;
		}

	}
	catch (err) {
		return new teaserItem('-1', false, false, false, 'Error');

		if (this.debug) {
			alert(err.description);
		}
		this.error = err.description;
	}

	// return empty teaser object
	return new teaserItem('-1', false, false, false, 'Error');
}









/*
---------------------------------------------------------------------------
NAME:			rotatingTeaser_createTeaserFromXml
PARAMETERS:		xmlNode - source xml
DESCRIPTION:	return teaser object from xml node
--------------------------------------------------------------------------
*/
function rotatingTeaser_createTeaserFromXml(xmlNode) {
	// pull the id & allert attriubtes out of the item element
	var id = xmlNode.getAttribute(this.schema.idAttribute); 		//<-- id attribute
	var isActive = xmlNode.getAttribute(this.schema.activeAttribute);
	var isDefault = xmlNode.getAttribute(this.schema.defaultAttribute); // <-- default attribute
	var isAlert = xmlNode.getAttribute(this.schema.alertAttribute); //<-- alert attribute
	var browseId = xmlNode.getAttribute(this.schema.browseIdAttribute);
	var readmoreTitle;

	// pull the content element out of the item element
	var xmlCell = xmlNode.getElementsByTagName(this.schema.contentTag)[0];
	var content = (xmlCell && xmlCell.firstChild) ? xmlCell.firstChild.data : '';

	// get a title for our content - grab it from the content
	readmoreTitle = xmlCell.getAttribute('title');
	// but overwrite it if there is content in the readmore tag
	var nextCell = xmlNode.getElementsByTagName(this.schema.readmoreTag)[0];
	if (nextCell)
	{ readmoreTitle = nextCell.getAttribute('title') }

	// return a new teaser object
	var newItem = new teaserItem(id ? id : '', Boolean(isActive), Boolean(isDefault), Boolean(isAlert), browseId ? browseId : '', content, readmoreTitle ? readmoreTitle : '');

	// search variables
	var hotTopic;
	var topic;
	var keyword;

	// get defined hot topic for search
	xmlCell = xmlNode.getElementsByTagName(this.schema.hotTopicTag)[0];
	hotTopic = (xmlCell && xmlCell.firstChild) ? xmlCell.firstChild.data : '';
	newItem.hotTopic = hotTopic.toString();

	// get topic for search (only if we don't have a hot topic)
	if (0 == hotTopic.length) {
		xmlCell = xmlNode.getElementsByTagName(this.schema.topicTag)[0];
		topic = (xmlCell && xmlCell.firstChild) ? xmlCell.firstChild.data : '';
		newItem.topic = topic.toString();
	}

	// get keyword for search (only if we don't have a hot topic or topic)
	if (0 == hotTopic.length && 0 == topic.length) {
		xmlCell = xmlNode.getElementsByTagName(this.schema.keywordTag)[0];
		keyword = (xmlCell && xmlCell.firstChild) ? xmlCell.firstChild.data : '';
		newItem.keyword = keyword.toString();
	}

	return newItem;
}

/*
---------------------------------------------------------------------------
NAME:			rotatingTeaser_parse
PARAMETERS:		_teaserXml - source xml
DESCRIPTION:	parses xml string and returns document object
--------------------------------------------------------------------------
*/
function rotatingTeaser_parse(_teaserXml) {
	try {
		// convert passed in xml string into document object
		if (typeof DOMParser != "undefined") {
			if (browserType == "ie") {
				var xdoc = new ActiveXObject("MSXML2.DOMDocument");
				xdoc.async = false
				xdoc.loadXML(_teaserXml);
				return xdoc;
			}
			else {
				// Mozilla (Firefox et al.)
				return (new DOMParser()).parseFromString(_teaserXml, "application/xml");
			}
		}
		else if (typeof ActiveXObject != "undefined") {
			// IE 6+
			var doc = this.newDocument();
			doc.loadXML(_teaserXml);
			return doc;
		}
		else {
			// Safari method (load the data as a url)
			var url = "data:text/xml;charset=utf-8," + encodeURIComponent(_teaserXml);
			var request = new XMLHttpRequest();

			request.open("GET", url, false);
			request.send(null);
			return request.responseXML;
		}
	}
	catch (err) {
		if (this.debug) {
			alert(err.description);
		}
		this.error = err.description;
	}

	return null;
}

/*
---------------------------------------------------------------------------
NAME:			rotatingTeaser_selectNodes(xpathExpression)
PARAMETERS:		xpathExpression - XPath expression used to select nodes
DESCRIPTION:	select nodes fromt the xml document using the given xpath
expression
--------------------------------------------------------------------------
*/
function rotatingTeaser_selectNodes(xpathExpression) {

	// get all of the alert elements
	if (this.xmlDoc && browserType == "ie") {
		// IE way to select nodes in an xml document
		return this.xmlDoc.selectNodes(xpathExpression);
	}

	if (this.xmlDoc && window.XPathEvaluator) {
		var oEvaluator = new XPathEvaluator();

		// W3C way to select nodes        
		var oResult = oEvaluator.evaluate(xpathExpression, this.xmlDoc, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
		xmlRows = new Array;

		if (oResult != null) {
			var oElement = oResult.iterateNext();
			while (oElement) {
				xmlRows.push(oElement);
				oElement = oResult.iterateNext();
			}
		}

		return xmlRows;
	}
	else {
		return null;
	}
}

/*
---------------------------------------------------------------------------
NAME:			rotatingTeaser_newDocument
PARAMETERS:		rootTagName - root tag for new document
namespaceURL - namespace URL for new document
DESCRIPTION:	Create a new empty document object
--------------------------------------------------------------------------
*/
function rotatingTeaser_newDocument(rootTagName, namespaceURL) {
	try {
		if (!rootTagName) {
			rootTagName = '';
		}
		if (!namespaceURL) {
			namespaceURL = '';
		}

		if (document.implementation && document.implementation.createDocument) { // w3c method		
			return document.implementation.createDocument(namespaceURL, rootTagName, null);
		}
		else { // IE method
			var doc = new ActiveXObject("MSXML2.DOMDocument");

			if (rootTagName) {
				var prefix = "";
				var tagname = rootTagName;
				var p = rootTagName.indexOf(':');
				if (p != -1) {
					prefix = rootTagName.substring(0, p);
					tagname = rootTagName.substring(p + 1);
				}

				if (namespaceURL) {
					if (!prefix) {
						prefix = "a0";
					}
				}
				else {
					prefix = "";
				}

				var text = "<" + (prefix ? (prefix + ":") : "") + tagname + (namespaceURL ? (" xmlns:" + prefix + '="' + namespaceURL + '"') : "") + "/>";
				doc.loadXML(text);
			}
			return doc;
		}
	}
	catch (err) {
		if (this.debug) {
			alert(err.description);
		}
		this.error = err.description;
	}

	return null;
}
/*
---------------------------------------------------------------------------
NAME:			displayTeaser()
PARAMETERS:		null
DESCRIPTION:	take a teaser and place the content into an existing panel named 'content'
--------------------------------------------------------------------------
*/
function displayTeaser() {
	try {

		if (theTease) {
			// get a random teaser
			// var randomTeaser = theTease.randomItem();

			// go through teasers in an orderly fashion
			var scrollTeasers = theTease.nextItem();
			if (scrollTeasers && content) {
				// update the hidden id value
				if (currentTeaserId) {
					currentTeaserId.value = scrollTeasers.id;
				}

				// show/hide search related elements
				if (scrollTeasers.hasSearch()) {
					show('findbutton');
				}
				else {
					hide('geocontrol');
					hide('findbutton');
				}

				// show/hide the 'read more' button based on teaser browse id
				if (scrollTeasers.browseId && 0 < scrollTeasers.browseId.length) {
					show('morebutton');
					setUrl(scrollTeasers.browseId, scrollTeasers.readmoreTitle);
				}
				else {
					hide('morebutton');
				}
				var translationCookie = readCookie("autoTranslateLanguage");
				if (null == translationCookie || 0 == translationCookie.length) {
					content.innerHTML = scrollTeasers.content;
				}
				else {
					//alert('div.' + content.id);
					//$('#' + content.id).translate(translationCookie);
					$.translate(scrollTeasers.content, 'en', translationCookie, {
						complete: function (translation) { $('#' + content.id).html(translation); }
					});
				}
			}
			// keep the teasers rollin'
			if (TeaserCount > 1) {
				timerID = setTimeout("displayTeaser()", interval);
			}
			//by default, we're not going to force focus here, only if someone is manually working through the teasers.
			//location.href = anchor;
		}
		else if (timerID) {
			clearTimeout(timerID);
			timerID = 0;
		}
	}
	catch (err) {
		if (this.debug) {
			alert(err.description);
		}
		this.error = err.description;
	}
}
/*
---------------------------------------------------------------------------
NAME:			stopTeaser()
PARAMETERS:		null
DESCRIPTION:	stop the teaser but let it resume if need be
--------------------------------------------------------------------------
*/

function stopTeaser() {
	try {
		clearTimeout(timerID);
		timerID = 0;
		location.href = anchor;
	}
	catch (err) {
		if (this.debug) {
			alert(err.description);
		}
		this.error = err.description;
	}
}
/*
---------------------------------------------------------------------------
NAME:			next()
PARAMETERS:		null
DESCRIPTION:	get the next teaser in the set
--------------------------------------------------------------------------
*/
function next() {
	try {
		var scrollTeasers = theTease.nextItem();
		if (scrollTeasers && content) {
			// update the hidden id value
			if (currentTeaserId) {
				currentTeaserId.value = scrollTeasers.id;
			}

			// show/hide search related elements
			if (scrollTeasers.hasSearch()) {
				show('findbutton');
			}
			else {
				hide('geocontrol');
				hide('findbutton');
			}

			// show/hide the 'read more' button based on teaser browse id
			if (scrollTeasers.browseId && 0 < scrollTeasers.browseId.length) {
				show('morebutton');
				setUrl(scrollTeasers.browseId, scrollTeasers.readmoreTitle);
			}
			else {
				hide('morebutton');
			}

			content.innerHTML = scrollTeasers.content;
		}
		clearTimeout(timerID);
		timerID = 0;
		location.href = anchor;
	}
	catch (err) {
		if (this.debug) {
			alert(err.description);
		}
		this.error = err.description;
	}
}

function setUrl(browseId, title) {
	try {

		title = title.replace(/ /g, "_");
		title = title + ".aspx";
		var sUrl = "browsetips.aspx?TipId=TEASERID&Title=TITLE&referrer=default.aspx#teaser";
		sUrl = sUrl.replace(/TEASERID/, URLEncode(browseId));
		sUrl = sUrl.replace(/TITLE/, URLEncode(title));
		oLink = document.getElementById('morelink');
		oLink.href = sUrl;
	}
	catch (err) {
		if (this.debug) {
			alert(err.description);
		}
		this.error = err.description;
	}
}

function goToGeocontrol() {
	location.href = '#geocontrol';
}

function URLEncode(clearString) {
	var output = '';
	var x = 0;
	clearString = clearString.toString();
	var regex = /(^[a-zA-Z0-9_.]*)/;
	while (x < clearString.length) {
		var match = regex.exec(clearString.substr(x));
		if (match != null && match.length > 1 && match[1] != '') {
			output += match[1];
			x += match[1].length;
		} else {
			if (clearString[x] == ' ')
				output += '+';
			else {
				var charCode = clearString.charCodeAt(x);
				var hexVal = charCode.toString(16);
				output += '%' + (hexVal.length < 2 ? '0' : '') + hexVal.toUpperCase();
			}
			x++;
		}
	}
	return output;
}

