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') {
 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 !== 'undefinded') {
 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'.
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 
273 		for (i = 0; i < argc; ++i) {
274 			arg = argv[i];
275 
276 			switch (jQuery.type(arg)) {
277 			case 'string':
278 				element = jQuery(arg);
279 				break;
280 			case 'object':
281 				element = arg;
282 				break;
283 			case 'function':
284 				if (success) {
285 					error = arg;
286 				} else {
287 					success = arg;
288 				}
289 				break;
290 			// Descarding all other types of arguments...
291 			}
292 		}
293 
294 		return {
295 			element : element,
296 			success : success,
297 			error   : error
298 		};
299 	}
300 
301 	/**
302 	 * Exposes an API to operate on a Content.Node tag.
303 	 *
304 	 * @public
305 	 * @class TagAPI
306 	 */
307 	var TagAPI = GCN.defineChainback({
308 
309 		__chainbacktype__: 'TagAPI',
310 
311 		/**
312 		 * @type {GCN.ContentObject} A reference to the object in which this
313 		 *                           tag is contained.  This value is set
314 		 *                           during initialization.
315 		 */
316 		_parent: null,
317 
318 		/**
319 		 * @type {string} Name of this tag.
320 		 */
321 		_name: null,
322 
323 		/**
324 		 * Gets this tag's information from the object that contains it.
325 		 *
326 		 * @param {function(TagAPI)} success Callback to be invoked when this
327 		 *                                   operation completes normally.
328 		 * @param {function(GCNError):boolean} error Custom error handler.
329 		 */
330 		'!_read': function (success, error) {
331 			if (this._fetched) {
332 				if (success) {
333 					success(this);
334 				}
335 
336 				return;
337 			}
338 
339 			var that = this;
340 			var parent = this.parent();
341 
342 			// assert(parent)
343 
344 			// Take the data for this tag from it's container.
345 			parent._read(function () {
346 				that._data = parent._getTagData(that._name);
347 
348 				if (!that._data) {
349 					var err = GCN.createError('TAG_NOT_FOUND',
350 						'Could not find tag "' + that._name + '" in ' +
351 						parent._type + " " + parent._data.id, that);
352 
353 					GCN.handleError(err, error);
354 
355 					return;
356 				}
357 
358 				that._fetched = true;
359 
360 				if (success) {
361 					success(that);
362 				}
363 			}, error);
364 		},
365 
366 		/**
367 		 * Retrieve the object in which this tag is contained.  It does so by
368 		 * getting this chainback's "chainlink ancestor" object.
369 		 *
370 		 * @return {GCN.AbstractTagContainer}
371 		 */
372 		'!parent': function () {
373 			return this._ancestor();
374 		},
375 
376 		/**
377 		 * Initialize a tag object.  Unlike other chainback objects, tags will
378 		 * always have a parent.  If its parent have been loaded, we will
379 		 * immediately copy the this tag's data from the parent's `_data'
380 		 * object to the tag's `_data' object.
381 		 *
382 		 * @param {string|object} settings
383 		 * @param {function(TagAPI)} success Callback to be invoked when this
384 		 *                                   operation completes normally.
385 		 * @param {function(GCNError):boolean} error Custom error handler.
386 		 */
387 		_init: function (settings, success, error) {
388 			if (jQuery.type(settings) === 'object') {
389 				this._name    = settings.name;
390 				this._data    = settings;
391 				this._data.id = settings.id;
392 				this._fetched = true;
393 			} else {
394 				this._data = {};
395 				this._data.id = this._name = settings;
396 			}
397 
398 			if (success) {
399 				var that = this;
400 
401 				this._read(function (container) {
402 					that._read(success, error);
403 				}, error);
404 
405 			// Even if not success callback is given, read this tag's data from
406 			// is container, it that container has the data available.
407 			// If we are initializing a placeholder tag object (in the process
408 			// of creating brand new tag, for example), then its parent
409 			// container will not have any data for this tag yet.  We know that
410 			// we are working with a placeholder tag if no `_data.id' or `_name'
411 			// property is set.
412 			} else if (!this._fetched && this._name &&
413 			           this.parent()._fetched) {
414 				this._data = this.parent()._getTagData(this._name);
415 				this._fetched = !!this._data;
416 
417 			// We are propably initializing a placholder object, we will assign
418 			// it its own `_data' and `_fetched' properties so that it is not
419 			// accessing the prototype values.
420 			} else if (!this._fetched) {
421 				this._data = {};
422 				this._data.id = this._name = settings;
423 				this._fetched = false;
424 			}
425 		},
426 
427 		/**
428 		 * Get or set a property of this tags.
429 		 * Note that tags do not have a `_shadow' object, and we update the
430 		 * `_data' object directly.
431 		 *
432 		 * @param {string} name Name of tag part.
433 		 * @param {*=} set Optional value.  If provided, the tag part will be
434 		 *                 replaced with this value.
435 		 * @return {*} The value of the accessed tag part.
436 		 * @throws UNFETCHED_OBJECT_ACCESS
437 		 */
438 		'!prop': function (name, value) {
439 			var parent = this.parent();
440 
441 			if (!this._fetched) {
442 				GCN.error('UNFETCHED_OBJECT_ACCESS',
443 					'Calling method `prop()\' on an unfetched object: ' +
444 					parent._type + " " + parent._data.id, this);
445 
446 				return;
447 			}
448 
449 			if (jQuery.type(value) !== 'undefined') {
450 				this._data[name] = value;
451 				parent._update('tags.' + name, this._data);
452 			}
453 
454 			return this._data[name];
455 		},
456 
457 		/**
458 		 * Get or set a part of this tags.
459 		 *
460 		 * @param {string} name Name of tag opart.
461 		 * @param {*=} set Optional value.  If provided, the tag part will be
462 		 *                 replaced with this value.
463 		 * @return {*} The value of the accessed tag part.
464 		 * @throws UNFETCHED_OBJECT_ACCESS
465 		 * @throws PART_NOT_FOUND
466 		 */
467 		'!part': function (name, value) {
468 			var parent;
469 
470 			if (!this._fetched) {
471 				parent = this.parent();
472 
473 				GCN.error('UNFETCHED_OBJECT_ACCESS',
474 					'Calling method `prop()\' on an unfetched object: ' +
475 					parent._type + " " + parent._data.id, this);
476 
477 				return null;
478 			}
479 
480 			var part = this._data.properties[name];
481 
482 			if (!part) {
483 				parent = this.parent();
484 
485 				GCN.error('PART_NOT_FOUND', 'Tag "' + this._name +
486 					'" of ' + parent._type + ' ' + parent._data.id +
487 					' does not have a part "' + name + '"', this);
488 
489 				return null;
490 			}
491 
492 			if (jQuery.type(value) === 'undefined') {
493 				return getPartValue(part);
494 			}
495 
496 			setPartValue(part, value);
497 
498 			// Each time we perform a write operation on a tag, we will update
499 			// the tag in the tag container's `_shadow' object as well.
500 			this.parent()._update('tags.' + this._name, this._data);
501 
502 			return value;
503 		},
504 
505 		/**
506 		 * Remove this tag from its containing object (it's parent).
507 		 *
508 		 * @param {function} callback A function that receive this tag's parent
509 		 *                            object as its only arguments.
510 		 */
511 		remove: function (success, error) {
512 			var parent = this.parent();
513 
514 			if (!parent.hasOwnProperty('_deletedTags')) {
515 				parent._deletedTags = [];
516 			}
517 
518 			parent._deletedTags.push(this._name);
519 
520 			if (parent._data.tags &&
521 					parent._data.tags[this._name]) {
522 				delete parent._data.tags[this._name];
523 			}
524 
525 			if (parent._shadow.tags &&
526 					parent._shadow.tags[this._name]) {
527 				delete parent._shadow.tags[this._name];
528 			}
529 
530 			if (success) {
531 				parent._persist(success, error);
532 			}
533 		},
534 
535 		/**
536 		 * Will render this tag in the given render `mode'.  If an element is
537 		 * provided, the content will be placed in that element.  If the `mode'
538 		 * is "edit", any rendered editables will be initialized for Aloha
539 		 * Editor.  Any editable that are rendered into an element will also be
540 		 * added to the tag's parent object's `_editables' array so that they
541 		 * can have their changed contents copied back into their corresponding
542 		 * tags during saving.
543 		 *
544 		 * @param {string} mode The rendering mode.  Valid values are "view",
545 		 *                      and "edit".
546 		 * @param {jQuery.<HTMLElement>} element DOM element into which the
547 		 *                                       the rendered content should be
548 		 *                                       placed.
549 		 * @param {function(string, TagAPI, object)} Optional success handler.
550 		 * @param {function(GCNError):boolean} Optional custom error handler.
551 		 */
552 		'!_render': function (mode, element, success, error) {
553 			var that = this;
554 			var parent = this.parent();
555 
556 			this._read(function () {
557 				var template = '<node ' + that._name + '>';
558 
559 				that._procure();
560 
561 				parent._renderTemplate(template, mode, function (data) {
562 					var tags = parent._getEditablesAndBlocks(data);
563 
564 					parent._storeRenderedEditables(tags.editables);
565 					parent._storeRenderedBlocks(tags.blocks);
566 
567 					GCN._handleContentRendered(data.content, function (html) {
568 						if (element) {
569 							element.html(html);
570 							GCN.pub('content-inserted', [element, html]);
571 						}
572 
573 						if (success) {
574 							success(html, that, data);
575 						}
576 
577 						initializeFrontendEditing(tags.editables, tags.blocks,
578 							parent.id(), element);
579 
580 						that._vacate();
581 					});
582 				}, function () {
583 					that._vacate();
584 				});
585 			}, error);
586 		},
587 
588 		/**
589 		 * Render the tag based on its settings on the server.
590 		 * Can be called with the following arguments:
591 		 *
592 		 * Do nothing:
593 		 * render()
594 		 *
595 		 * Render tag contents into div whose id is "content-div":
596 		 * @param {string|jQuery.<HTMLElement>}
597 		 * render('#content-div') or render(jQuery('#content-div'))
598 		 *
599 		 * Pass the html rendering of the tag in the given callback:
600 		 * @param {function(string, GCN.TagAPI)}
601 		 * render(function (html, tag) {})
602 		 *
603 		 * Whenever a 2nd argument is provided, it will be taken as as custom
604 		 * error handler.
605 		 */
606 		render: function () {
607 			var that = this;
608 			var args = arguments;
609 
610 			// Wait until DOM is ready
611 			jQuery(function () {
612 				args = getRenderOptions(args);
613 
614 				if (args.element || args.success) {
615 					that._render('view', args.element, args.success,
616 						args.error);
617 				}
618 			});
619 		},
620 
621 		/**
622 		 * Like `render()', except that the content is rendered with additional
623 		 * elements that are required for front-end editing. ie: editables.
624 		 */
625 		edit: function () {
626 			var that = this;
627 			var args = arguments;
628 
629 			// Wait until DOM is ready
630 			jQuery(function () {
631 				args = getRenderOptions(args);
632 
633 				if (args.element || args.success) {
634 					that._render('edit', args.element, args.success,
635 						args.error);
636 				}
637 			});
638 		},
639 
640 		/**
641 		 * Persists the changes to this tag on its container object.
642 		 *
643 		 * @param {function(TagAPI)} success Callback to be invoked when this
644 		 *                                   operation completes normally.
645 		 * @param {function(GCNError):boolean} error Custom error handler.
646 		 */
647 		save: function (success, error) {
648 			var that = this;
649 			this.parent().save(function () {
650 				if (success) {
651 					success(that);
652 				}
653 			}, error);
654 		}
655 
656 	});
657 
658 	// Unlike content objects, tags do not have unique ids and so we uniquely I
659 	// dentify tags by their name, and their parent's id.
660 	TagAPI._needsChainedHash = true;
661 
662 	GCN.tag = GCN.exposeAPI(TagAPI);
663 	GCN.TagAPI = TagAPI;
664 
665 }(GCN));
666