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 			if (success) {
414 				parent._persist(null, success, error);
415 			}
416 		},
417 
418 		/**
419 		 * Given a DOM element, will generate a template which represents this
420 		 * tag as it would be if rendered in the element.
421 		 *
422 		 * @param {jQuery.<HTMLElement>} $element DOM element with which to
423 		 *                                        generate the template.
424 		 * @return {string} Template string.
425 		 */
426 		'!_makeTemplate': function ($element) {
427 			if (0 === $element.length) {
428 				return '<node ' + this._name + '>';
429 			}
430 			var placeholder =
431 					'-{(' + this.parent().id() + ':' + this._name + ')}-';
432 			var template = jQuery.trim(
433 					$element.clone().html(placeholder)[0].outerHTML
434 				);
435 			return template.replace(placeholder, '<node ' + this._name + '>');
436 		},
437 
438 		/**
439 		 * Will render this tag in the given render `mode'.  If an element is
440 		 * provided, the content will be placed in that element.  If the `mode'
441 		 * is "edit", any rendered editables will be initialized for Aloha
442 		 * Editor.  Any editable that are rendered into an element will also be
443 		 * added to the tag's parent object's `_editables' array so that they
444 		 * can have their changed contents copied back into their corresponding
445 		 * tags during saving.
446 		 *
447 		 * @param {string} mode The rendering mode.  Valid values are "view",
448 		 *                      and "edit".
449 		 * @param {jQuery.<HTMLElement>} element DOM element into which the
450 		 *                                       the rendered content should be
451 		 *                                       placed.
452 		 * @param {function(string, TagAPI, object)} Optional success handler.
453 		 * @param {function(GCNError):boolean} Optional custom error handler.
454 		 */
455 		'!_render': function (mode, $element, success, error) {
456 			var tag = this._fork();
457 			tag._read(function () {
458 				var template = ($element && $element.length)
459 				             ? tag._makeTemplate($element)
460 				             : '<node ' + tag._name + '>';
461 
462 				var obj = tag.parent();
463 
464 				obj._renderTemplate(template, mode, function (data) {
465 
466 					// Because the parent content object needs to track any
467 					// blocks or editables that have been rendered in this tag.
468 					obj._processRenderedTags(data);
469 
470 					GCN._handleContentRendered(data.content, tag,
471 						function (html) {
472 							if ($element && $element.length) {
473 								GCN.renderOnto($element, html);
474 								// Because 'content-inserted' is deprecated by
475 								// 'tag.inserted'.
476 								GCN.pub('content-inserted', [$element, html]);
477 								GCN.pub('tag.inserted', [$element, html]);
478 							}
479 
480 							var frontendEditing = function (callback) {
481 								if ('edit' === mode) {
482 									// Because 'rendered-for-editing' is deprecated by
483 									// 'tag.rendered-for-editing'.
484 									GCN.pub('rendered-for-editing', {
485 										tag: tag,
486 										data: data,
487 										callback: callback
488 									});
489 									GCN.pub('tag.rendered-for-editing', {
490 										tag: tag,
491 										data: data,
492 										callback: callback
493 									});
494 								} else if (callback) {
495 									callback();
496 								}
497 							};
498 
499 							// Because the caller of edit() my wish to do things
500 							// in addition to, or instead of, our frontend
501 							// initialization.
502 							if (success) {
503 								tag._invoke(
504 									success,
505 									[html, tag, data, frontendEditing]
506 								);
507 							} else {
508 								frontendEditing();
509 							}
510 
511 							tag._merge();
512 						});
513 				}, function () {
514 					tag._merge();
515 				});
516 			}, error);
517 		},
518 
519 		/**
520 		 * <p>
521 		 * Render the tag based on its settings on the server. Can be called
522 		 * with the following arguments:<(p>
523 		 *
524 		 * <pre>
525 		 * // Render tag contents into div whose id is "content-div"
526 		 * render('#content-div') or render(jQuery('#content-div'))
527 		 * </pre>
528 		 *
529 		 * <pre>
530 		 * // Pass the html rendering of the tag in the given callback
531 		 * render(function(html, tag) {
532 		 *   // implementation!
533 		 * })
534 		 * </pre>
535 		 *
536 		 * Whenever a 2nd argument is provided, it will be taken as as custom
537 		 * error handler. Invoking render() without any arguments will yield no
538 		 * results.
539 		 *
540 		 * @function
541 		 * @name render
542 		 * @memberOf TagAPI
543 		 * @param {string|jQuery.HTMLElement}
544 		 *            selector jQuery selector or jQuery target element to be
545 		 *            used as render destination
546 		 * @param {function(string,
547 		 *            GCN.TagAPI)} success success function that will receive
548 		 *            the rendered html as well as the TagAPI object
549 		 */
550 		render: function () {
551 			var tag = this;
552 			var args = arguments;
553 			jQuery(function () {
554 				args = getRenderOptions(args);
555 				if (args.element || args.success) {
556 					tag._render(
557 						'view',
558 						args.element,
559 						args.success,
560 						args.error
561 					);
562 				}
563 			});
564 		},
565 
566 		/**
567 		 * <p>
568 		 * Renders this tag for editing.
569 		 * </p>
570 		 *
571 		 * <p>
572 		 * Differs from the render() method in that it calls this tag to be
573 		 * rendered in "edit" mode via the REST API so that it is rendered with
574 		 * any additional content that is appropriate for when this tag is used
575 		 * in edit mode.
576 		 * </p>
577 		 *
578 		 * <p>
579 		 * The GCN JS API library will also start keeping track of various
580 		 * aspects of this tag and its rendered content.
581 		 * </p>
582 		 *
583 		 * <p>
584 		 * When a jQuery selector is passed to this method, the contents of the
585 		 * rendered tag will overwrite the element identified by that selector.
586 		 * All rendered blocks and editables will be automatically placed into
587 		 * the DOM and initialize for editing.
588 		 * </p>
589 		 *
590 		 * <p>
591 		 * The behavior is different when this method is called with a function
592 		 * as its first argument.  In this case the rendered contents of the tag
593 		 * will not be autmatically placed into the DOM, but will be passed onto
594 		 * the callback function as argmuments.  It is then up to the caller to
595 		 * place the content into the DOM and initialize all rendered blocks and
596 		 * editables appropriately.
597 		 * </p>
598 		 *
599 		 * @function
600 		 * @name edit
601 		 * @memberOf TagAPI
602 		 * @param {(string|jQuery.HTMLElement)=} element
603 		 *            The element into which this tag is to be rendered.
604 		 * @param {function(string,TagAPI)=} success
605 		 *            A function that will be called once the tag is rendered.
606 		 * @param {function(GCNError):boolean=} error
607 		 *            A custom error handler.
608 		 */
609 		edit: function () {
610 			var tag = this;
611 			var args = getRenderOptions(arguments);
612 			if (args.data) {
613 
614 				// Because the parent content object needs to track any
615 				// blocks or editables that have been rendered in this tag.
616 				tag.parent()._processRenderedTags(args.data);
617 
618 				// Because 'rendered-for-editing' is deprecated in favor of
619 				// 'tag.rendered-for-editing'
620 				GCN.pub('rendered-for-editing', {
621 					tag: tag,
622 					data: args.data,
623 					callback: function () {
624 						if (args.success) {
625 							tag._invoke(
626 								args.success,
627 								[args.content, tag, args.data]
628 							);
629 						}
630 					}
631 				});
632 				GCN.pub('tag.rendered-for-editing', {
633 					tag: tag,
634 					data: args.data,
635 					callback: function () {
636 						if (args.success) {
637 							tag._invoke(
638 								args.success,
639 								[args.content, tag, args.data]
640 							);
641 						}
642 					}
643 				});
644 			} else {
645 				jQuery(function () {
646 					if (args.element || args.success) {
647 						tag._render(
648 							'edit',
649 							args.element,
650 							args.success,
651 							args.error
652 						);
653 					}
654 				});
655 			}
656 		},
657 
658 		/**
659 		 * Persists the changes to this tag on its container object. Will only
660 		 * save this one tag and not affect the container object itself.
661 		 * Important: be careful when dealing with editable contents - these
662 		 * will be reloaded from Aloha Editor editables when a page is saved
663 		 * and thus overwrite changes you made to an editable tag.
664 		 *
665 		 * @function
666 		 * @name save
667 		 * @memberOf TagAPI
668 		 * @param {function(TagAPI)} success Callback to be invoked when this
669 		 *                                   operation completes normally.
670 		 * @param {function(GCNError):boolean} error Custom error handler.
671 		 */
672 		save: function (success, error) {
673 			var tag = this;
674 			var parent = tag.parent();
675 			var type = parent._type;
676 			var json = {};
677 
678 			// create a mockup object to be able to save only one tag
679 			// id is needed - REST API won't accept objects without id
680 			json[type] = { id: parent.id(), tags: {} };
681 			json[type].tags[tag._name] = tag._data;
682 
683 			parent._authAjax({
684 				url   : GCN.settings.BACKEND_PATH + '/rest/' + type + '/save/'
685 				      + parent.id() + GCN._getChannelParameter(parent),
686 				type  : 'POST',
687 				error : error,
688 				json  : json,
689 				success : function onTagSaveSuccess(response) {
690 					if (GCN.getResponseCode(response) === 'OK') {
691 						tag._invoke(success, [tag]);
692 					} else {
693 						tag._die(GCN.getResponseCode(response));
694 						GCN.handleResponseError(response, error);
695 					}
696 				}
697 			});
698 		}
699 	});
700 
701 	// Unlike content objects, tags do not have unique ids and so we uniquely I
702 	// dentify tags by their name, and their parent's id.
703 	TagAPI._needsChainedHash = true;
704 
705 	GCN.tag = GCN.exposeAPI(TagAPI);
706 	GCN.TagAPI = TagAPI;
707 
708 }(GCN));
709