/**
 * 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
 */

/**
 * Destacado component
 *
 *
 * @namespace Alfresco
 * @class Alfresco.Destacado
 */

(function()
{
	/**
	 * YUI Library aliases
	 */
	var Dom = YAHOO.util.Dom,
			Event = YAHOO.util.Event,
			Element = YAHOO.util.Element;

	varhtml = Alfresco.util.encodeHTML;

	/**
	 * Destacado constructor.
	 *
	 * @param {String} htmlId The HTML id of the parent element
	 * @return {Alfresco.SiteFinder} The new SiteFinder instance
	 * @constructor
	 */
	Alfresco.Destacado = function(htmlId)
	{

		this.id = htmlId;
		this.name = "Alfresco.Destacado";
		this.currentFilter = {};

		this.widgets = {};

		/**
		 * Object literal used to generate unique tag ids
		 *
		 * @property tagId
		 * @type object
		 */

		this.tagId =
		{
			id: 0,
			tags: {}
		};

		/**
		 * The deleted link CSS style.
		 */
		this.DELETEDCLASS = "delete-link";

		/**
		 * The edited link CSS style.
		 */
		this.EDITEDCLASS = "edit-link";

		/* Register this component */
		Alfresco.util.ComponentManager.register(this);

		/* Load YUI Components */
		Alfresco.util.YUILoaderHelper.require(["button", "container", "datasource", "datatable", "paginator", "json", "resize"], this.onComponentsLoaded, this);

		YAHOO.Bubbling.on("filterDestacadoChanged", this.onfilterDestacadoChanged, this);
		YAHOO.Bubbling.on("linksListRefresh", this.onDestacadoListRefresh, this);

		this.newLinkBtn = null;
		this.changeListViewBtn = null;
		this.linksMenu = null;
	};

	Alfresco.Destacado.prototype =
	{
		/**
		 * Tells whether an action is currently ongoing.
		 *
		 * @property busy
		 * @type boolean
		 * @see _setBusy/_releaseBusy
		 */
		busy: false,

		/**
		 * Object container for initialization options
		 *
		 * @property options
		 * @type object
		 */
		options:
		{
			/**
			 * Current siteId.
			 *
			 * @property siteId
			 * @type string
			 */
			siteId: "",

			/**
			 * Initially used filter name and id.
			 */
			initialFilter: {},

			/**
			 * Number of items displayed per page
			 *
			 * @property pageSize
			 * @type int
			 */
			pageSize: 0,

			/**
			 * Flag indicating whether the list shows a detailed view or a simple one.
			 *
			 * @property simpleView
			 * @type boolean
			 */
			simpleView: false,

			/**
			 * permission delete
			 */
			permissionDelete: true,

			/**
			 * permission update
			 */
			permissionUpdate:true,

			/**
			 * Length of preview content loaded for each topic
			 */
			maxContentLength: 512,

			/**
			 * Minimal length of filter panel
			 */
			MIN_FILTER_PANEL_WIDTH: 150,

			/**
			 * Maximal length of filter panel
			 */
			MAX_FILTER_PANEL_WIDTH: 640 - ((YAHOO.env.ua.ie > 0) && (YAHOO.env.ua.ie < 7) ? 160 : 0),

			/**
			 * The pagination flag.
			 *
			 * @property: usePagination
			 * @type: boolean
			 * @default: true
			 */
			usePagination: true,

			/**
			 * Minimal height of filter panel
			 */
			MAX_FILTER_PANEL_HEIGHT: 200,

			/**
			 * ContainerId representing root container
			 *
			 * @property containerId
			 * @type string
			 */
			containerId: "",

			field: "",
			urlView: "",
			page: ""
		},

		/**
		 * 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 Destacado_setOptions(obj)
		{
			this.options = YAHOO.lang.merge(this.options, obj);
			return this;
		},

		/**
		 * Fired by YUILoaderHelper when required component script files have
		 * been loaded into the browser.
		 *
		 * @method onComponentsLoaded
		 */
		onComponentsLoaded: function Destacado_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 Destacado_onReady()
		{
			this.activate();
		},

		/** Object container for storing YUI widget instances.
		 *
		 * @property widgets
		 * @type object
		 */
		widgets: null,

		/**
		 * init DataSource
		 * @method createDataSource
		 * @return {Alfresco.Destacado} returns 'this' for method chaining
		 */
		createDataSource: function Destacado_createDataSource()
		{
			var uriResults = YAHOO.lang.substitute(Alfresco.constants.PROXY_URI + "api/links/site/{site}/{container}",
			{
				site: this.options.siteId,
				container: this.options.containerId
			});
			this.widgets.dataSource = new YAHOO.util.DataSource(uriResults);
			this.widgets.dataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
			this.widgets.dataSource.connXhrMode = 'queueRequests';
			this.widgets.dataSource.responseSchema =
			{
				resultsList: 'items',
				fields: ['name', 'title', 'description', 'url', 'tags', 'internal', 'createdOn', 'author', 'permissions'],
				metaFields:
				{
					paginationRecordOffset: 'startIndex',
					totalRecords: 'total',
					metadata: 'metadata'
				}
			};

			return this;
		},
		/**
		 * Updates the toolbar using the passed permissions
		 * @method updateToolbar
		 * @param linkPermissions {object} Container permissions
		 */
		updateToolbar: function Destacado_updateToolbar(linkPermissions)
		{
			if (linkPermissions.create === "false")
			{
				this.newLinkBtn.set("disabled", true);
			}
		},
		/**
		 * Set messages for this component.
		 *
		 * @method setMessages
		 * @param obj {object} Object literal specifying a set of messages
		 * @return {Alfresco.Destacado} returns 'this' for method chaining
		 */
		setMessages: function Destacado_setMessages(obj)
		{
			Alfresco.util.addMessages(obj, this.name);
			return this;
		},

		/**
		 * Initialise DataTable
		 *
		 * @method createDataTable
		 */
		createDataTable: function Destacado_createDataTable()
		{
			var me = this;

			var generateUserProfileUrl = function DL_generateUserProfileUrl(userName)
			{
				return Alfresco.util.uriTemplate("userpage",
				{
					userid: userName,
					pageid: "profile"
				});
			};

			/**
			 * Selector custom datacell formatter
			 *
			 * @method renderCellSelected
			 * @param elCell {object}
			 * @param oRecord {object}
			 * @param oColumn {object}
			 * @param oData {object|string}
			 */
			var renderCellSelected = function Destacado_renderCellSelected(elCell, oRecord, oColumn, oData)
			{

			};

			/**
			 * Description custom datacell formatter
			 *
			 * @method renderCellDescription
			 * @param elCell {object}
			 * @param oRecord {object}
			 * @param oColumn {object}
			 * @param oData {object|string}
			 */
			var renderCellDescription = function Destacado_renderCellDescription(elCell, oRecord, oColumn, oData)
			{
				var data = oRecord.getData();
				var name = data["title"],
					url = data["url"],
					description = data["description"],
					createdOn = data["createdOn"],
					author = data["author"],
					tags = data["tags"],
					internal = data["internal"];

				var start = description.indexOf('<img');
				img = '';
				if ( start > -1 ){
					var end = description.indexOf('/>');
					var img = description.substring(start, end + 2);
				}

				var re = new RegExp('(<img)[ ]+(src=")[^"]*\"[ ]*/>', 'g');
				description = description.replace(re,"");


				var innerHtml = "";

				innerHtml += '<li><a href="#" title="' +html(name) + '">' +html(name) + '</a></li>';
				elCell.innerHTML = innerHtml;

			};

			/**
			 * Actions custom datacell formatter
			 *
			 * @method renderCellActions
			 * @param elCell {object}
			 * @param oRecord {object}
			 * @param oColumn {object}
			 * @param oData {object|string}
			 */
			var renderCellActions = function Destacado_renderCellActions(elCell, oRecord, oColumn, oData)
			{

			};

			var columnDefinitions =
			[
				{
					key: 'title', label: 'Title', sortable: false, formatter: renderCellDescription
				}
			];

			this.widgets.paginator = new YAHOO.widget.Paginator(
			{
				containers: [this.id + "-paginator"],
				rowsPerPage: this.options.pageSize,
				initialPage: this.options.page,
				template: this._msg("pagination.template"),
				pageReportTemplate: this._msg("pagination.template.page-report"),
				previousPageLinkLabel: this._msg("pagination.previousPageLinkLabel"),
				nextPageLinkLabel: this._msg("pagination.nextPageLinkLabel")
			});

			// called by the paginator on state changes
			var handlePagination = function Destacado_handlePagination (state, dt)
			{
				me.updateDestacado(
				{
					page: state.page
				});
			};

			this.widgets.dataTable = new YAHOO.widget.DataTable(this.id + this.options.field, columnDefinitions, this.widgets.dataSource,
			{
				renderLoopSize: 32,
				initialLoad: false,
				MSG_EMPTY: '<span class="datatable-msg-empty">' + this._msg("links.empty") + '</span>'
			});

			YAHOO.widget.DataTable.CLASS_SELECTED = "links-selected-row";

			this.widgets.dataTable.doBeforeLoadData = function Destacado_doBeforeLoadData(sRequest, oResponse, oPayload)
			{
				if (oResponse.error)
				{
					try
					{
						var response = YAHOO.lang.JSON.parse(oResponse.responseText);
						me.widgets.dataTable.set("MSG_ERROR", response.message);
					}
					catch(e)
					{
					}

				}
				else if (oResponse.results && !me.options.usePagination)
				{
					this.renderLoopSize = oResponse.results.length >> YAHOO.env.ua.gecko ? 3 : 5;
				}

				// Must return true to have the "Loading..." message replaced by the error message
				return true;
			};

			// Update totalRecords on the fly with value from server
			this.widgets.dataTable.handleDataReturnPayload = function Destacado_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 Destacado_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);

			this.widgets.dataTable.subscribe("tableMsgShowEvent", function(oArgs)
			{
				// NOTE: Scope needs to be DataTable
				this._elMsgTbody.parentNode.style.width = "";
			});

			this.widgets.dataTable.set("selectionMode", "single");


			var filterObj = YAHOO.lang.merge(
			{
				filterId: "all",
				filterOwner: "Alfresco.LinkFilter",
				filterData: null
			}, this.options.initialFilter);

			YAHOO.Bubbling.fire("filterDestacadoChanged", filterObj);
		},

		/**
		* Generate a view url for a given site, link id.
		*
		* @param linkId the id/name of the link
		* @return an url to access the link
		*/
		generateDestacadoViewUrl: function Destacado_generateDestacadoViewUrl(site, container, linkId)
		{
			var url = YAHOO.lang.substitute(Alfresco.constants.URL_CONTEXT + "page/site/{site}/links-view?linkId={linkId}&listViewLinkBack=true",
			{
				site: site,
				container: container,
				linkId: linkId
			});
			return url;
		},

		/**
		 * Destacado Filter changed event handler
		 *
		 * @method onfilterDestacadoChanged
		 * @param layer {object} Event fired (unused)
		 * @param args {array} Event parameters (new filterId)
		 */
		onfilterDestacadoChanged: function Destacado_onfilterDestacadoChanged(layer, args)
		{
			var obj = args[1];
			if ((obj !== null) && (obj.filterId !== null))
			{
				this.currentFilter =
				{
					filterId: obj.filterId,
					filterOwner: obj.filterOwner,
					filterData: obj.filterData
				};
				this.updateDestacado(
				{
					page: this.options.page
				});
			}
		},

		/**
		 * Destacado Refresh Required event handler
		 *
		 * @method onDestacadoListRefresh
		 * @param layer {object} Event fired (unused)
		 * @param args {array} Event parameters (unused)
		 */
		onDestacadoListRefresh: function Destacado_onDestacadoListRefresh(layer, args)
		{
			this.updateDestacado();
		},

		/**
		 * Updates links list by calling data webscript with current site and filter information
		 *
		 * @method updateDestacado
		 */
		updateDestacado: function Destacado_updateDestacado(p_obj)
		{

			function successHandler(sRequest, oResponse, oPayload)
			{
				this.renderLinks(oResponse.results);
			}

			function failureHandler(sRequest, oResponse)
			{
				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)
						{
							YAHOO.Bubbling.fire("deactivateAllControls");
						}
					}
					catch(e)
					{
					}
				}
			}
			if ( this.widgets.dataSource != null ){
				this.widgets.dataSource.sendRequest(this._buildDestacadoParams(p_obj || {}),
				{
					success: successHandler,
					failure: failureHandler,
					scope: this
				});
		}

		},

		renderLinks: function Destacado_renderLinks(results){
			var r = results;

			var result = results[0];
			var description = result["description"];
			var url = result["url"];


			var div = Dom.get(this.id + '-' + this.options.field);
			var innerHtml = '<div class="img_container">';

			var start = description.indexOf('<img');
			img = '';
			if ( start > -1 ){
					var end = description.indexOf('/>');
					var img = description.substring(start, end + 2);
			}
			var re = new RegExp('(<img)[ ]+(src=")[^"]*\"[ ]*/>', 'g');
			description = description.replace(re,"");

			innerHtml += img;
			if (this.options.hiddeLink) {
				// No hacer nada.
			} else {
				innerHtml += '<a href="' + url + '" title="Ir" class="btn_ir"><span class="hide">Ir</span></a>';
			}

			innerHtml += '</div>';

			if (result.permissions['edit'])
			{
				var prefix = result.name;
				innerHtml += "<div class='onEditLink'><a id='edit-" + prefix + "' class='link-action-link-div'><span>" + this._msg("links.edit") + "</a></span></div>";
			}

			div.innerHTML = innerHtml;
		},

		/**
		 * Deactivate All Controls event handler
		 *
		 * @method onDeactivateAllControls
		 * @param layer {object} Event fired
		 * @param args {array} Event parameters (depends on event type)
		 */
		onDeactivateAllControls: function Destacado_onDeactivateAllControls(layer, args)
		{
			for (var widget in this.widgets)
			{
				if (widget)
				{
					this.widgets[widget].set("disabled", true);
				}
			}
		},

		onEditLink: function Links_onEditLink(linkId)
		{

			window.location = YAHOO.lang.substitute(Alfresco.constants.URL_CONTEXT + "page?p=destacado-linkedit&linkId={linkId}" ,
			{
				site: this.options.siteId,
				linkId: linkId
			});
		},

		/**
		 * activation of components
		 * @method activate.
		 */
		activate: function Destacado_activate()
		{
			var me = this;

			// Hook action events.
			var fnActionHandlerDiv = function Links_fnActionHandlerDiv(layer, args)
			{
				var owner = YAHOO.Bubbling.getOwnerByTagName(args[1].anchor, "div");
				if (owner !== null)
				{
					var action = "";
					action = owner.className;

					var ini = args[1].el.id.indexOf('-');
					var linkId = args[1].el.id.substring(ini + 1, args[1].el.id.length);
					me[action].call(me, linkId);
					args[1].stop = true;

				}
				return true;
			};
			YAHOO.Bubbling.addDefaultAction("link-action-link-div", fnActionHandlerDiv);

			this.createDataSource();

			this.createDataTable();
		},

		/**
		 * topic list resize event handler
		 * @method onTopicListResize.
		 * @param width {int}
		 */
		onTopicListResize: function Destacado_onTopicListResize(width)
		{
			if (width)
			{
				Dom.setStyle(Dom.get("divLinkFilters"), "height", "auto");
				Dom.setStyle(Dom.get("divLinkList"), "margin-left", width + 3 + "px");
			}
		},

		/**
		* menu item event handler
		* @method onMenuItemClick.
		* @param sType, aArgs, p_obj
		*/
		onMenuItemClick: function Destacado_onMenuItemClick(sType, aArgs, p_obj)
		{
			var me = this;
			switch (aArgs[1]._oAnchor.className.split(" ")[0])
			{
				case "delete-item":
					var callback = function()
					{
						var arrDestacado = me.getSelectedDestacado();
						me.deleteDestacado(arrDestacado);
					};
					this.showConfirmDialog(this._msg("dialog.confirm.message.delete.selected"), callback);
					break;

				case "deselect-item":
					this.deselectAll();
					this.linksMenu.set("disabled", true);
					break;
			}

		},

		/**
		* deselect all links
		* @method deselectAll.
		* @param no params
		*/
		deselectAll: function Destacado_deselectAll()
		{
			var rows = this.widgets.dataTable.getTbodyEl().rows;
			for (var i = 0; i < rows.length; i++)
			{
				rows[i].cells[0].getElementsByTagName('input')[0].checked = false;

			}
		},

		/**
		 * init links buttons
		 * @method attachButtons.
		 */
		attachButtons: function Destacado_attachButtons()
		{
			var me = this;
			this.newLinkBtn = Alfresco.util.createYUIButton(this, "create-link-button", this.showCreateLinkDlg,
			{
				disabled: false,
				value: "create"
			});

			this.linksMenu = Alfresco.util.createYUIButton(this, "selected-i-dd", this.onMenuItemClick,
			{
				disabled: true,
				type: "menu",
				menu:"selectedItems-menu"
			});

			this.changeListViewBtn = Alfresco.util.createYUIButton(this, "viewMode-button", this.changeListView,
			{
			});

			this.linksSelectMenu = Alfresco.util.createYUIButton(this, "select-button", this.onSelectItemClick,
			{
				type: "menu",
				menu: "selecItems-menu"
			});

			this.widgets.rssFeed = Alfresco.util.createYUIButton(this, "rss-feed", null,
			{
				type: "link"
			});

			this.widgets.rssFeed.set("href", this._generateRSSFeedUrl());
		},

		/**
		 * Handler on Menu Item Click
		 * @param sType
		 * @param aArgs
		 * @param p_obj
		 * @method onSelectItemClick
		 */
		onSelectItemClick: function Destacado_onSelectItemClick(sType, aArgs, p_obj)
		{
			var elem = YAHOO.env.ua.ie ? aArgs[0].srcElement : aArgs[0].target;
			if (elem.tagName.toLocaleLowerCase() != "span")
			{
				elem = elem.getElementsByTagName("span")[0];
			}
			switch (elem.className.split(" ")[0])
			{
				case "links-action-deselect-all":
					this.deselectAll();
					this.linksMenu.set("disabled", true);
					break;

				case "links-action-select-all":
					this.selectAll();
					this.linksMenu.set("disabled", !this.getSelectedDestacado().length);
					break;

				case "links-action-invert-selection":
					this.invertAll();
					break;
			}
		},

		/**
		 * Invert All Selection on the page
		 * @method invertAll
		 */
		invertAll: function Destacado_invertAll()
		{
			var isDisable = false;
			var rows = this.widgets.dataTable.getTbodyEl().rows;
			for (var i = 0; i < rows.length; i++)
			{
				var ipt = rows[i].cells[0].getElementsByTagName('input')[0];
				ipt.checked = !ipt.checked;
				isDisable = ipt.checked ? true : isDisable;
			}
			this.linksMenu.set("disabled", !isDisable);
		},

		/**
		 * select All Tags on the page
		 * @method selectAll
		 */
		selectAll: function Destacado_selectAll()
		{
			var rows = this.widgets.dataTable.getTbodyEl().rows;
			for (var i = 0; i < rows.length; i++)
			{
				rows[i].cells[0].getElementsByTagName('input')[0].checked = true;
			}
		},

		/**
		 * show 'Create Link' dialog
		 * @method showCreateLinkDlg.
		 */
		showCreateLinkDlg: function Destacado_showCreateLinkDlg()
		{
			var url = YAHOO.lang.substitute(Alfresco.constants.URL_CONTEXT + "page/site/{site}/links-linkedit",
			{
				site: this.options.siteId
			});
			window.location = url;
		},

		/**
		 * change list view
		 * @method changeListView.
		 */
		changeListView: function Destacado_changeListView()
		{
			var records = this.widgets.dataTable.getRecordSet().getRecords();
			var rows = this.widgets.dataTable.getTbodyEl().rows;
			var colDefinitions = this.widgets.dataTable.getColumnSet().getDefinitions();

			this.options.simpleView = !this.options.simpleView;
			var j = 0;
			for (var i in records)
			{
				if (i)
				{
					colDefinitions[1].formatter.call(this, rows[j].cells[1].firstChild, records[i]);
					j++;
				}
			}
			this.changeListViewBtn.set("label", this._msg(this.options.simpleView ? "header.detailedList" : "header.simpleList"));
		},

		/**
		 * @method deleteDestacado
		 * @param arr {array}
		 */
		deleteDestacado: function Destacado_deleteDestacado(arr)
		{
			var me = this;
			if (!this._setBusy(this._msg('message.wait')))
			{
				return;
			}

			// get the url to call
			var ids = [];
			for (var i in arr)
			{
				if (i)
				{
					ids.push(arr[i].getData().name);
				}
			}

			var url = YAHOO.lang.substitute(Alfresco.constants.PROXY_URI + "api/links/delete/site/{site}/{container}",
			{
				site: this.options.siteId,
				container: this.options.containerId
			});

			// ajax request success handler
			var onDeletedSuccess = function Destacado_deleteLinkConfirm_onDeletedSuccess(response)
			{
				// remove busy message
				this._releaseBusy();

				// reload the table data
				this.updateDestacado();
				YAHOO.Bubbling.fire("tagRefresh");
			};

			// execute ajax request
			Alfresco.util.Ajax.request(
			{
				url: url,
				method: "POST",
				requestContentType: "application/json",
				successMessage: this._msg("message.delete.success"),
				successCallback:
				{
					fn: onDeletedSuccess,
					scope: this
				},
				failureMessage: this._msg("message.delete.failure"),
				failureCallback:
				{
					fn: function(response)
					{
						response.config.failureMessage = YAHOO.lang.JSON.parse(response.serverResponse.responseText).message;
						this._releaseBusy();
					},
					scope: this
				},
				dataObj:
				{
					items: ids
				}
			});

		},

		/**
		 * Adds the link.
		 *
		 * @param rowData {object} the row's data.
		 * @method createLink.
		 */
		createLink: function Destacado_createLink(data)
		{
			this.updateDestacado(
			{
				page: 1
			});
		},

		/**
		 * Updates the link.
		 *
		 * @param rowData {object} the row's data.
		 * @param row {YAHOO.widget.Record}.
		 * @method updateLink.
		 */
		onUpdateLink: function Destacado_onUpdateLink(rowData, row)
		{
			this.updateDestacado();

		},

		/**
		 * Show delete confirm dialog.
		 * @param row {YAHOO.widget.Record} the row which needs for delete.
		 */
		showConfirmDialog: function Destacado_showConfirmDialog(mes, callback)
		{
			var me = this;

			var prompt = Alfresco.util.PopupManager.displayPrompt(
			{
				text: mes,
				buttons: [
				{
					text: this._msg("button.delete"),
					handler: function()
					{
						callback();
						this.destroy();
					}
				},
				{
					text: this._msg("button.cancel"),
					handler: function()
					{
						this.destroy();
					},
					isDefault: true
				}]
			});
		},

		/**
		 * Gets the array of selected links.
		 *
		 * @method getSelectedDestacado
		 */
		getSelectedDestacado: function Destacado_getSelectedDestacado()
		{
			var arr = [];
			var rows = this.widgets.dataTable.getTbodyEl().rows;
			for (var i = 0; i < rows.length; i++)
			{
				if (rows[i].cells[0].getElementsByTagName('input')[0].checked)
				{
					var data = this.widgets.dataTable.getRecord(i);
					if (data)
					{
						arr.push(data);
					}
				}
			}

			return arr;
		},

		/**
		 * PRIVATE FUNCTIONS
		 */

		/**
		 * activation of resize
		 * @method _attachResize.
		 */
		_attachResize: function Destacado__attachResize()
		{
			this.widgets.horizResize = new YAHOO.util.Resize("divLinkFilters",
			{
				handles: ["r"],
				minWidth: this.options.MIN_FILTER_PANEL_WIDTH,
				maxWidth: this.options.MAX_FILTER_PANEL_WIDTH
			});


			this.widgets.horizResize.on("resize",
					function(eventTarget)
					{
						this.onTopicListResize(eventTarget.width);
					}, this, true);

			this.widgets.horizResize.resize(null, null, this.options.MIN_FILTER_PANEL_WIDTH, 0, 0, true);
		},

		/**
		 * Generate ID alias for tag, suitable for DOM ID attribute
		 *
		 * @method _generateTagId
		 * @param tagName {string} Tag name
		 * @return {string} A unique DOM-safe ID for the tag
		 */
		_generateTagId: function Destacado__generateTagId(tagName)
		{
			var id = 0;
			var tagId = this.tagId;
			if (tagName in tagId.tags) {
				id = tagId.tags[tagName];
			}
			else
			{
				tagId.id++;
				id = tagId.tags[tagName] = tagId.id;
			}
			return this.id + "-tagId-" + id;
		},

		/**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
		 */
		_buildDestacadoParams: function Destacado_buildDestacadoParams(p_obj)
		{
			var params =
			{
				contentLength: this.options.maxContentLength,
				fromDate: null,
				toDate: null,
				tag: null,
				page: this.options.page,
				pageSize: this.options.pageSize
			};

			// 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.LinkFilter")
			{
				switch (filterId)
				{
					case "all":
						url = "?filter=all";
						break;
					case "user":
						url = "?filter=user";
						break;
					case "recent":
						url = "?filter=recent";
						break;
				}
			}
			else if (filterOwner == "Alfresco.LinkTags")
			{
				url = "?filter=tag";
				params.tag = filterData;
			}

			// build the url extension
			var urlExt = "";
			for (var paramName in params)
			{
				if (params[paramName] !== null)
				{
					urlExt += "&" + paramName + "=" + encodeURIComponent(params[paramName]);
				}
			}
			if (urlExt.length > 0)
			{
				urlExt = urlExt.substring(1);
			}
			return url + "&" + urlExt;

		},

		/**
		 * Gets a custom message
		 *
		 * @method _msg
		 * @param messageId {string} The messageId to retrieve
		 * @return {string} The custom message
		 * @private
		 */
		_msg: function Destacado_msg(messageId)
		{
			return Alfresco.util.message.call(this, messageId, this.name, Array.prototype.slice.call(arguments).slice(1));
		},

		/**
		 * Init the 'Create Link' dialog.
		 *
		 * @method _initCreateLinkDialog.
		 */
		_initCreateLinkDialog: function Destacado_initCreateLinkDialog()
		{
			this.widgets.createLinkDlg = new Alfresco.DestacadoEditDialog(this.id + "-editdlg");
			this.widgets.createLinkDlg.setOptions(
			{
				siteId:this.options.siteId,
				containerId:this.options.containerId,
				templateUrl: Alfresco.constants.URL_SERVICECONTEXT + "components/links/modaldialogs/edit-dialog"
			});
			this.widgets.createLinkDlg.init();
		},

		/**
		 * Removes the busy message and marks the component as non-busy
		 */
		_releaseBusy: function Destacado_releaseBusy()
		{
			if (this.busy)
			{
				this.widgets.busyMessage.destroy();
				this.busy = false;
				return true;
			}
			else
			{
				return false;
			}
		},

		/**
		 * 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 Destacado__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;
		},

		/**
		 * Generate the html markup for a tag link.
		 *
		 * @method _generateTagLink
		 * @param tagName {string} the tag to create a link for
		 * @return {string} the markup for a tag
		 */
		_generateTagLink: function Destacado_generateTagLink(tagName)
		{
			var encodedTagName =html(tagName);
			var html = '';
			html += '<span id="' + this._generateTagId(tagName) + '" class="nodeAttrValue">';
			html += '<a href="#" class="tag-link" title="' + encodedTagName + '">';
			html += '<span>' + encodedTagName + '</span>';
			html += '</a>';
			html += '</span>';
			return html;
		},

		/**
		 * Generates the HTML mark-up for the RSS feed link
		 *
		 * @method _generateRSSFeedUrl
		 * @private
		 */
		_generateRSSFeedUrl: function Destacado__generateRSSFeedUrl()
		{
				var url = YAHOO.lang.substitute(Alfresco.constants.URL_CONTEXT + "service/components/links/rss?site={site}",
				{
					site: this.options.siteId
				});

		 return url;
		}
	};
})();