/**
 * Copyright (C) 2005-2008 Alfresco Software Limited.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

 * As a special exception to the terms and conditions of version 2.0 of
 * the GPL, you may redistribute this Program in connection with Free/Libre
 * and Open Source Software ("FLOSS") applications as described in Alfresco's
 * FLOSS exception.  You should have recieved a copy of the text describing
 * the FLOSS exception, and it is also available here:
 * http://www.alfresco.com/legal/licensing
 */

/**
 * LastNews component.
 *
 * @namespace Alfresco
 * @class Alfresco.LastNews
 */
(function()
{
	var htmlAux = '';
	var counter = 1;

	/**
	 * YUI Library aliases
	 */
	var Dom = YAHOO.util.Dom,
		 Event = YAHOO.util.Event,
		 Element = YAHOO.util.Element;

	/**
	 * Alfresco Slingshot aliases
	 */
	var $html = Alfresco.util.encodeHTML;


	/**
	 * LastNews constructor.
	 *
	 * @param {String} htmlId The HTML id of the parent element
	 * @return {Alfresco.LastNews} The new LastNews instance
	 * @constructor
	 */
	Alfresco.LastNews = function(htmlId)
	{
		/* Mandatory properties */
		this.name = "Alfresco.LastNews";
		this.id = htmlId;

		/* Initialise prototype properties */
		this.widgets = {};
		this.currentFilter = {};

		/* Register this component */
		Alfresco.util.ComponentManager.register(this);

		/* Load YUI Components */
		Alfresco.util.YUILoaderHelper.require(["button", "dom", "datasource", "datatable", "paginator", "event", "element"], this.onComponentsLoaded, this);

		/* Decoupled event listeners */
		YAHOO.Bubbling.on("blogConfigChanged", this.onBlogConfigChanged, this);
		YAHOO.Bubbling.on("filterChanged", this.onFilterChanged, this);
		YAHOO.Bubbling.on("LastNewsRefresh", this.onLastNewsRefresh, this);

		return this;
	};

	Alfresco.LastNews.prototype =
	{
		/**
		 * Object container for initialization options
		 *
		 * @property options
		 * @type object
		 */
		options:
		{
			/**
			 * Current siteId.
			 *
			 * @property siteId
			 * @type string
			 */
			siteId: "",

			/**
			 * ContainerId representing root container
			 *
			 * @property containerId
			 * @type string
			 * @default "blog"
			 */
			containerId: "blog",

			/**
			 * Initially used filter name and id.
			 */
			initialFilter: {},

			/**
			 * Number of items per page
			 *
			 * @property pageSize
			 * @type int
			 */
			pageSize: '',

			/**
			 * Flag indicating whether the list shows a detailed view or a simple one.
			 *
			 * @property simpleView
			 * @type boolean
			 */
			simpleView: false,

			/**
			 * Maximum length of post to show in list view
			 *
			 * @property maxContentLength
			 * @type int
			 * @default 512
			 */
			maxContentLength: 9999,
			field: '',
			urlView: '',
			style: '',
			hasLastNew: true
		},

		/**
		 * Current filter to filter blog post list.
		 *
		 * @property currentFilter
		 * @type object
		 */
		currentFilter: null,

		/**
		 * Object container for storing YUI widget instances.
		 *
		 * @property widgets
		 * @type object
		 */
		widgets: null,

		/**
		 * Object container for storing module instances.
		 *
		 * @property modules
		 * @type object
		 */
		modules: null,


		/**
		 * Tells whether an action is currently ongoing.
		 *
		 * @property busy
		 * @type boolean
		 * @see _setBusy/_releaseBusy
		 */
		busy: false,

		/**
		 * True if publishing actions should be displayed
		 *
		 * @property showPublishingActions
		 * @type boolean
		 * @default false
		 */
		showPublishingActions: false,

		/**
		 * Offset of first record on page
		 *
		 * @property recordOffset
		 * @type int
		 * @default 0
		 */
		recordOffset: 0,

		/**
		 * Total number of posts in the current view (across all pages)
		 *
		 * @property totalRecords
		 * @type int
		 * @default 0
		 */
		totalRecords: 0,

		/**
		 * Set multiple initialization options at once.
		 *
		 * @method setOptions
		 * @param obj {object} Object literal specifying a set of options
		 */
		setOptions: function LastNews_setOptions(obj)
		{
			this.options = YAHOO.lang.merge(this.options, obj);
			return this;
		},

		/**
		 * Set messages for this component.
		 *
		 * @method setMessages
		 * @param obj {object} Object literal specifying a set of messages
		 * @return {Alfresco.DocumentList} returns 'this' for method chaining
		 */
		setMessages: function LastNews_setMessages(obj)
		{
			Alfresco.util.addMessages(obj, this.name);
			return this;
		},

		/**
		 * Fired by YUILoaderHelper when required component script files have
		 * been loaded into the browser.
		 *
		 * @method onComponentsLoaded
		 */
		onComponentsLoaded: function LastNews_onComponentsLoaded()
		{
			Event.onContentReady(this.id, this.onReady, this, true);
		},

		/**
		 * Fired by YUI when parent element is available for scripting.
		 * Component initialisation, including instantiation of YUI widgets and event listener binding.
		 *
		 * @method onReady
		 */
		onReady: function LastNews_onReady()
		{
			// Reference to self used by inline functions
			var me = this;

			// called by the paginator on state changes
			var handlePagination = function LastNews_handlePagination(state, dt)
			{
				//me.currentPage = state.page;
				me._updateLastNews(
				{
					page: state.page
				});
			};

			// YUI Paginator definition
			this.widgets.paginator = new YAHOO.widget.Paginator(
			{
				containers: [this.id + "-paginator"],
				rowsPerPage: this.options.pageSize,
				initialPage: 1,
				template: this._msg("pagination.template"),
				pageReportTemplate: this._msg("pagination.template.page-report"),
				previousPageLinkLabel : this._msg("pagination.previousPageLinkLabel"),
				nextPageLinkLabel	  : this._msg("pagination.nextPageLinkLabel")
			});

			this.widgets.paginator.subscribe("changeRequest", handlePagination);

			// Hook action events for details view
			var fnActionHandlerDiv = function LastNews_fnActionHandlerDiv(layer, args)
			{
				var owner = YAHOO.Bubbling.getOwnerByTagName(args[1].anchor, "div");
				if (owner !== null)
				{
					if (typeof me[owner.className] == "function")
					{
						args[1].stop = true;
						me[owner.className].call(me, args[1].target.offsetParent, owner);
					}
				}

				return true;
			};
			YAHOO.Bubbling.addDefaultAction("blogpost-action-link-div", fnActionHandlerDiv);

			// Hook action events for simple view
			var fnActionHandlerSpan = function LastNews_fnActionHandlerSpan(layer, args)
			{
				var owner = YAHOO.Bubbling.getOwnerByTagName(args[1].anchor, "span");
				if (owner !== null)
				{
					var action = owner.className;
					var target = args[1].target;
					if (typeof me[action] == "function")
					{
						me[action].call(me, target.offsetParent, owner);
						args[1].stop = true;
					}
				}

				return true;
			};
			YAHOO.Bubbling.addDefaultAction("blogpost-action-link-span", fnActionHandlerSpan);


			// DataSource definition
			var uriLastNews = YAHOO.lang.substitute(Alfresco.constants.PROXY_URI + "api/blog/site/{site}/{container}/posts",
			{
				site: this.options.siteId,
				container: this.options.containerId
			});
			this.widgets.dataSource = new YAHOO.util.DataSource(uriLastNews);
			this.widgets.dataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
			this.widgets.dataSource.connXhrMode = "queueRequests";
			this.widgets.dataSource.responseSchema =
			{
				resultsList: "items",
				fields:
				[
					 "url", "commentsUrl",  "nodeRef", "name", "title", "content", "author", "createdOn", "modifiedOn",
					 "permissions", "commentCount", "tags", "isDraft", "releasedOn", "isUpdated", "updatedOn", "publishedOn",
					 "updatedOn", "postId", "postLink", "outOfDate", "isPublished"
				],
				metaFields:
				{
					recordOffset: "startIndex",
					totalRecords: "total",
					metadata: "metadata"
				}
			};

			/**
			 * Blog post element. We only have a list and not an acutal table, there is therefore
			 * only one column renderer
			 *
			 * @method renderBlogPost
			 * @param elCell {object}
			 * @param oRecord {object}
			 * @param oColumn {object}
			 * @param oData {object|string}
			 */
			var renderBlogPost = function LastNews_renderBlogPost(elCell, oRecord, oColumn, oData)
			{
				// fetch the data and pregenerate some values
				var data = oRecord.getData();
				var postViewUrl = me.generateNewViewUrl(me.options.siteId, me.options.containerId, data.name);

				//----------------------------------------
					// Extraemos el resumen delimitado por la etiqueta <resumen></resumen>
				var start = data.content.indexOf('&lt;resumen&gt;');
				var summary = '';
				 //Si existe alg?n v?deo
				if ( start > -1 ){
					var end = data.content.indexOf('&lt;/resumen&gt;');
					summary = data.content.substring(start+15, end);
					//Eliminamos todos los v?deos que pudieran existir
					var re = new RegExp('(&lt;resumen&gt;).*(&lt;/resumen&gt;)', 'g');
					data.content = data.content.replace(re,"");
				}
				//--------------------------
				//----------------------------------------
				// Extraemos el video delimitado por la etiqueta <video></video>
				start = data.content.indexOf('&lt;video&gt;');
				var video = '';
				//Si existe alg?n v?deo
				if ( start > -1 ){
					var end = data.content.indexOf('&lt;/video&gt;');
					video = data.content.substring(start+13, end);

					//Eliminamos todos los v?deos que pudieran existir
					var re = new RegExp('(&lt;video&gt;).*(&lt;/video&gt;)', 'g');
					data.content = data.content.replace(re,"");
				}
				//-------------------------- 

				//------------------------
				//Obtenemos la primera imagen que se haya insertado
				//(Sólo tenemos en cuenta la primera, si se introducen más de una se ignorarán)
				start = data.content.indexOf('<img');
				img = '';

				//Si existe alguna imagen obtenemos la primera y eliminamos todas del contenido.
				if ( start > -1 ){
					var contentAux = data.content.substring(start, data.content.length);
					var end = contentAux.indexOf('/>');
					end = end + start + 2;
					var img = data.content.substring(start, end);

					//Eliminamos todas las imágenes del contenido, para no mostrarlas en el contenido
				var re = new RegExp('(<img)[ ]+(src=")[^"]*\"[ ]*/>', 'g');
					data.content = data.content.replace(re,"");
				}
				//-------------

				var html = '';

				if ( counter < me.options.pageSize || !me.options.hasLastNew)
					html += '<div class="mod25">';
				else
					html += '<div class="mod25 lastmargin">';

				html += '<h3 class="' + me.options.style + '">' + $html(data.title) + '</h3>';
				html += '<div class="img_container">';

				if ( (video != null) && (video != '') ){

					var type = video.substring(video.lastIndexOf(video), video.length);
					html += '<embed ';
					html += '  src="' + YAHOO.lang.substitute(Alfresco.constants.URL_CONTEXT) + 'videos/player.swf" ';
					html += '  width="208"';
					html += '  height="144"';
					html += '  allowscriptaccess="always"';
					html += '  allowfullscreen="true"';
					html += '  wmode="transparent"';
					html += '  flashvars="file=' + window.location.protocol + '//' + window.location.host + YAHOO.lang.substitute(Alfresco.constants.URL_CONTEXT) + video + '?filename=content.' + type + '&wmode=transparent&autostart=false"';
					html += '/>';
		 		}
				else
					html += img;
				html += '<a href="' + postViewUrl + '" title="Ir" class="btn_ir"><span class="hide">Ir</span></a>';
				html += '</div>';
				html += '<p>' + Alfresco.util.stripUnsafeHTMLTags(summary) + '...</p>';
				html += '</div>';

				htmlAux += html;
				counter ++;
			};

			// DataTable column defintions
			var columnDefinitions = [
			{
				key: "blogposts", label: "BlogPosts", sortable: false, formatter: renderBlogPost
			}];

			// DataTable definition
			this.widgets.dataTable = new YAHOO.widget.DataTable(this.id + "-" + this.options.field, columnDefinitions, this.widgets.dataSource,
			{
				initialLoad: false,
				dynamicData: true,
				MSG_EMPTY: this._msg("message.loading")
			});

			var div = Dom.get(this.id + '-' + this.options.field);
			div.innerHTML = "";

			// Update totalRecords on the fly with value from server
			this.widgets.dataTable.handleDataReturnPayload = function DL_handleDataReturnPayload(oRequest, oResponse, oPayload)
			{
				// Save totalRecords for Paginator update later
				me.recordOffset = oResponse.meta.recordOffset;
				me.totalRecords = oResponse.meta.totalRecords;

				oPayload = oPayload || {};
				oPayload.recordOffset = oResponse.meta.recordOffset;
				oPayload.totalRecords = oResponse.meta.totalRecords;

				return oPayload;
			}

			// Prevent the DataTable from updating the Paginator widget
			this.widgets.dataTable.doBeforePaginatorChange = function DL_doBeforePaginatorChange(oPaginatorState)
			{
				return false;
			}

			// Rendering complete event handler
			this.widgets.dataTable.subscribe("renderEvent", function()
			{
				// Update the paginator if it's been created
				this.widgets.paginator.setState(
				{
					recordOffset: this.recordOffset,
					totalRecords: this.totalRecords
				});
				this.widgets.paginator.render();
			}, this, true);

			// Custom error messages
			this._setDefaultDataTableErrors(this.widgets.dataTable);

			// Hook tableMsgShowEvent to clear out fixed-pixel width on <table> element (breaks resizer)
			this.widgets.dataTable.subscribe("tableMsgShowEvent", function(oArgs)
			{
				// NOTE: Scope needs to be DataTable
				this._elMsgTbody.parentNode.style.width = "";
			});

			// Override abstract function within DataTable to set custom error message
			this.widgets.dataTable.doBeforeLoadData = function LastNews_doBeforeLoadData(sRequest, oResponse, oPayload)
			{
				if (oResponse.error)
				{
					try
					{
						var response = YAHOO.lang.JSON.parse(oResponse.responseText);
						this.set("MSG_ERROR", response.message);
					}
					catch(e)
					{
						me._setDefaultDataTableErrors(me.widgets.dataTable);
					}
				}
				else if (oResponse.results && !me.options.usePagination)
				{
					this.renderLoopSize = me.options.pageSize;
				}

				// set whether publishing actions should be available
				me.showPublishingActions = oResponse.meta.metadata.externalBlogConfig;

				// Must return true to have the "Loading..." message replaced by the error message
				return true;
			};

			// Enable row highlighting
			this.widgets.dataTable.subscribe("rowMouseoverEvent", this.onEventHighlightRow, this, true);
			this.widgets.dataTable.subscribe("rowMouseoutEvent", this.onEventUnhighlightRow, this, true);

			// Load the new blog posts by default
			var filterObj = YAHOO.lang.merge(
			{
				filterId: "all",
				filterOwner: "Alfresco.LastNewsFilter",
				filterData: null
			}, this.options.initialFilter);
			YAHOO.Bubbling.fire("filterChanged", filterObj);
		},

		/**
		* Generate a view url for a given site, container and blog post id.
		*
		* @param postId the id/name of the post
		* @return an url to access the post
	  */
	  generateNewViewUrl:  function LastNews_generateNewViewUrl(site, container, postId)
	  {
		  var url = YAHOO.lang.substitute(Alfresco.constants.URL_CONTEXT + 'page?p=' + this.options.urlView + '-postview&container={container}&postId={postId}&listViewLinkBack=true',
		  {
			  site: site,
			  container: container,
			  postId: postId
		  });
		  return url;
	  },

		// Actions

		/**
		 * Action handler for the simple view toggle button
		 *
		 * @method onSimpleView
		 */
		onSimpleView: function LastNews_onSimpleView(e, p_obj)
		{
			this.options.simpleView = !this.options.simpleView;
			p_obj.set("label", this._msg(this.options.simpleView ? "header.detailList" : "header.simpleList"));

			// refresh the list
			YAHOO.Bubbling.fire("LastNewsRefresh");
			Event.preventDefault(e);
		},

		/**
		 * Handler for the view blog post action links
		 *
		 * @method onViewBlogPost
		 * @param row {object} DataTable row representing post to be actioned
		 */
		onViewBlogPost: function LastNews_onViewNode(row)
		{
			var record = this.widgets.dataTable.getRecord(row);
			window.location = this._generatePostViewUrl(record.getData('name'));
		},

		/**
		 * Handler for the edit blog post action links
		 *
		 * @method onEditBlogPost
		 * @param row {object} DataTable row representing post to be actioned
		 */
		onEditBlogPost: function LastNews_onEditBlogPost(row)
		{
			var record = this.widgets.dataTable.getRecord(row);
			var url = YAHOO.lang.substitute(Alfresco.constants.URL_CONTEXT + "page?p=blog-postedit&container={container}&postId={postId}",
			{
				site: this.options.siteId,
				container: this.options.containerId,
				postId: record.getData('name')
			});
			window.location = url;
		},

		/**
		 * Handler for the delete blog post action links
		 *
		 * @method onDeleteBlogPost
		 * @param row {object} DataTable row representing post to be actioned
		 */
		onDeleteBlogPost: function LastNews_onDeleteBlogPost(row)
		{
			var record = this.widgets.dataTable.getRecord(row);
			var me = this;
			Alfresco.util.PopupManager.displayPrompt(
			{
				text: this._msg("message.confirm.delete", $html(record.getData('title'))),
				buttons: [
				{
					text: this._msg("button.delete"),
					handler: function LastNews_onDeleteBlogPost_delete()
					{
						this.destroy();
						me._deleteBlogPostConfirm.call(me, record.getData('name'));
					}
				},
				{
					text: this._msg("button.cancel"),
					handler: function LastNews_onDeleteBlogPost_cancel()
					{
						this.destroy();
					},
					isDefault: true
				}]
			});
		},

		/**
		 * Handler for the publish external action links
		 *
		 * @method onPublishExternal
		 * @param row {object} DataTable row representing post to be actioned
		 */
		onPublishExternal: function Blog_onPublishExternal(row)
		{
			var record = this.widgets.dataTable.getRecord(row);
			this._publishExternal(record.getData('name'));
		},

		/**
		 * Handler for the update external action links
		 *
		 * @method onUpdateExternal
		 * @param row {object} DataTable row representing post to be actioned
		 */
		onUpdateExternal: function Blog_onUpdateExternal(row)
		{
			var record = this.widgets.dataTable.getRecord(row);
			this._updateExternal(record.getData('name'));
		},


		/**
		 * On blog config changed h handler
		 *
		 * @method onTagSelected
		 */
		onBlogConfigChanged: function LastNews_onBlogConfigChanged(layer, args)
		{
			// refresh the list
			this._updateLastNews();
		},

		// Actions implementation

		/**
		 * Blog post deletion implementation
		 *
		 * @method _deleteBlogPostConfirm
		 * @param postId {string} the id of the blog post to delete
		 */
		_deleteBlogPostConfirm: function LastNews__deleteBlogPostConfirm(postId)
		{
			// show busy message
			if (! this._setBusy(this._msg('message.wait')))
			{
				return;
			}

			// ajax request success handler
			var onDeletedSuccess = function LastNews_deleteBlogPostConfirm_onDeletedSuccess(response)
			{
				// remove busy message
				this._releaseBusy();

				// reload the table data
				this._updateLastNews();
			};

			// get the url to call
			var url = YAHOO.lang.substitute(Alfresco.constants.PROXY_URI + "api/blog/post/site/{site}/{container}/{postId}?page=blog-postlist",
			{
				site: this.options.siteId,
				container: this.options.containerId,
				postId: postId
			});

			// execute ajax request
			Alfresco.util.Ajax.request(
			{
				url: url,
				method: "DELETE",
				responseContentType : "application/json",
				successMessage: this._msg("message.delete.success"),
				successCallback:
				{
					fn: onDeletedSuccess,
					scope: this
				},
				failureMessage: this._msg("message.delete.failure"),
				failureCallback:
				{
					fn: function(response)
					{
						this._releaseBusy();
					},
					scope: this
				}
			});
		},

		/**
		 * Publishing of a blog post implementation
		 *
		 * @method _publishExternal
		 * @param postId {string} the id of the blog post to publish
		 */
		_publishExternal: function LastNews__publishExternal(postId)
		{
			// show busy message
			if (! this._setBusy(this._msg('message.wait')))
			{
				return;
			}

			// ajax call success handler
			var onPublishedSuccess = function LastNews_onPublishedSuccess(response)
			{
				// remove busy message
				this._releaseBusy();

				// reload the table data
				this._updateLastNews();
			};

			// get the url to call
			var url = Alfresco.util.blog.generatePublishingRestURL(this.options.siteId, this.options.containerId, postId);

			// execute ajax request
			Alfresco.util.Ajax.request(
			{
				url: url,
				method: "POST",
				requestContentType : "application/json",
				responseContentType : "application/json",
				dataObj:
				{
					action : "publish"
				},
				successMessage: this._msg("message.publishExternal.success"),
				successCallback:
				{
					fn: onPublishedSuccess,
					scope: this
				},
				failureMessage: this._msg("message.publishExternal.failure"),
				failureCallback:
				{
					fn: function(response) { this._releaseBusy(); },
					scope: this
				}
			});
		},


		/**
		 * Updating of an external published blog post implementation
		 *
		 * @method _updateExternal
		 * @param postId {string} the id of the blog post to update
		 */
		_updateExternal: function LastNews__updateExternal(postId)
		{
			// show busy message
			if (! this._setBusy(this._msg('message.wait')))
			{
				return;
			}

			// ajax request success handler
			var onUpdatedSuccess = function LastNews_onUpdatedSuccess(response)
			{
				// remove busy message
				this._releaseBusy();

				// reload the table data
				this._updateLastNews();
			};

			// get the url to call
			var url = Alfresco.util.blog.generatePublishingRestURL(this.options.siteId, this.options.containerId, postId);

			// execute ajax request
			Alfresco.util.Ajax.request(
			{
				url: url,
				method: "POST",
				requestContentType : "application/json",
				responseContentType : "application/json",
				dataObj:
				{
					action : "update"
				},
				successMessage: this._msg("message.updateExternal.success"),
				successCallback:
				{
					fn: onUpdatedSuccess,
					scope: this
				},
				failureMessage: this._msg("message.updateExternal.failure"),
				failureCallback:
				{
					fn: function(response) { this._releaseBusy(); },
					scope: this
				}
			});
		},


		/**
		 * Unpublishing of an external published blog post implementation
		 *
		 * @method _unpublishExternal
		 * @param postId {string} the id of the blog post to update
		 */
		_unpublishExternal: function LastNews__onUnpublishExternal(postId)
		{
			// show busy message
			if (! this._setBusy(this._msg('message.wait')))
			{
				return;
			}

			// ajax request success handler
			var onUnpublishedSuccess = function LastNews_onUnpublishedSuccess(response)
			{
				// remove busy message
				this._releaseBusy();

				// reload the table data
				this._updateLastNews();
			};

			// get the url to call
			var url = Alfresco.util.blog.generatePublishingRestURL(this.options.siteId, this.options.containerId, postId);

			// execute ajax request
			Alfresco.util.Ajax.request(
			{
				url: url,
				method: "POST",
				requestContentType : "application/json",
				responseContentType : "application/json",
				dataObj:
				{
					action : "unpublish"
				},
				successMessage: this._msg("message.unpublishExternal.success"),
				successCallback:
				{
					fn: onUnpublishedSuccess,
					scope: this
				},
				failureMessage: this._msg("message.unpublishExternal.failure"),
				failureCallback:
				{
					fn: function(response)
					{
						this._releaseBusy();
					},
					scope: this
				}
			});
		},


		// row highlighting

		/**
		 * Custom event handler to highlight row.
		 *
		 * @method onEventHighlightRow
		 * @param oArgs.event {HTMLEvent} Event object.
		 * @param oArgs.target {HTMLElement} Target element.
		 */
		onEventHighlightRow: function LastNews_onEventHighlightRow(oArgs)
		{
			// only highlight if we got actions to show
			var record = this.widgets.dataTable.getRecord(oArgs.target.id);
			var permissions = record.getData('permissions');
			if (!(permissions.edit || permissions["delete"]))
			{
				return;
			}

			var elem = Dom.getElementsByClassName('post', null, oArgs.target, null);
			Dom.addClass(elem, 'overNode');
		},

		/**
		 * Custom event handler to unhighlight row.
		 *
		 * @method onEventUnhighlightRow
		 * @param oArgs.event {HTMLEvent} Event object.
		 * @param oArgs.target {HTMLElement} Target element.
		 */
		onEventUnhighlightRow: function LastNews_onEventUnhighlightRow(oArgs)
		{
			var elem = Dom.getElementsByClassName('post', null, oArgs.target, null);
			Dom.removeClass(elem, 'overNode');
		},


		/**
		 * LastNews Filter changed event handler
		 *
		 * @method onFilterChanged
		 * @param layer {object} Event fired (unused)
		 * @param args {array} Event parameters (new filterId)
		 */
		onFilterChanged: function LastNews_onFilterChanged(layer, args)
		{
			var obj = args[1];
			if ((obj !== null) && (obj.filterId !== null))
			{
				this.currentFilter =
				{
					filterId: obj.filterId,
					filterOwner: obj.filterOwner,
					filterData: obj.filterData
				};
				this._updateLastNews(
				{
					page: 1
				});
			}
		},

		/**
		 * Deactivate All Controls event handler
		 *
		 * @method onDeactivateAllControls
		 * @param layer {object} Event fired
		 * @param args {array} Event parameters (depends on event type)
		 */
		onDeactivateAllControls: function LastNews_onDeactivateAllControls(layer, args)
		{
			var widget;
			for (widget in this.widgets)
			{
				if (this.widgets.hasOwnProperty(widget))
				{
					this.widgets[widget].set("disabled", true);
				}
			}
		},

		/**
		 * Updates the list title considering the current active filter.
		 */
		updateListTitle: function LastNews_updateListTitle()
		{
			/*
			var elem = Dom.get(this.id + '-listtitle');
			var title = this._msg("title.postlist");

			var filterOwner = this.currentFilter.filterOwner;
			var filterId = this.currentFilter.filterId;
			var filterData = this.currentFilter.filterData;
			if (filterOwner == "Alfresco.LastNewsFilter")
			{
				if (filterId == "all")
				{
					 title = this._msg("title.allposts");
				}
				if (filterId == "new")
				{
					title = this._msg("title.newposts");
				}
				else if (filterId == "mydrafts")
				{
					title = this._msg("title.mydrafts");
				}
				else if (filterId == "mypublished")
				{
					title = this._msg("title.mypublished");
				}
				else if (filterId == "publishedext")
				{
					title = this._msg("title.publishedext");
				}
			}
			else if (filterOwner == "Alfresco.LastNewsTags")
			{
				title = this._msg("title.bytag", $html(filterData));
			}
			else if (filterOwner == "Alfresco.LastNewsArchive" && filterId == "bymonth")
			{
				var date = new Date(filterData.year, filterData.month, 1);
				var formattedDate = Alfresco.util.formatDate(date, "mmmm yyyy");
				title = this._msg("title.bymonth", formattedDate);
			}

			elem.innerHTML = title;
			*/
		},


		/**
		 * LastNews Refresh Required event handler
		 *
		 * @method onLastNewsRefresh
		 * @param layer {object} Event fired (unused)
		 * @param args {array} Event parameters (unused)
		 */
		onLastNewsRefresh: function LastNews_onLastNewsRefresh(layer, args)
		{
			this._updateLastNews();
		},

		/**
		 * Displays the provided busyMessage but only in case
		 * the component isn't busy set.
		 *
		 * @return true if the busy state was set, false if the component is already busy
		 */
		_setBusy: function LastNews__setBusy(busyMessage)
		{
			if (this.busy)
			{
				return false;
			}
			this.busy = true;
			this.widgets.busyMessage = Alfresco.util.PopupManager.displayMessage(
			{
				text: busyMessage,
				spanClass: "wait",
				displayTime: 0
			});
			return true;
		},

		/**
		 * Removes the busy message and marks the component as non-busy
		 */
		_releaseBusy: function LastNews__releaseBusy()
		{
			if (this.busy)
			{
				this.widgets.busyMessage.destroy();
				this.busy = false;
				return true;
			}
			else
			{
				return false;
			}
		},

		/**
		 * Gets a custom message
		 *
		 * @method _msg
		 * @param messageId {string} The messageId to retrieve
		 * @return {string} The custom message
		 * @private
		 */
		_msg: function LastNews_msg(messageId)
		{
			return Alfresco.util.message.call(this, messageId, "Alfresco.LastNews", Array.prototype.slice.call(arguments).slice(1));
		},

		/**
		 * Resets the YUI DataTable errors to our custom messages
		 * NOTE: Scope could be YAHOO.widget.DataTable, so can't use "this"
		 *
		 * @method _setDefaultDataTableErrors
		 * @param dataTable {object} Instance of the DataTable
		 */
		_setDefaultDataTableErrors: function LastNews__setDefaultDataTableErrors(dataTable)
		{
			var msg = Alfresco.util.message;
			dataTable.set("MSG_EMPTY", msg("message.empty", "Alfresco.LastNews"));
			dataTable.set("MSG_ERROR", msg("message.error", "Alfresco.LastNews"));
		},

		/**
		 * Updates blog post list by calling data webscript with current site and filter information
		 *
		 * @method _updateLastNews
		 */
		_updateLastNews: function LastNews__updateLastNews(p_obj)
		{
			// show busy message
			/*if (! this._setBusy(this._msg('message.wait')))
			{
				return;
			}*/

			// Reset the custom error messages
			this._setDefaultDataTableErrors(this.widgets.dataTable);

			// ajax request success handler
			var successHandler = function LastNews__updateLastNews_successHandler(sRequest, oResponse, oPayload)
			{
				// remove busy message
				//this._releaseBusy();

				this.widgets.dataTable.onDataReturnInitializeTable.call(this.widgets.dataTable, sRequest, oResponse, oPayload);
				//this.updateListTitle();

				// Obtenemos el html con la tabla y se lo asignamos al <div> en cuestión
				var div2 = document.getElementById(this.id + "-" + this.options.field);

				div2.innerHTML = htmlAux;

				//Vaciamos el htmlAux y el contador
				htmlAux = "";
				counter = 1;

			};

			// ajax request failure handler
			var failureHandler = function LastNews__updateLastNews_failureHandler(sRequest, oResponse)
			{
				// remove busy message
				//this._releaseBusy();

				if (oResponse.status == 401)
				{
					// Our session has likely timed-out, so refresh to offer the login page
					window.location.reload(true);
				}
				else
				{
					try
					{
						var response = YAHOO.lang.JSON.parse(oResponse.responseText);
						this.widgets.dataTable.set("MSG_ERROR", response.message);
						this.widgets.dataTable.showTableMessage(response.message, YAHOO.widget.DataTable.CLASS_ERROR);
						if (oResponse.status == 404)
						{
							// Site or container not found - deactivate controls
							YAHOO.Bubbling.fire("deactivateAllControls");
						}
					}
					catch(e)
					{
						this._setDefaultDataTableErrors(this.widgets.dataTable);
					}
				}
			};

			// get the url to call
			this.widgets.dataSource.sendRequest(this._buildLastNewsParams(p_obj || {}),
			{
				success: successHandler,
				failure: failureHandler,
				scope: this
			});
		},

		/**
		 * Build URI parameter string for doclist JSON data webscript
		 *
		 * @method _buildDocListParams
		 * @param p_obj.page {string} Page number
		 * @param p_obj.pageSize {string} Number of items per page
		 */
		_buildLastNewsParams: function LastNews__buildDocListParams(p_obj)
		{
			var params =
			{
				contentLength: this.options.maxContentLength,
				fromDate: null,
				toDate: null,
				tag: null,
				page: this.widgets.paginator.getCurrentPage() || "1",
				pageSize: this.widgets.paginator.getRowsPerPage()
			};

			// Passed-in overrides
			if (typeof p_obj == "object")
			{
				params = YAHOO.lang.merge(params, p_obj);
			}

			// calculate the startIndex param
			params.startIndex = (params.page-1) * params.pageSize;

			// check what url to call and with what parameters
			var filterOwner = this.currentFilter.filterOwner;
			var filterId = this.currentFilter.filterId;
			var filterData = this.currentFilter.filterData;

			// check whether we got a filter or not
			var url = "";
			if (filterOwner == "Alfresco.LastNewsFilter")
			{
				// latest only
				if (filterId == "all")
				{
					 url = "";
				}
				if (filterId == "new")
				{
					 url = "/new";
				}
				else if (filterId == "mydrafts")
				{
					 url = "/mydrafts";
				}
				else if (filterId == "mypublished")
				{
					 url = "/mypublished";
				}
				else if (filterId == "publishedext")
				{
					 url = "/publishedext";
				}
			}
			else if (filterOwner == "Alfresco.LastNewsTags")
			{
				params.tag = filterData;
			}
			else if (filterOwner == "Alfresco.LastNewsArchive" && filterId == "bymonth")
			{
				var fromDate = new Date(filterData.year, filterData.month, 1);
				var toDate = new Date(filterData.year, filterData.month + 1, 1);
				toDate = new Date(toDate.getTime() - 1);
				params.fromDate = fromDate.getTime();
				params.toDate = toDate.getTime();
			}

			// build the url extension
			var urlExt = "", paramName;
			for (paramName in params)
			{
				if (params[paramName] !== null)
				{
					urlExt += "&" + paramName + "=" + encodeURIComponent(params[paramName]);
				}
			}
			if (urlExt.length > 0)
			{
				urlExt = urlExt.substring(1);
			}
			return url + "?" + urlExt;
		}
	};
})();
