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