/**
 * 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
 */
 
/**
 * Last3News component.
 * 
 * @namespace Alfresco
 * @class Alfresco.Last3News
 */
(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;
    
    
   /**
    * Last3News constructor.
    * 
    * @param {String} htmlId The HTML id of the parent element
    * @return {Alfresco.Last3News} The new Last3News instance
    * @constructor
    */
   Alfresco.Last3News = function(htmlId)
   {
      /* Mandatory properties */
      this.name = "Alfresco.Last3News";
      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("Last3NewsRefresh", this.onLast3NewsRefresh, this);
      
      return this;
   };
   
   Alfresco.Last3News.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: ''
      },
      
      /**
       * 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 Last3News_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 Last3News_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 Last3News_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 Last3News_onReady()
      {
         // Reference to self used by inline functions
         var me = this;        

         // called by the paginator on state changes
         var handlePagination = function Last3News_handlePagination(state, dt)
         {
            //me.currentPage = state.page;
            me._updateLast3News(
            {
               page: state.page
            });
         };

         // YUI Paginator definition
         this.widgets.paginator = new YAHOO.widget.Paginator(
         {
            containers: [this.id + "-paginator"],
            rowsPerPage: 3,
            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 Last3News_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 Last3News_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 uriLast3News = 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(uriLast3News);
         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 Last3News_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 )
            	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 Last3News_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 = oResponse.results.length >> YAHOO.env.ua.gecko ? 3 : 5;
            }            
            
            // 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.Last3NewsFilter",
            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 Last3News_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 Last3News_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("Last3NewsRefresh");
         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 Last3News_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 Last3News_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 Last3News_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 Last3News_onDeleteBlogPost_delete()
               {
                  this.destroy();
                  me._deleteBlogPostConfirm.call(me, record.getData('name'));
               }
            },
            {
               text: this._msg("button.cancel"),
               handler: function Last3News_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 Last3News_onBlogConfigChanged(layer, args)
      {
         // refresh the list
         this._updateLast3News();
      },
      
      // Actions implementation
      
      /**
       * Blog post deletion implementation
       * 
       * @method _deleteBlogPostConfirm
       * @param postId {string} the id of the blog post to delete
       */
      _deleteBlogPostConfirm: function Last3News__deleteBlogPostConfirm(postId)
      {
         // show busy message
         if (! this._setBusy(this._msg('message.wait')))
         {
            return;
         }
          
         // ajax request success handler
         var onDeletedSuccess = function Last3News_deleteBlogPostConfirm_onDeletedSuccess(response)
         {
            // remove busy message
            this._releaseBusy();
            
            // reload the table data
            this._updateLast3News();
         };
         
         // 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 Last3News__publishExternal(postId)
      {
         // show busy message
         if (! this._setBusy(this._msg('message.wait')))
         {
            return;
         }
          
         // ajax call success handler
         var onPublishedSuccess = function Last3News_onPublishedSuccess(response)
         {
            // remove busy message
            this._releaseBusy();
            
            // reload the table data
            this._updateLast3News();
         };
         
         // 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 Last3News__updateExternal(postId)
      {
         // show busy message
         if (! this._setBusy(this._msg('message.wait')))
         {
            return;
         }
          
         // ajax request success handler
         var onUpdatedSuccess = function Last3News_onUpdatedSuccess(response)
         {
            // remove busy message
            this._releaseBusy();
             
            // reload the table data
            this._updateLast3News();
         };
         
         // 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 Last3News__onUnpublishExternal(postId)
      {
         // show busy message
         if (! this._setBusy(this._msg('message.wait')))
         {
            return;
         }
          
         // ajax request success handler
         var onUnpublishedSuccess = function Last3News_onUnpublishedSuccess(response)
         {
            // remove busy message
            this._releaseBusy();
             
            // reload the table data
            this._updateLast3News();
         };
          
         // 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 Last3News_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 Last3News_onEventUnhighlightRow(oArgs)
      {
         var elem = Dom.getElementsByClassName('post', null, oArgs.target, null);
         Dom.removeClass(elem, 'overNode');
      },
      
      
      /**
       * Last3News Filter changed event handler
       *
       * @method onFilterChanged
       * @param layer {object} Event fired (unused)
       * @param args {array} Event parameters (new filterId)
       */
      onFilterChanged: function Last3News_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._updateLast3News(
            {
               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 Last3News_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 Last3News_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.Last3NewsFilter")
         {
            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.Last3NewsTags")
         {
            title = this._msg("title.bytag", $html(filterData));
         }
         else if (filterOwner == "Alfresco.Last3NewsArchive" && 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;
         */
      },


      /**
       * Last3News Refresh Required event handler
       *
       * @method onLast3NewsRefresh
       * @param layer {object} Event fired (unused)
       * @param args {array} Event parameters (unused)
       */
      onLast3NewsRefresh: function Last3News_onLast3NewsRefresh(layer, args)
      {
         this._updateLast3News();
      },

      /**
       * 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 Last3News__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 Last3News__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 Last3News_msg(messageId)
      {
         return Alfresco.util.message.call(this, messageId, "Alfresco.Last3News", 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 Last3News__setDefaultDataTableErrors(dataTable)
      {
         var msg = Alfresco.util.message;
         dataTable.set("MSG_EMPTY", msg("message.empty", "Alfresco.Last3News"));
         dataTable.set("MSG_ERROR", msg("message.error", "Alfresco.Last3News"));
      },
      
      /**
       * Updates blog post list by calling data webscript with current site and filter information
       *
       * @method _updateLast3News
       */
      _updateLast3News: function Last3News__updateLast3News(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 Last3News__updateLast3News_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 Last3News__updateLast3News_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._buildLast3NewsParams(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
       */
      _buildLast3NewsParams: function Last3News__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.Last3NewsFilter")
         {
            // 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.Last3NewsTags")
         {
            params.tag = filterData;
         }
         else if (filterOwner == "Alfresco.Last3NewsArchive" && 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;
      }
   };
})();
