1 /*global window: true*/
  2 (function (GCN) {
  3 
  4 	'use strict';
  5 
  6 	/**
  7 	 * @private
  8 	 * @const
  9 	 * @type {object<string, function(string, *)|string>} This hash is used to
 10 	 *                                                    determine what
 11 	 *                                                    property can be read
 12 	 *                                                    for a part of a given
 13 	 *                                                    type. *SELECT and
 14 	 *                                                    PAGE parttypes are
 15 	 *                                                    handled specially.
 16 	 */
 17 	var PART_TYPES = {};
 18 
 19 	PART_TYPES = {
 20 		STRING   : 'stringValue',
 21 		RICHTEXT : 'stringValue',
 22 		BOOLEAN  : 'booleanValue',
 23 		IMAGE    : 'imageId',
 24 		// (URL) file is the same as File (upload).
 25 		FILE     : 'fileId',
 26 		// (URL) folder is the same as Folder (upload).
 27 		FOLDER   : 'folderId',
 28 		OVERVIEW : 'overview',
 29 		PAGE     : function (part, value) {
 30 			if (jQuery.type(value) === 'number') {
 31 				part.pageId = value;
 32 				delete part.stringValue;
 33 				return value;
 34 			}
 35 
 36 			if (typeof value !== 'undefined' && value !== null) {
 37 				part.stringValue = value.toString();
 38 				delete part.pageId;
 39 				return value;
 40 			}
 41 
 42 			return part[jQuery.type(part.stringValue) === 'string'
 43 				? 'stringValue' : 'pageId'];
 44 		},
 45 
 46 		SELECT : function (part, value) {
 47 			if (value) {
 48 				if (typeof value.datasourceId !== 'undefined') {
 49 					part.datasourceId = value.datasourceId;
 50 				}
 51 
 52 				if (value.options) {
 53 					part.options = value.options;
 54 				}
 55 
 56 				if (value.selectedOptions) {
 57 					part.selectedOptions = value.selectedOptions;
 58 				}
 59 			}
 60 
 61 			return {
 62 				datasourceId    : part.datasourceId,
 63 				options         : part.options,
 64 				selectedOptions : part.selectedOptions
 65 			};
 66 		},
 67 
 68 		MULTISELECT : function (part, value) {
 69 			return PART_TYPES.SELECT(part, value);
 70 		},
 71 
 72 		TEMPLATETAG : function (part, value) {
 73 			if (value) {
 74 				if (typeof value.templateId !== 'undefined') {
 75 					part.templateId = value.templateId;
 76 				}
 77 
 78 				if (typeof value.templateTagId !== 'undefined') {
 79 					part.templateTagId = value.templateTagId;
 80 				}
 81 			}
 82 
 83 			return {
 84 				templateId    : part.templateId,
 85 				templateTagId : part.templateTagId
 86 			};
 87 		},
 88 
 89 		PAGETAG : function (part, value) {
 90 			if (value) {
 91 				if (typeof value.pageId !== 'undefined') {
 92 					part.pageId = value.pageId;
 93 				}
 94 
 95 				if (typeof value.pageTagId !== 'undefined') {
 96 					part.pageTagId = value.pageTagId;
 97 				}
 98 			}
 99 
100 			return {
101 				templateId    : part.pageId,
102 				templateTagId : part.pageTagId
103 			};
104 		}
105 	};
106 
107 	/**
108 	 * Determine the key inside tag properties where our value is stored, and
109 	 * retreive that value.
110 	 *
111 	 * @param {object} part The tag part we want to read.
112 	 * @return {*} The value that the given tag part holds.
113 	 * @throws CANNOT_READ_TAG_PART
114 	 */
115 	function getPartValue(part) {
116 		var propName = PART_TYPES[part.type];
117 
118 		if (!propName) {
119 			GCN.error('CANNOT_READ_TAG_PART',
120 				'Cannot read or write to tag part', part);
121 
122 			return null;
123 		}
124 
125 		if (jQuery.type(propName) === 'function') {
126 			return propName(part);
127 		}
128 
129 		return part[propName];
130 	}
131 
132 
133 	function setPartValue(part, value) {
134 		var prop = PART_TYPES[part.type];
135 
136 		if (!prop) {
137 			GCN.error('CANNOT_READ_TAG_PART',
138 				'Cannot read or write to tag part', part);
139 
140 			return null;
141 		}
142 
143 		if (jQuery.type(prop) === 'function') {
144 			return prop(part, value);
145 		}
146 
147 		part[prop] = value;
148 
149 		return value;
150 	}
151 
152 	/**
153 	 * Searches for the an Aloha editable object of the given id.
154 	 *
155 	 * @TODO: Once Aloha.getEditableById() is patched to not cause an
156 	 *        JavaScript exception if the element for the given ID is not found
157 	 *        then we can deprecate this function and use Aloha's instead.
158 	 *
159 	 * @static
160 	 * @param {string} id Id of Aloha.Editable object to find.
161 	 * @return {Aloha.Editable=} The editable object, if wound; otherwise null.
162 	 */
163 	function getAlohaEditableById(id) {
164 		var Aloha = (typeof window !== 'undefined') && window.Aloha;
165 		if (!Aloha) {
166 			return null;
167 		}
168 
169 		// If the element is a textarea then route to the editable div.
170 		var element = jQuery('#' + id);
171 		if (element.length &&
172 				element[0].nodeName.toLowerCase() === 'textarea') {
173 			id += '-aloha';
174 		}
175 
176 		var editables = Aloha.editables;
177 		var j = editables.length;
178 		while (j) {
179 			if (editables[--j].getId() === id) {
180 				return editables[j];
181 			}
182 		}
183 
184 		return null;
185 	}
186 
187 	/**
188 	 * Will initialize the contents that have been rendered in a given
189 	 * container for front end editing.
190 	 *
191 	 * @TODO: This function should be moved out of gcn library.  We should
192 	 *        publish a message instead, and pass these arguments in the
193 	 *        message.
194 	 *
195 	 * @private
196 	 * @static
197 	 * @param {Array.<object>} editables Editables to be `aloha()'fied.
198 	 * @param {Array.<object>} blocks Blocks to receive tagfill buttons.
199 	 * @param {number|string} pageId id of the page the tag belongs to
200 	 * @param {jQuery<HTMLElement>} container The element that wraps the
201 	 *                              incoming tag contents.
202 	 */
203 	function initializeFrontendEditing(editables, blocks, pageId, container) {
204 		var Aloha = (typeof window !== 'undefined') && window.Aloha;
205 
206 		if (!Aloha) {
207 			return;
208 		}
209 
210 		Aloha.ready(function () {
211 			if (Aloha.GCN) {
212 				// If we are in the backend, then we need to remove the id of
213 				// the container because it is duplicated in the incoming
214 				// content.
215 				if (container && Aloha.GCN.isBackendMode()) {
216 					container.removeAttr('id');
217 				}
218 				Aloha.GCN.page = GCN.page(pageId);
219 				Aloha.GCN.setupConstructsButton(pageId);
220 			}
221 
222 			var j = editables && editables.length;
223 			var editable;
224 			var unmodified = [];
225 			while (j) {
226 				Aloha.jQuery('#' + editables[--j].element).aloha();
227 				editable = getAlohaEditableById(editables[j].element);
228 				if (editable) {
229 					unmodified.push(editable);
230 					if (editables[j].readonly) {
231 						editable.disable();
232 					}
233 				}
234 			}
235 
236 			if (Aloha.GCN) {
237 				j = Aloha.editables.length;
238 				while (j) {
239 					if (!Aloha.editables[--j].isModified()) {
240 						unmodified.push(Aloha.editables[j]);
241 					}
242 				}
243 				Aloha.GCN.alohaBlocks(blocks, pageId, function () {
244 					var j = unmodified.length;
245 					while (j) {
246 						unmodified[--j].setUnmodified();
247 					}
248 				});
249 			}
250 		});
251 	}
252 
253 	/**
254 	 * Helper function to normalize the arguments that can be passed to the
255 	 * `edit()' and `render()' methods.
256 	 *
257 	 * @private
258 	 * @static
259 	 * @param {arguments} args A list of arguments.
260 	 * @return {object} Object containing an the properties `element',
261 	 *                         `success' and `error', and `data'.
262 	 */
263 	function getRenderOptions(args) {
264 		var argv = Array.prototype.slice.call(args);
265 		var argc = args.length;
266 		var arg;
267 		var i;
268 
269 		var element;
270 		var success;
271 		var error;
272 		var prerenderedData = false;
273 
274 		for (i = 0; i < argc; ++i) {
275 			arg = argv[i];
276 
277 			switch (jQuery.type(arg)) {
278 			case 'string':
279 				element = jQuery(arg);
280 				break;
281 			case 'object':
282 				if (element) {
283 					prerenderedData = arg;
284 				} else {
285 					element = arg;
286 				}
287 				break;
288 			case 'function':
289 				if (success) {
290 					error = arg;
291 				} else {
292 					success = arg;
293 				}
294 				break;
295 			// Descarding all other types of arguments...
296 			}
297 		}
298 
299 		return {
300 			element : element,
301 			success : success,
302 			error   : error,
303 			data    : prerenderedData
304 		};
305 	}
306 
307 	/**
308 	 * Exposes an API to operate on a Content.Node tag.
309 	 *
310 	 * @public
311 	 * @class TagAPI
312 	 */
313 	var TagAPI = GCN.defineChainback({
314 
315 		__chainbacktype__: 'TagAPI',
316 
317 		/**
318 		 * @type {GCN.ContentObject} A reference to the object in which this
319 		 *                           tag is contained.  This value is set
320 		 *                           during initialization.
321 		 */
322 		_parent: null,
323 
324 		/**
325 		 * @type {string} Name of this tag.
326 		 */
327 		_name: null,
328 
329 		/**
330 		 * Gets this tag's information from the object that contains it.
331 		 *
332 		 * @param {function(TagAPI)} success Callback to be invoked when this
333 		 *                                   operation completes normally.
334 		 * @param {function(GCNError):boolean} error Custom error handler.
335 		 */
336 		'!_read': function (success, error) {
337 			if (this._fetched) {
338 				if (success) {
339 					success(this);
340 				}
341 
342 				return;
343 			}
344 
345 			var that = this;
346 			var parent = this.parent();
347 
348 			// assert(parent)
349 
350 			// Take the data for this tag from it's container.
351 			parent._read(function () {
352 				that._data = parent._getTagData(that._name);
353 
354 				if (!that._data) {
355 					var err = GCN.createError('TAG_NOT_FOUND',
356 						'Could not find tag "' + that._name + '" in ' +
357 						parent._type + " " + parent._data.id, that);
358 
359 					GCN.handleError(err, error);
360 
361 					return;
362 				}
363 
364 				that._fetched = true;
365 
366 				if (success) {
367 					success(that);
368 				}
369 			}, error);
370 		},
371 
372 		/**
373 		 * Retrieve the object in which this tag is contained.  It does so by
374 		 * getting this chainback's "chainlink ancestor" object.
375 		 *
376 		 * @return {GCN.AbstractTagContainer}
377 		 */
378 		'!parent': function () {
379 			return this._ancestor();
380 		},
381 
382 		/**
383 		 * Initialize a tag object.  Unlike other chainback objects, tags will
384 		 * always have a parent.  If its parent have been loaded, we will
385 		 * immediately copy the this tag's data from the parent's `_data'
386 		 * object to the tag's `_data' object.
387 		 *
388 		 * @param {string|object} settings
389 		 * @param {function(TagAPI)} success Callback to be invoked when this
390 		 *                                   operation completes normally.
391 		 * @param {function(GCNError):boolean} error Custom error handler.
392 		 */
393 		_init: function (settings, success, error) {
394 			if (jQuery.type(settings) === 'object') {
395 				this._name    = settings.name;
396 				this._data    = settings;
397 				this._data.id = settings.id;
398 				this._fetched = true;
399 			} else {
400 				this._data = {};
401 				this._data.id = this._name = settings;
402 			}
403 
404 			if (success) {
405 				var that = this;
406 
407 				this._read(function (container) {
408 					that._read(success, error);
409 				}, error);
410 
411 			// Even if not success callback is given, read this tag's data from
412 			// is container, it that container has the data available.
413 			// If we are initializing a placeholder tag object (in the process
414 			// of creating brand new tag, for example), then its parent
415 			// container will not have any data for this tag yet.  We know that
416 			// we are working with a placeholder tag if no `_data.id' or `_name'
417 			// property is set.
418 			} else if (!this._fetched && this._name &&
419 			           this.parent()._fetched) {
420 				this._data = this.parent()._getTagData(this._name);
421 				this._fetched = !!this._data;
422 
423 			// We are propably initializing a placholder object, we will assign
424 			// it its own `_data' and `_fetched' properties so that it is not
425 			// accessing the prototype values.
426 			} else if (!this._fetched) {
427 				this._data = {};
428 				this._data.id = this._name = settings;
429 				this._fetched = false;
430 			}
431 		},
432 
433 		/**
434 		 * Get or set a property of this tags.
435 		 * Note that tags do not have a `_shadow' object, and we update the
436 		 * `_data' object directly.
437 		 *
438 		 * @param {string} name Name of tag part.
439 		 * @param {*=} set Optional value.  If provided, the tag part will be
440 		 *                 replaced with this value.
441 		 * @return {*} The value of the accessed tag part.
442 		 * @throws UNFETCHED_OBJECT_ACCESS
443 		 */
444 		'!prop': function (name, value) {
445 			var parent = this.parent();
446 
447 			if (!this._fetched) {
448 				GCN.error('UNFETCHED_OBJECT_ACCESS',
449 					'Calling method `prop()\' on an unfetched object: ' +
450 					parent._type + " " + parent._data.id, this);
451 
452 				return;
453 			}
454 
455 			if (jQuery.type(value) !== 'undefined') {
456 				this._data[name] = value;
457 				parent._update('tags.' + name, this._data);
458 			}
459 
460 			return this._data[name];
461 		},
462 
463 		/**
464 		 * Get or set a part of this tags.
465 		 *
466 		 * @param {string} name Name of tag opart.
467 		 * @param {*=} set Optional value.  If provided, the tag part will be
468 		 *                 replaced with this value.
469 		 * @return {*} The value of the accessed tag part.
470 		 * @throws UNFETCHED_OBJECT_ACCESS
471 		 * @throws PART_NOT_FOUND
472 		 */
473 		'!part': function (name, value) {
474 			var parent;
475 
476 			if (!this._fetched) {
477 				parent = this.parent();
478 
479 				GCN.error('UNFETCHED_OBJECT_ACCESS',
480 					'Calling method `prop()\' on an unfetched object: ' +
481 					parent._type + " " + parent._data.id, this);
482 
483 				return null;
484 			}
485 
486 			var part = this._data.properties[name];
487 
488 			if (!part) {
489 				parent = this.parent();
490 
491 				GCN.error('PART_NOT_FOUND', 'Tag "' + this._name +
492 					'" of ' + parent._type + ' ' + parent._data.id +
493 					' does not have a part "' + name + '"', this);
494 
495 				return null;
496 			}
497 
498 			if (jQuery.type(value) === 'undefined') {
499 				return getPartValue(part);
500 			}
501 
502 			setPartValue(part, value);
503 
504 			// Each time we perform a write operation on a tag, we will update
505 			// the tag in the tag container's `_shadow' object as well.
506 			this.parent()._update('tags.' + this._name, this._data);
507 
508 			return value;
509 		},
510 
511 		/**
512 		 * Remove this tag from its containing object (it's parent).
513 		 *
514 		 * @param {function} callback A function that receive this tag's parent
515 		 *                            object as its only arguments.
516 		 */
517 		remove: function (success, error) {
518 			var parent = this.parent();
519 
520 			if (!parent.hasOwnProperty('_deletedTags')) {
521 				parent._deletedTags = [];
522 			}
523 
524 			parent._deletedTags.push(this._name);
525 
526 			if (parent._data.tags &&
527 					parent._data.tags[this._name]) {
528 				delete parent._data.tags[this._name];
529 			}
530 
531 			if (parent._shadow.tags &&
532 					parent._shadow.tags[this._name]) {
533 				delete parent._shadow.tags[this._name];
534 			}
535 
536 			parent._removeAssociatedTagData(this._name);
537 
538 			if (success) {
539 				parent._persist(success, error);
540 			}
541 		},
542 
543 		/**
544 		 * Will render this tag in the given render `mode'.  If an element is
545 		 * provided, the content will be placed in that element.  If the `mode'
546 		 * is "edit", any rendered editables will be initialized for Aloha
547 		 * Editor.  Any editable that are rendered into an element will also be
548 		 * added to the tag's parent object's `_editables' array so that they
549 		 * can have their changed contents copied back into their corresponding
550 		 * tags during saving.
551 		 *
552 		 * @param {string} mode The rendering mode.  Valid values are "view",
553 		 *                      and "edit".
554 		 * @param {jQuery.<HTMLElement>} element DOM element into which the
555 		 *                                       the rendered content should be
556 		 *                                       placed.
557 		 * @param {function(string, TagAPI, object)} Optional success handler.
558 		 * @param {function(GCNError):boolean} Optional custom error handler.
559 		 */
560 		'!_render': function (mode, element, success, error) {
561 			var that = this;
562 			var parent = this.parent();
563 
564 			this._read(function () {
565 				that._procure();
566 				parent._renderTemplate('<node ' + that._name + '>', mode,
567 					function (data) {
568 						var tags = parent._processRenderedTags(data);
569 						GCN._handleContentRendered(data.content,
570 							function (html) {
571 								if (element) {
572 									element.html(html);
573 									GCN.pub('content-inserted', [element,
574 										html]);
575 								}
576 
577 								if (success) {
578 									success(html, that, data);
579 								}
580 
581 								initializeFrontendEditing(tags.editables,
582 									tags.blocks, parent.id(), element);
583 
584 								that._vacate();
585 							});
586 					}, function () {
587 						that._vacate();
588 					});
589 			}, error);
590 		},
591 
592 		/**
593 		 * Render the tag based on its settings on the server.
594 		 * Can be called with the following arguments:
595 		 *
596 		 * Do nothing:
597 		 * render()
598 		 *
599 		 * Render tag contents into div whose id is "content-div":
600 		 * @param {string|jQuery.<HTMLElement>}
601 		 * render('#content-div') or render(jQuery('#content-div'))
602 		 *
603 		 * Pass the html rendering of the tag in the given callback:
604 		 * @param {function(string, GCN.TagAPI)}
605 		 * render(function (html, tag) {})
606 		 *
607 		 * Whenever a 2nd argument is provided, it will be taken as as custom
608 		 * error handler.
609 		 */
610 		render: function () {
611 			var that = this;
612 			var args = arguments;
613 			// Wait until DOM is ready
614 			jQuery(function () {
615 				args = getRenderOptions(args);
616 				if (args.element || args.success) {
617 					that._render('view', args.element, args.success,
618 						args.error);
619 				}
620 			});
621 		},
622 
623 		/**
624 		 * Like `render()', except that the content is rendered with additional
625 		 * elements that are required for front-end editing. ie: editables.
626 		 */
627 		edit: function () {
628 			var args = getRenderOptions(arguments);
629 			if (args.data) {
630 				var parent = this.parent();
631 				var tags = parent._processRenderedTags(args.data);
632 				if (args.success) {
633 					args.success(args.content, this, args.data);
634 				}
635 				initializeFrontendEditing(tags.editables, tags.blocks,
636 					parent.id());
637 			} else {
638 				// Wait until DOM is ready
639 				var that = this;
640 				jQuery(function () {
641 					if (args.element || args.success) {
642 						that._render('edit', args.element, args.success,
643 							args.error);
644 					}
645 				});
646 			}
647 		},
648 
649 		/**
650 		 * Persists the changes to this tag on its container object.
651 		 *
652 		 * @param {function(TagAPI)} success Callback to be invoked when this
653 		 *                                   operation completes normally.
654 		 * @param {function(GCNError):boolean} error Custom error handler.
655 		 */
656 		save: function (success, error) {
657 			var that = this;
658 			this.parent().save(function () {
659 				if (success) {
660 					success(that);
661 				}
662 			}, error);
663 		}
664 
665 	});
666 
667 	// Unlike content objects, tags do not have unique ids and so we uniquely I
668 	// dentify tags by their name, and their parent's id.
669 	TagAPI._needsChainedHash = true;
670 
671 	GCN.tag = GCN.exposeAPI(TagAPI);
672 	GCN.TagAPI = TagAPI;
673 
674 }(GCN));
675