1 /*global window: true, GCN: true, jQuery: true*/
  2 (function (GCN) {
  3 
  4 	'use strict';
  5 
  6 	/**
  7 	 * Searches for the an Aloha editable object of the given id.
  8 	 *
  9 	 * @TODO: Once Aloha.getEditableById() is patched to not cause an
 10 	 *        JavaScript exception if the element for the given ID is not found
 11 	 *        then we can deprecate this function and use Aloha's instead.
 12 	 *
 13 	 * @static
 14 	 * @param {string} id Id of Aloha.Editable object to find.
 15 	 * @return {Aloha.Editable=} The editable object, if wound; otherwise null.
 16 	 */
 17 	function getAlohaEditableById(id) {
 18 		var Aloha = (typeof window !== 'undefined') && window.Aloha;
 19 		if (!Aloha) {
 20 			return null;
 21 		}
 22 
 23 		// If the element is a textarea then route to the editable div.
 24 		var element = jQuery('#' + id);
 25 		if (element.length &&
 26 				element[0].nodeName.toLowerCase() === 'textarea') {
 27 			id += '-aloha';
 28 		}
 29 
 30 		var editables = Aloha.editables;
 31 		var j = editables.length;
 32 		while (j) {
 33 			if (editables[--j].getId() === id) {
 34 				return editables[j];
 35 			}
 36 		}
 37 
 38 		return null;
 39 	}
 40 
 41 	/**
 42 	 * Helper function to normalize the arguments that can be passed to the
 43 	 * `edit()' and `render()' methods.
 44 	 *
 45 	 * @private
 46 	 * @static
 47 	 * @param {arguments} args A list of arguments.
 48 	 * @return {object} Object containing an the properties `element',
 49 	 *                  `success', `error', `data' and `post'.
 50 	 */
 51 	function getRenderOptions(args) {
 52 		var argv = Array.prototype.slice.call(args);
 53 		var argc = args.length;
 54 		var arg;
 55 		var i;
 56 
 57 		var element;
 58 		var success;
 59 		var error;
 60 		var prerenderedData = false;
 61 		var post = false;
 62 
 63 		for (i = 0; i < argc; ++i) {
 64 			arg = argv[i];
 65 
 66 			switch (jQuery.type(arg)) {
 67 			case 'string':
 68 				element = jQuery(arg);
 69 				break;
 70 			case 'object':
 71 				if (element) {
 72 					prerenderedData = arg;
 73 				} else {
 74 					element = arg;
 75 				}
 76 				break;
 77 			case 'function':
 78 				if (success) {
 79 					error = arg;
 80 				} else {
 81 					success = arg;
 82 				}
 83 				break;
 84 			case 'boolean':
 85 				post = arg;
 86 				break;
 87 			// Descarding all other types of arguments...
 88 			}
 89 		}
 90 
 91 		return {
 92 			element : element,
 93 			success : success,
 94 			error   : error,
 95 			data    : prerenderedData,
 96 			post    : post
 97 		};
 98 	}
 99 
100 	/**
101 	 * Exposes an API to operate on a Content.Node tag.
102 	 *
103 	 * @class
104 	 * @name TagAPI
105 	 */
106 	var TagAPI = GCN.defineChainback({
107 
108 		__chainbacktype__: 'TagAPI',
109 
110 		/**
111 		 * Type of the object
112 		 * 
113 		 * @type {string}
114 		 */
115 		_type: 'tag',
116 
117 		/**
118 		 * A reference to the object in which this tag is contained.  This value
119 		 * is set during initialization.
120 		 *
121 		 * @type {GCN.ContentObject}
122 		 */
123 		_parent: null,
124 
125 		/**
126 		 * Name of this tag.
127 		 *
128 		 * @type {string}
129 		 */
130 		_name: null,
131 
132 		/**
133 		 * Gets this tag's information from the object that contains it.
134 		 *
135 		 * @param {function(TagAPI)} success Callback to be invoked when this
136 		 *                                   operation completes normally.
137 		 * @param {function(GCNError):boolean} error Custom error handler.
138 		 */
139 		'!_read': function (success, error) {
140 			var parent = this.parent();
141 			// Because tags always retrieve their data from a parent object,
142 			// this tag is only completely fetched if it's parent is also fetch.
143 			// The parent could have been cleared of all it's data using
144 			// _clearCache() while this tag was left in a _fetched state, so we
145 			// need to check.
146 			if (this._fetched && parent._fetched) {
147 				if (success) {
148 					this._invoke(success, [this]);
149 				}
150 				return;
151 			}
152 
153 			// Because when loading folders via folder(1).folders() will
154 			// fetch them without any tag data.  We therefore have to refetch
155 			// them wit their tag data.
156 			if (parent._fetched && !parent._data.tags) {
157 				parent._data.tags = {};
158 				parent.fetch(function (response) {
159 					if (GCN.getResponseCode(response) !== 'OK') {
160 						GCN.handleResponseError(response);
161 						return;
162 					}
163 					var newTags = {};
164 					jQuery.each(
165 						response[parent._type].tags,
166 						function (name, data) {
167 							if (!GCN.TagContainerAPI.hasTagData(parent, name)) {
168 								newTags[name] = data;
169 							}
170 						}
171 					);
172 					GCN.TagContainerAPI.extendTags(parent, newTags);
173 					parent._read(success, error);
174 				});
175 				return;
176 			}
177 
178 			var that = this;
179 
180 			// Take the data for this tag from it's container.
181 			parent._read(function () {
182 				that._data = parent._getTagData(that._name);
183 
184 				if (!that._data) {
185 					var err = GCN.createError('TAG_NOT_FOUND',
186 						'Could not find tag "' + that._name + '" in ' +
187 						parent._type + " " + parent._data.id, that);
188 					GCN.handleError(err, error);
189 					return;
190 				}
191 
192 				that._fetched = true;
193 
194 				if (success) {
195 					that._invoke(success, [that]);
196 				}
197 			}, error);
198 		},
199 
200 		/**
201 		 * Retrieve the object in which this tag is contained.  It does so by
202 		 * getting this chainback's "chainlink ancestor" object.
203 		 *
204 		 * @function
205 		 * @name parent
206 		 * @memberOf TagAPI
207 		 * @return {GCN.AbstractTagContainer}
208 		 */
209 		'!parent': function () {
210 			return this._ancestor();
211 		},
212 
213 		/**
214 		 * Initialize a tag object. Unlike other chainback objects, tags will
215 		 * always have a parent. If its parent have been loaded, we will
216 		 * immediately copy the this tag's data from the parent's `_data' object
217 		 * to the tag's `_data' object.
218 		 *
219 		 * @param {string|object}
220 		 *            settings
221 		 * @param {function(TagAPI)}
222 		 *            success Callback to be invoked when this operation
223 		 *            completes normally.
224 		 * @param {function(GCNError):boolean}
225 		 *            error Custom error handler.
226 		 */
227 		_init: function (settings, success, error) {
228 			if (jQuery.type(settings) === 'object') {
229 				this._name    = settings.name;
230 				this._data    = settings;
231 				this._data.id = settings.id;
232 				this._fetched = true;
233 			} else {
234 				// We don't want to reinitalize the data object when it
235 				// has not been fetched yet.
236 				if (!this._fetched) {
237 					this._data = {};
238 					this._data.id = this._name = settings;
239 				}
240 			}
241 
242 			if (success) {
243 				var that = this;
244 
245 				this._read(function (container) {
246 					that._read(success, error);
247 				}, error);
248 
249 			// Even if not success callback is given, read this tag's data from
250 			// is container, if that container has the data available.
251 			// If we are initializing a placeholder tag object (in the process
252 			// of creating brand new tag, for example), then its parent
253 			// container will not have any data for this tag yet.  We know that
254 			// we are working with a placeholder tag if no `_data.id' or `_name'
255 			// property is set.
256 			} else if (!this._fetched && this._name &&
257 			           this.parent()._fetched) {
258 				this._data = this.parent()._getTagData(this._name);
259 				this._fetched = !!this._data;
260 
261 			// We are propably initializing a placholder object, we will assign
262 			// it its own `_data' and `_fetched' properties so that it is not
263 			// accessing the prototype values.
264 			} else if (!this._fetched) {
265 				this._data = {};
266 				this._data.id = this._name = settings;
267 				this._fetched = false;
268 			}
269 		},
270 
271 		/**
272 		 * Gets or sets a property of this tags. Note that tags do not have a
273 		 * `_shadow' object, and we update the `_data' object directly.
274 		 *
275 		 * @function
276 		 * @name prop
277 		 * @memberOf TagAPI
278 		 * @param {string}
279 		 *            name Name of tag part.
280 		 * @param {*=}
281 		 *            set Optional value. If provided, the tag part will be
282 		 *            replaced with this value.
283 		 * @return {*} The value of the accessed tag part.
284 		 * @throws UNFETCHED_OBJECT_ACCESS
285 		 */
286 		'!prop': function (name, value) {
287 			var parent = this.parent();
288 
289 			if (!this._fetched) {
290 				GCN.error('UNFETCHED_OBJECT_ACCESS',
291 					'Calling method `prop()\' on an unfetched object: ' +
292 					parent._type + " " + parent._data.id, this);
293 
294 				return;
295 			}
296 
297 			if (jQuery.type(value) !== 'undefined') {
298 				this._data[name] = value;
299 				parent._update('tags.' + GCN.escapePropertyName(this.prop('name')),
300 					this._data);
301 			}
302 
303 			return this._data[name];
304 		},
305 
306 		/**
307 		 * <p>
308 		 * Gets or sets a part of a tag.
309 		 *
310 		 * <p>
311 		 * There exists different types of tag parts, and the possible value of
312 		 * each kind of tag part may differ.
313 		 *
314 		 * <p>
315 		 * Below is a list of possible kinds of tag parts, and references to
316 		 * what the possible range their values can take:
317 		 *
318 		 * <pre>
319 		 *      STRING : {@link TagParts.STRING}
320 		 *    RICHTEXT : {@link TagParts.RICHTEXT}
321 		 *     BOOLEAN : {@link TagParts.BOOLEAN}
322 		 *       IMAGE : {@link TagParts.IMAGE}
323 		 *        FILE : {@link TagParts.FILE}
324 		 *      FOLDER : {@link TagParts.FOLDER}
325 		 *        PAGE : {@link TagParts.PAGE}
326 		 *    OVERVIEW : {@link TagParts.OVERVIEW}
327 		 *     PAGETAG : {@link TagParts.PAGETAG}
328 		 * TEMPLATETAG : {@link TagParts.TEMPLATETAG}
329 		 *      SELECT : {@link TagParts.SELECT}
330 		 * MULTISELECT : {@link TagParts.MULTISELECT}
331 		 * </pre>
332 		 *
333 		 * @function
334 		 * @name part
335 		 * @memberOf TagAPI
336 		 *
337 		 * @param {string} name Name of tag opart.
338 		 * @param {*=} value (optional)
339 		 *             If provided, the tag part will be update with this
340 		 *             value.  How this happens differs between different type
341 		 *             of tag parts.
342 		 * @return {*} The value of the accessed tag part.  Null if the part
343 		 *             does not exist.
344 		 * @throws UNFETCHED_OBJECT_ACCESS
345 		 */
346 		'!part': function (name, value) {
347 			if (!this._fetched) {
348 				var parent = this.parent();
349 
350 				GCN.error(
351 					'UNFETCHED_OBJECT_ACCESS',
352 					'Calling method `prop()\' on an unfetched object: '
353 						+ parent._type + " " + parent._data.id,
354 					this
355 				);
356 
357 				return null;
358 			}
359 
360 			var part = this._data.properties[name];
361 
362 			if (!part) {
363 				return null;
364 			}
365 
366 			if (jQuery.type(value) === 'undefined') {
367 				return GCN.TagParts.get(part);
368 			}
369 
370 			var partValue = GCN.TagParts.set(part, value);
371 
372 			// Each time we perform a write operation on a tag, we will update
373 			// the tag in the tag container's `_shadow' object as well.
374 			this.parent()._update(
375 				'tags.' + GCN.escapePropertyName(this._name),
376 				this._data
377 			);
378 
379 			return partValue;
380 		},
381 
382 		/**
383 		 * Returns a list of all of this tag's parts.
384 		 *
385 		 * @function
386 		 * @memberOf TagAPI
387 		 * @name     parts
388 		 * @param    {string} name
389 		 * @return   {Array.<string>}
390 		 */
391 		'!parts': function (name) {
392 			var parts = [];
393 			jQuery.each(this._data.properties, function (key) {
394 				parts.push(key);
395 			});
396 			return parts;
397 		},
398 
399 		/**
400 		 * Remove this tag from its containing object (it's parent).
401 		 *
402 		 * @function
403 		 * @memberOf TagAPI
404 		 * @name remove
405 		 * @param {function} callback A function that receive this tag's parent
406 		 *                            object as its only arguments.
407 		 */
408 		remove: function (success, error) {
409 			var parent = this.parent();
410 
411 			if (!parent.hasOwnProperty('_deletedTags')) {
412 				parent._deletedTags = [];
413 			}
414 
415 			GCN.pub('tag.before-deleted', {tag: this});
416 
417 			parent._deletedTags.push(this._name);
418 
419 			if (parent._data.tags &&
420 					parent._data.tags[this._name]) {
421 				delete parent._data.tags[this._name];
422 			}
423 
424 			if (parent._shadow.tags &&
425 					parent._shadow.tags[this._name]) {
426 				delete parent._shadow.tags[this._name];
427 			}
428 
429 			parent._removeAssociatedTagData(this._name);
430 
431 			this._clearCache();
432 
433 			if (success) {
434 				parent._persist(null, success, error);
435 			}
436 		},
437 
438 		/**
439 		 * Given a DOM element, will generate a template which represents this
440 		 * tag as it would be if rendered in the element.
441 		 *
442 		 * @param {jQuery.<HTMLElement>} $element DOM element with which to
443 		 *                                        generate the template.
444 		 * @return {string} Template string.
445 		 */
446 		'!_makeTemplate': function ($element) {
447 			if (0 === $element.length) {
448 				return '<node ' + this._name + '>';
449 			}
450 			var placeholder =
451 					'-{(' + this.parent().id() + ':' + this._name + ')}-';
452 			var template = jQuery.trim(
453 					$element.clone().html(placeholder)[0].outerHTML
454 				);
455 			return template.replace(placeholder, '<node ' + this._name + '>');
456 		},
457 
458 		/**
459 		 * Will render this tag in the given render `mode'.  If an element is
460 		 * provided, the content will be placed in that element.  If the `mode'
461 		 * is "edit", any rendered editables will be initialized for Aloha
462 		 * Editor.  Any editable that are rendered into an element will also be
463 		 * added to the tag's parent object's `_editables' array so that they
464 		 * can have their changed contents copied back into their corresponding
465 		 * tags during saving.
466 		 *
467 		 * @param {string} mode The rendering mode.  Valid values are "view",
468 		 *                      and "edit".
469 		 * @param {jQuery.<HTMLElement>} element DOM element into which the
470 		 *                                       the rendered content should be
471 		 *                                       placed.
472 		 * @param {function(string, TagAPI, object)} Optional success handler.
473 		 * @param {function(GCNError):boolean} Optional custom error handler.
474 		 * @param {boolean} post flag to POST the data for rendering
475 		 */
476 		'!_render': function (mode, $element, success, error, post) {
477 			var tag = this._fork();
478 			tag._read(function () {
479 				var template = ($element && $element.length)
480 				             ? tag._makeTemplate($element)
481 				             : '<node ' + tag._name + '>';
482 
483 				var obj = tag.parent();
484 				var renderHandler = function (data) {
485 					// Because the parent content object needs to track any
486 					// blocks or editables that have been rendered in this tag.
487 					obj._processRenderedTags(data);
488 
489 					GCN._handleContentRendered(data.content, tag,
490 						function (html) {
491 							if ($element && $element.length) {
492 								GCN.renderOnto($element, html);
493 								// Because 'content-inserted' is deprecated by
494 								// 'tag.inserted'.
495 								GCN.pub('content-inserted', [$element, html]);
496 								GCN.pub('tag.inserted', [$element, html]);
497 							}
498 
499 							var frontendEditing = function (callback) {
500 								if ('edit' === mode) {
501 									// Because 'rendered-for-editing' is deprecated by
502 									// 'tag.rendered-for-editing'.
503 									GCN.pub('rendered-for-editing', {
504 										tag: tag,
505 										data: data,
506 										callback: callback
507 									});
508 									GCN.pub('tag.rendered-for-editing', {
509 										tag: tag,
510 										data: data,
511 										callback: callback
512 									});
513 								} else if (callback) {
514 									callback();
515 								}
516 							};
517 
518 							// Because the caller of edit() my wish to do things
519 							// in addition to, or instead of, our frontend
520 							// initialization.
521 							if (success) {
522 								tag._invoke(
523 									success,
524 									[html, tag, data, frontendEditing]
525 								);
526 							} else {
527 								frontendEditing();
528 							}
529 
530 							tag._merge();
531 						});
532 				};
533 				var errorHandler = function () {
534 					tag._merge();
535 				};
536 
537 				if ('edit' === mode && obj._previewEditableTag) {
538 					obj._previewEditableTag(tag._name, renderHandler, errorHandler);
539 				} else {
540 					obj._renderTemplate(template, mode, renderHandler, errorHandler, post);
541 				}
542 			}, error);
543 		},
544 
545 		/**
546 		 * <p>
547 		 * Render the tag based on its settings on the server. Can be called
548 		 * with the following arguments:<(p>
549 		 *
550 		 * <pre>
551 		 * // Render tag contents into div whose id is "content-div"
552 		 * render('#content-div') or render(jQuery('#content-div'))
553 		 * </pre>
554 		 *
555 		 * <pre>
556 		 * // Pass the html rendering of the tag in the given callback
557 		 * render(function(html, tag) {
558 		 *   // implementation!
559 		 * })
560 		 * </pre>
561 		 *
562 		 * Whenever a 2nd argument is provided, it will be taken as as custom
563 		 * error handler. Invoking render() without any arguments will yield no
564 		 * results.
565 		 *
566 		 * @function
567 		 * @name render
568 		 * @memberOf TagAPI
569 		 * @param {string|jQuery.HTMLElement}
570 		 *            selector jQuery selector or jQuery target element to be
571 		 *            used as render destination
572 		 * @param {function(string,
573 		 *            GCN.TagAPI)} success success function that will receive
574 		 *            the rendered html as well as the TagAPI object
575 		 * @param {boolean} post
576 		 *            True, when the tag shall be rendered by POSTing the data to
577 		 *            the REST API. Otherwise the tag is rendered with a GET call
578 		 */
579 		render: function () {
580 			var tag = this;
581 			var args = arguments;
582 			jQuery(function () {
583 				args = getRenderOptions(args);
584 				if (args.element || args.success) {
585 					tag._render(
586 						'view',
587 						args.element,
588 						args.success,
589 						args.error,
590 						args.post
591 					);
592 				}
593 			});
594 		},
595 
596 		/**
597 		 * <p>
598 		 * Renders this tag for editing.
599 		 * </p>
600 		 *
601 		 * <p>
602 		 * Differs from the render() method in that it calls this tag to be
603 		 * rendered in "edit" mode via the REST API so that it is rendered with
604 		 * any additional content that is appropriate for when this tag is used
605 		 * in edit mode.
606 		 * </p>
607 		 *
608 		 * <p>
609 		 * The GCN JS API library will also start keeping track of various
610 		 * aspects of this tag and its rendered content.
611 		 * </p>
612 		 *
613 		 * <p>
614 		 * When a jQuery selector is passed to this method, the contents of the
615 		 * rendered tag will overwrite the element identified by that selector.
616 		 * All rendered blocks and editables will be automatically placed into
617 		 * the DOM and initialize for editing.
618 		 * </p>
619 		 *
620 		 * <p>
621 		 * The behavior is different when this method is called with a function
622 		 * as its first argument.  In this case the rendered contents of the tag
623 		 * will not be autmatically placed into the DOM, but will be passed onto
624 		 * the callback function as argmuments.  It is then up to the caller to
625 		 * place the content into the DOM and initialize all rendered blocks and
626 		 * editables appropriately.
627 		 * </p>
628 		 *
629 		 * @function
630 		 * @name edit
631 		 * @memberOf TagAPI
632 		 * @param {(string|jQuery.HTMLElement)=} element
633 		 *            The element into which this tag is to be rendered.
634 		 * @param {function(string,TagAPI)=} success
635 		 *            A function that will be called once the tag is rendered.
636 		 * @param {function(GCNError):boolean=} error
637 		 *            A custom error handler.
638 		 * @param {boolean} post
639 		 *            True, when the tag shall be rendered by POSTing the data to
640 		 *            the REST API. Otherwise the tag is rendered with a GET call
641 		 */
642 		edit: function () {
643 			var tag = this;
644 			var args = getRenderOptions(arguments);
645 			if (args.data) {
646 
647 				// Because the parent content object needs to track any
648 				// blocks or editables that have been rendered in this tag.
649 				tag.parent()._processRenderedTags(args.data);
650 
651 				// Because 'rendered-for-editing' is deprecated in favor of
652 				// 'tag.rendered-for-editing'
653 				GCN.pub('rendered-for-editing', {
654 					tag: tag,
655 					data: args.data,
656 					callback: function () {
657 						if (args.success) {
658 							tag._invoke(
659 								args.success,
660 								[args.content, tag, args.data]
661 							);
662 						}
663 					}
664 				});
665 				GCN.pub('tag.rendered-for-editing', {
666 					tag: tag,
667 					data: args.data,
668 					callback: function () {
669 						if (args.success) {
670 							tag._invoke(
671 								args.success,
672 								[args.content, tag, args.data]
673 							);
674 						}
675 					}
676 				});
677 			} else {
678 				jQuery(function () {
679 					if (args.element || args.success) {
680 						tag._render(
681 							'edit',
682 							args.element,
683 							args.success,
684 							args.error,
685 							args.post
686 						);
687 					}
688 				});
689 			}
690 		},
691 
692 		/**
693 		 * Persists the changes to this tag on its container object. Will only
694 		 * save this one tag and not affect the container object itself.
695 		 * Important: be careful when dealing with editable contents - these
696 		 * will be reloaded from Aloha Editor editables when a page is saved
697 		 * and thus overwrite changes you made to an editable tag.
698 		 *
699 		 * @function
700 		 * @name save
701 		 * @memberOf TagAPI
702 		 * @param {object=} settings Optional settings to pass on to the ajax
703 		 *            function.
704 		 * @param {function(TagAPI)} success Callback to be invoked when this
705 		 *                                   operation completes normally.
706 		 * @param {function(GCNError):boolean} error Custom error handler.
707 		 */
708 		save: function (settings, success, error) {
709 			var tag = this;
710 			var parent = tag.parent();
711 			var type = parent._type;
712 			// to support the optional setting object as first argument we need
713 			// to shift the arguments when it is not an object
714 			if (jQuery.type(settings) !== 'object') {
715 				error = success;
716 				success = settings;
717 				settings = null;
718 			}
719 			var json = settings || {};
720 			// create a mockup object to be able to save only one tag
721 			// id is needed - REST API won't accept objects without id
722 			json[type] = { id: parent.id(), tags: {} };
723 			json[type].tags[tag._name] = tag._data;
724 
725 			parent._authAjax({
726 				url   : GCN.settings.BACKEND_PATH + '/rest/' + type + '/save/'
727 				      + parent.id() + GCN._getChannelParameter(parent),
728 				type  : 'POST',
729 				error : error,
730 				json  : json,
731 				success : function onTagSaveSuccess(response) {
732 					if (GCN.getResponseCode(response) === 'OK') {
733 						tag._invoke(success, [tag]);
734 					} else {
735 						tag._die(GCN.getResponseCode(response));
736 						GCN.handleResponseError(response, error);
737 					}
738 				}
739 			});
740 		},
741 
742 		/**
743 		 * TagAPI Objects are not cached themselves. Their _data object
744 		 * always references a tag in the _data of their parent, so that
745 		 * changes made to the TagAPI object will also change the tag in the
746 		 * _data of the parent.
747 		 * If the parent is reloaded and the _data refreshed, this would not
748 		 * clear or refresh the cache of the TagAPI objects. This would lead
749 		 * to a "broken" references and changes made to the cached TagAPI object
750 		 * would no longer change the tag in the parent.
751 		 *
752 		 * @private
753 		 * @return {Chainback} This Chainback.
754 		 */
755 		_addToCache: function () {
756 			return this;
757 		}
758 	});
759 
760 	// Unlike content objects, tags do not have unique ids and so we uniquely I
761 	// dentify tags by their name, and their parent's id.
762 	TagAPI._needsChainedHash = true;
763 
764 	GCN.tag = GCN.exposeAPI(TagAPI);
765 	GCN.TagAPI = TagAPI;
766 
767 }(GCN));
768