/**
 * Newsroom library. Gets article content via XHR and creates a history
 * entry for each request, allowing bookmarking and forward/backward
 * navigation.
 *
 * @author tlynn
 * @requires YAHOO
 * @requires YAHOO.util.Dom
 * @requires YAHOO.util.Event
 * @requires YAHOO.util.Connect
 * @requires YAHOO.widgets.History
 */

YAHOO.namespace('gaia.app');

/**
 * Constructor for Newsroom object
 * @param {Object} config Contains name/value pairs for configuration parameters
 */
YAHOO.gaia.app.Newsroom = function(config) {
	this._init(config);
}

YAHOO.gaia.app.Newsroom.prototype = {
	appRoot : '',
	start : 1,
	type : 'article',
	id : '',
	initialIdState : '',
	callback : {},
	url : '',
	articleBody : null,
	imgSrc : '<p class="progress_indicator">Loading Article<br /><img src="http://'+GAIA_config('graphics_server')+'/images/loader.gif" height="60" width="72" alt="Please wait...Loading" title="Please wait...Loading" /></p>',

	/**
	 * Initiates the XHR request for the article content, appending
	 * the required querystring param to instruct backend to spit out
	 * json
	 * @param {String} id The id for the article we're fetching
	 */
	loadArticle : function(id) {
		this.id = id;
		var a = document.getElementById('article'+this.id);
		if (a) {
			this.highlightCurrent(a);
		}
		if (this.appRoot.charAt(0) != '/') {
			this.appRoot = '/' + this.appRoot;
		}
		if (this.appRoot.charAt(this.appRoot.length-1) != '/') {
			this.appRoot += '/';
		}		
		this.url = this.appRoot + this.type + '/' + this.start + '/' + this.id;		
		YAHOO.util.Connect.asyncRequest("GET", this.url+'?ajax=true',this.callback);
	},

	/**
	 * Creates the loading message when the XHR request starts
	 */
	showLoader : function() {
		this.articleBody.innerHTML = this.imgSrc;
		if (YAHOO.env.ua.ie) {
			this.fixFooter();
		}		
	},

	/**
	 * Highlights the currently-selected story
	 * @param {Object} obj The anchor that gets the viewing class
	 */
	highlightCurrent : function(obj) {
		var a = YAHOO.util.Dom.getElementsByClassName('viewing_article','a','archivelist');
		YAHOO.util.Dom.removeClass(a,'viewing_article');
		YAHOO.util.Dom.addClass(obj,'viewing_article');
	},

	/**
	 * Does some initialization, setting up the click function for each anchor
	 */
	initArchiveLinks : function() {
		var anchors, i, len, anchor;
		anchors = YAHOO.util.Dom.get('archivelist').getElementsByTagName('a');
		for (i = 0, len = anchors.length; i < len; i++) {
			anchor = anchors[i];
			YAHOO.util.Event.addListener(anchor, 'click', function (evt,self) {
				YAHOO.util.Event.preventDefault(evt);
				var href = this.href;
				var parts = self.getUrlParts(href);
				self.id = parts.id || YAHOO.util.History.getQueryStringParameter('id', href) || '';
				if (self.id != YAHOO.util.History.getCurrentState('id')) {
					self.showLoader();
					self.start = parts.start || YAHOO.util.History.getQueryStringParameter('start', href) || 1;
					self.type = parts.type || YAHOO.util.History.getQueryStringParameter('type', href) || 'article';
					try {
						YAHOO.util.History.navigate('id', self.id);
					} catch (e) {
						self.loadArticle(self.id);
					}
				}
			},this);
		}

		var currentId = YAHOO.util.History.getCurrentState('id');
		if (currentId && currentId != this.getUrlParts().id) {
			this.id = currentId;
			this.loadArticle(currentId);
		}
	},

	/**
	 * Cheap utility function for IE6 to fix the rounded corners not
	 * reseting their positions
	 */
	fixFooter : function() {
		var news = document.getElementById('news');
		var ft = YAHOO.util.Dom.getElementsByClassName('ft','div',news)[0];
		YAHOO.util.Dom.removeClass(ft,'ft');
		YAHOO.util.Dom.addClass(ft,'ft');
	},

	/**
	 * Breaks up the canonical URL into its important parts for mapping
	 * into the proper parameters
	 * @param {String} href The URL to break up, defaults to doc's URL
	 * @return {Object} parts An object with the type, start and id 
	 */
	getUrlParts : function(href) {
		var url = href || document.location.href;
		var parts = {};
		var tmpparts = [];
		if (this.appRoot) {
			url = url.substring(url.indexOf(this.appRoot)+this.appRoot.length-1,url.length);
			if (url.charAt(0) == '/') {
				url = url.substr(1,url.length);
			}
			if (url.charAt(url.length-1) == '/') {
				url = url.substr(0,url.length-1);
			}
			tmpparts = url.split('/');
			parts.type = tmpparts[0];
			parts.start = parseInt(tmpparts[1])+'';
			parts.id = parseInt(tmpparts[2])+'';
		}
		return parts;
	},

	/**
	 * Sets up any required initialization parameters
	 * @private
	 * @param {Object} config
	 * @return boolean
	 */
	_init : function(config) {
		
		for (var prop in config) {
			this[prop] = config[prop];
		}
		
		this.callback.parent = this;
		this.initialIdState = YAHOO.util.History.getBookmarkedState('id') || this.getUrlParts().id || YAHOO.util.History.getQueryStringParameter('id') || '';
		this.articleBody = document.getElementById('articlebody');
		this.callback.success = function(obj) {			
			var response = eval(obj.responseText);
			if (response.display.body) {
				this.parent.articleBody.innerHTML = '<h3>'+response.display.title+'</h3><p>'+response.display.body+'</p>';
			} else {
				document.location.href = this.parent.url;
			}
			this.parent.fixFooter();
		};

		this.callback.failure = function(obj) {
			document.location.href = this.parent.url;
		};
		
		YAHOO.util.History.register('id', this.initialIdState, this.loadArticle, this, true);

		// Use the Browser History Manager onReady method to initialize the application.
		YAHOO.util.History.onReady(this.initArchiveLinks, this, true);
		// Initialize the browser history management library.
		try {
			YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");
		} catch (e) {
			this.loadArticle(this.initialIdState);		
		}
		return true;
	}
}