1 (function (GCN) {
  2 
  3 	'use strict';
  4 
  5 	/**
  6 	 * Updates the internal data of the given content object.
  7 	 *
  8 	 * This function extends and overwrites properties of the instances's
  9 	 * internal data structure.  No property is deleted on account of being
 10 	 * absent from the given `props' object.
 11 	 *
 12 	 * @param {ContentObjectAPI} obj An instance whose internal data is to be
 13 	 *                               reset.
 14 	 * @param {object} props The properties with which to replace the internal
 15 	 *                       data of the given chainback instance.
 16 	 */
 17 	function update(obj, props) {
 18 		jQuery.extend(obj._data, props);
 19 	}
 20 
 21 	/**
 22 	 * The prefix that will be temporarily applied to block tags during an
 23 	 * encode() process.
 24 	 *
 25 	 * @type {string}
 26 	 * @const
 27 	 */
 28 	var BLOCK_ENCODING_PREFIX = 'GCN_BLOCK_TMP__';
 29 
 30 	/**
 31 	 * Will match <span id="GENTICS_block_123"></span>" but not "<node abc123>"
 32 	 * tags.  The first backreference contains the tagname of the tag
 33 	 * corresponding to this block.
 34 	 *
 35 	 * Limitation: Will not work with unicode characters.
 36 	 *
 37 	 * @type {RexExp}
 38 	 * @const
 39 	 */
 40     var CONTENT_BLOCK = new RegExp(
 41 			// "<span" or "<div" but not "<node"
 42 			'<(?!node)[a-z]+'            +
 43 				// "class=... data-*..."
 44 				'(?:\\s+[^/<>\\s=]+(?:=(?:"[^"]*"|\'[^\']*\'|[^>/\\s]+))?)*?' +
 45 				// " id = "
 46 				'\\s+id\\s*=\\s*["\']?'  +
 47 				// "GCN_BLOCK_TMP__"
 48 				BLOCK_ENCODING_PREFIX    +
 49 				// "_abc-123"
 50 				'([^"\'/<>\\s=]*)["\']?' +
 51 				// class=... data-*...
 52 				'(?:\\s+[^/<>\\s=]+(?:=(?:"[^"]*"|\'[^\']*\'|[^>/\\s]+))?)*' +
 53 				// "' ...></span>" or "</div>"
 54 				'\\s*></[a-z]+>',
 55 			'gi'
 56 		);
 57 
 58 	/**
 59 	 * Will match <node foo> or <node bar_123> or <node foo-bar> but not
 60 	 * <node "blah">.
 61 	 *
 62 	 * @type {RegExp}
 63 	 * @const
 64 	 */
 65 	var NODE_NOTATION = /<node ([a-z0-9_\-]+?)>/gim;
 66 
 67 	/**
 68 	 * Examines a string for "<node>" tags, and for each occurance of this
 69 	 * notation, the given callback will be invoked to manipulate the string.
 70 	 *
 71 	 * @private
 72 	 * @static
 73 	 * @param {string} str The string that will be examined for "<node>" tags.
 74 	 * @param {function} onMatchFound Callback function that should receive the
 75 	 *                                following three parameters:
 76 	 *
 77 	 *                    name:string The name of the tag being notated by the
 78 	 *                                node substring.  If the `str' arguments
 79 	 *                                is "<node myTag>", then the `name' value
 80 	 *                                will be "myTag".
 81 	 *                  offset:number The offset where the node substring was
 82 	 *                                found within the examined string.
 83 	 *                     str:string The string in which the "<node *>"
 84 	 *                                substring occured.
 85 	 *
 86 	 *                                The return value of the function will
 87 	 *                                replace the entire "<node>" substring
 88 	 *                                that was passed to it within the examined
 89 	 *                                string.
 90 	 */
 91 	function replaceNodeTags(str, onMatchFound) {
 92 		var parsed = str.replace(NODE_NOTATION, function (substr, tagname,
 93 		                                                  offset, examined) {
 94 				return onMatchFound(tagname, offset, examined);
 95 			});
 96 		return parsed;
 97 	}
 98 
 99 	/*
100 	 * have a look at _init 
101 	 */
102 	GCN.ContentObjectAPI = GCN.defineChainback({
103 		/** @lends ContentObjectAPI */
104 
105 		/**
106 		 * @private
107 		 * @type {string} A string denoting a content node type.  This value is
108 		 *                used to compose the correct REST API ajax urls.  The
109 		 *                following are valid values: "node", "folder",
110 		 *                "template", "page", "file", "image".
111 		 */
112 		_type: null,
113 
114 		/**
115 		 * @private
116 		 * @type {object<string,*>} An internal object to store data that we
117 		 *                          get from the server.
118 		 */
119 		_data: {},
120 
121 		/**
122 		 * @private
123 		 * @type {object<string,*>} An internal object to store updates to
124 		 *                          the content object.  Should reflect the
125 		 *                          structural typography of the `_data'
126 		 *                          object.
127 		 */
128 		_shadow: {},
129 
130 		/**
131 		 * @type {boolean} Flags whether or not data for this content object have
132 		 *                 been fetched from the server.
133 		 */
134 		_fetched: false,
135 
136 		/**
137 		 * @private
138 		 * @type {object} will contain an objects internal settings
139 		 */
140 		_settings: null,
141 
142 		/**
143 		 * An array of all properties of an object that can be changed by the
144 		 * user. Writeable properties for all content objects.
145 		 * 
146 		 * @public
147 		 * @type {Array.string}
148 		 */
149 		WRITEABLE_PROPS: [],
150 
151 		/**
152 		 * <p>This object can contain various contrains for writeable props. 
153 		 * Those contrains will be checked when the user tries to set/save a
154 		 * property. Currently only maxLength is beeing handled.</p>
155 		 *
156 		 * <p>Example:</p>
157 		 * <pre>WRITEABLE_PROPS_CONSTRAINTS: {
158 		 *    'name': {
159 		 *        maxLength: 255
160 		 *     } 
161 		 * }</pre>
162 		 * @type {object}
163 		 * @const
164 		 *
165 		 */
166 		WRITEABLE_PROPS_CONSTRAINTS: {},
167 
168 		/**
169 		 * Fetches this content object's data from the backend.
170 		 *
171 		 * @ignore
172 		 * @param {function(object)} success A function to receive the server
173 		 *                                   response.
174 		 * @param {function(GCNError):boolean} error Optional custrom error
175 		 *                                           handler.
176 		 */
177 		'!fetch': function (success, error, stack) {
178 			var obj = this;
179 			var ajax = function () {
180 				obj._authAjax({
181 					url: GCN.settings.BACKEND_PATH + '/rest/' + obj._type +
182 					     '/load/' + obj.id() + GCN._getChannelParameter(obj),
183 					data: obj._loadParams(),
184 					error: error,
185 					success: success
186 				});
187 			};
188 
189 			// If this chainback object has an ancestor, then invoke that
190 			// parent's `_read()' method before fetching the data for this
191 			// chainback object.
192 			if (obj._chain) {
193 				var circularReference =
194 						stack && -1 < jQuery.inArray(obj._chain, stack);
195 				if (!circularReference) {
196 					stack = stack || [];
197 					stack.push(obj._chain);
198 					obj._chain._read(ajax, error, stack);
199 					return;
200 				}
201 			}
202 
203 			ajax();
204 		},
205 
206 		/**
207 		 * Internal method, to fetch this object's data from the server.
208 		 *
209 		 * @ignore
210 		 * @private
211 		 * @param {function(ContentObjectAPI)=} success Optional callback that
212 		 *                                              receives this object as
213 		 *                                              its only argument.
214 		 * @param {function(GCNError):boolean=} error Optional customer error
215 		 *                                            handler.
216 		 */
217 		'!_read': function (success, error, stack) {
218 			var obj = this;
219 			if (obj._fetched) {
220 				if (success) {
221 					obj._invoke(success, [obj]);
222 				}
223 				return;
224 			}
225 
226 			if (obj.multichannelling) {
227 				obj.multichannelling.read(obj, success, error);
228 				return;
229 			}
230 
231 			var id = obj.id();
232 
233 			if (null === id || undefined === id) {
234 				obj._getIdFromParent(function () {
235 					obj._read(success, error, stack);
236 				}, error, stack);
237 				return;
238 			}
239 
240 			obj.fetch(function (response) {
241 				obj._processResponse(response);
242 				obj._fetched = true;
243 				if (success) {
244 					obj._invoke(success, [obj]);
245 				}
246 			}, error, stack);
247 		},
248 
249 		/**
250 		 * Retrieves this object's id from its parent.  This function is used
251 		 * in order for this object to be able to fetch its data from the
252 		 * backend.
253 		 *
254 		 * FIXME: If the id that `obj` aquires results in it having a hash that
255 		 * is found in the cache, then `obj` should not replace the object that
256 		 * was in the cache, rather, `obj` should be masked by the object in the
257 		 * cache.  This scenario will arise in the following scenario:
258 		 *
259 		 * page.node().constructs();
260 		 * page.node().folders();
261 		 *
262 		 * The above will cause the same node to be fetched from the server
263 		 * twice, each time, clobbering the previosly loaded data in the cache.
264 		 *
265 		 * @ignore
266 		 * @private
267 		 * @param {function(ContentObjectAPI)=} success Optional callback that
268 		 *                                              receives this object as
269 		 *                                              its only argument.
270 		 * @param {function(GCNError):boolean=} error Optional customer error
271 		 *                                            handler.
272 		 * @throws CANNOT_GET_OBJECT_ID
273 		 */
274 		'!_getIdFromParent': function (success, error, stack) {
275 			var parent = this._ancestor();
276 
277 			if (!parent) {
278 				var err = GCN.createError('CANNOT_GET_OBJECT_ID',
279 					'Cannot get an id for object', this);
280 				GCN.handleError(err, error);
281 				return;
282 			}
283 
284 			var that = this;
285 
286 			parent._read(function () {
287 				if ('folder' === that._type) {
288 					// There are 3 possible property names that an object can
289 					// use to hold the id of the folder that it is related to:
290 					//
291 					// "folderId": for pages, templates, files, and images.
292 					// "motherId": for folders
293 					// "nodeId":   for nodes
294 					//
295 					// We need to see which of this properties is set, the
296 					// first one we find will be our folder's id.
297 					var props = ['folderId', 'motherId', 'nodeId'];
298 					var prop = props.pop();
299 					var id;
300 
301 					while (prop) {
302 						id = parent.prop(prop);
303 						if (typeof id !== 'undefined') {
304 							break;
305 						}
306 						prop = props.pop();
307 					}
308 
309 					that._data.id = id;
310 				} else {
311 					that._data.id = parent.prop(that._type + 'Id');
312 				}
313 
314 				if (that._data.id === null || typeof that._data.id === 'undefined') {
315 					var err = GCN.createError('CANNOT_GET_OBJECT_ID',
316 						'Cannot get an id for object', this);
317 					GCN.handleError(err, error);
318 					return;
319 				}
320 
321 				that._setHash(that._data.id)._addToCache();
322 
323 				if (success) {
324 					success();
325 				}
326 			}, error, stack);
327 		},
328 
329 		/**
330 		 * Gets this object's node id. If used in a multichannelling is enabled
331 		 * it will return the channel id or 0 if no channel was set.
332 		 * 
333 		 * @public
334 		 * @function
335 		 * @name nodeId
336 		 * @memberOf ContentObjectAPI
337 		 * @return {number} The channel to which this object is set. 0 if no
338 		 *         channel is set.
339 		 */
340 		'!nodeId': function () {
341 			return this._channel || 0;
342 		},
343 
344 		/**
345 		 * Gets this object's id. We'll return the id of the object when it has
346 		 * been loaded - this can only be a localid. Otherwise we'll return the
347 		 * id which was provided by the user. This can either be a localid or a
348 		 * globalid.
349 		 *
350 		 * @name id
351 		 * @function
352 		 * @memberOf ContentObjectAPI
353 		 * @public
354 		 * @return {number}
355 		 */
356 		'!id': function () {
357 			return this._data.id;
358 		},
359 
360 		/**
361 		 * Alias for {@link ContentObjectAPI#id}
362 		 *
363 		 * @name localId
364 		 * @function
365 		 * @memberOf ContentObjectAPI
366 		 * @private
367 		 * @return {number}
368 		 * @decprecated
369 		 */
370 		'!localId': function () {
371 			return this.id();
372 		},
373 
374 		/**
375 		 * Update the `_shadow' object that maintains changes to properties
376 		 * that reflected the internal `_data' object.  This shadow object is
377 		 * used to persist differential changes to a REST API object.
378 		 *
379 		 * @ignore
380 		 * @private
381 		 * @param {string} path The path through the object to the property we
382 		 *                      want to modify if a node in the path contains
383 		 *                      dots, then these dots should be escaped.  This
384 		 *                      can be done using the GCN.escapePropertyName()
385 		 *                      convenience function.
386 		 * @param {*} value The value we wish to set the property to.
387 		 * @param {function=} error Custom error handler.
388 		 * @param {boolean=} force If true, no error will be thrown if `path'
389 		 *                         cannot be fully resolved against the
390 		 *                         internal `_data' object, instead, the path
391 		 *                         will be created on the shadow object.
392 		 */
393 		'!_update': function (pathStr, value, error, force) {
394 			var boundary = Math.random().toString(8).substring(2);
395 			var path = pathStr.replace(/\./g, boundary)
396 			                  .replace(new RegExp('\\\\' + boundary, 'g'), '.')
397 			                  .split(boundary);
398 			var shadow = this._shadow;
399 			var actual = this._data;
400 			var i = 0;
401 			var numPathNodes = path.length;
402 			var pathNode;
403 			// Whether or not the traversal path in `_data' and `_shadow' are
404 			// at the same position in the respective objects.
405 			var areMirrored = true;
406 
407 			while (true) {
408 				pathNode = path[i++];
409 
410 				if (areMirrored) {
411 					actual = actual[pathNode];
412 					areMirrored = jQuery.type(actual) !== 'undefined';
413 				}
414 
415 				if (i === numPathNodes) {
416 					break;
417 				}
418 
419 				if (shadow[pathNode]) {
420 					shadow = shadow[pathNode];
421 				} else if (areMirrored || force) {
422 					shadow = (shadow[pathNode] = {});
423 				} else {
424 					break; // goto error
425 				}
426 			}
427 
428 			if (i === numPathNodes && (areMirrored || force)) {
429 				shadow[pathNode] = value;
430 			} else {
431 				var err = GCN.createError('TYPE_ERROR', 'Object "' +
432 					path.slice(0, i).join('.') + '" does not exist',
433 					actual);
434 				GCN.handleError(err, error);
435 			}
436 		},
437 
438 		/**
439 		 * Receives the response from a REST API request, and stores it in the
440 		 * internal `_data' object.
441 		 *
442 		 * @private
443 		 * @param {object} data Parsed JSON response data.
444 		 */
445 		'!_processResponse': function (data) {
446 			jQuery.extend(this._data, data[this._type]);
447 		},
448 
449 		/**
450 		 * Specifies a list of parameters that will be added to the url when
451 		 * loading the content object from the server.
452 		 *
453 		 * @private
454 		 * @return {object} object With parameters to be appended to the load
455 		 *                         request
456 		 */
457 		'!_loadParams': function () {},
458 
459 		/**
460 		 * Reads the property `property' of this content object if this
461 		 * property is among those in the WRITEABLE_PROPS array. If a second
462 		 * argument is provided, them the property is updated with that value.
463 		 *
464 		 * @name prop
465 		 * @function
466 		 * @memberOf ContentObjectAPI
467 		 * @param {String} property Name of the property to be read or updated.
468 		 * @param {String} value Optional value to set property to. If omitted the property will just be read.
469 		 * @param {function(GCNError):boolean=} error Custom error handler to 
470 		 *                                      stop error propagation for this
471 		 *                                      synchronous call. 
472 		 * @return {?*} Meta attribute.
473 		 * @throws UNFETCHED_OBJECT_ACCESS if the object has not been fetched from the server yet
474 		 * @throws READONLY_ATTRIBUTE whenever trying to write to an attribute that's readonly
475 		 */
476 		'!prop': function (property, value, error) {
477 			if (!this._fetched) {
478 				GCN.handleError(GCN.createError(
479 					'UNFETCHED_OBJECT_ACCESS',
480 					'Object not fetched yet.'
481 				), error);
482 				return;
483 			}
484 
485 			if (typeof value !== 'undefined') {
486 				// Check whether the property is writable
487 				if (jQuery.inArray(property, this.WRITEABLE_PROPS) >= 0) {
488 					// Check wether the property has a constraint and verify it
489 					var constraint = this.WRITEABLE_PROPS_CONSTRAINTS[property];
490 					if (constraint) {
491 						// verify maxLength
492 						if (constraint.maxLength && value.length >= constraint.maxLength) {
493 							var data = { name: property, value: value, maxLength: constraint.maxLength };
494 							var constraintError = GCN.createError('ATTRIBUTE_CONSTRAINT_VIOLATION',
495 								'Attribute "' + property + '" of ' + this._type +
496 								' is too long. The \'maxLength\' was set to {' + constraint.maxLength + '} ', data);
497 							GCN.handleError(constraintError, error);
498 							return;
499 						}
500 					}
501 					this._update(GCN.escapePropertyName(property), value);
502 				} else {
503 					GCN.handleError(GCN.createError('READONLY_ATTRIBUTE',
504 						'Attribute "' + property + '" of ' + this._type +
505 						' is read-only. Writeable properties are: ' +
506 						this.WRITEABLE_PROPS, this.WRITEABLE_PROPS), error);
507 					return;
508 				}
509 			}
510 
511 			return (
512 				(jQuery.type(this._shadow[property]) !== 'undefined'
513 					? this._shadow
514 					: this._data)[property]
515 			);
516 		},
517 
518 		/**
519 		 * Sends the a template string to the Aloha Servlet for rendering.
520 		 *
521 		 * @ignore
522 		 * @TODO: Consider making this function public.  At least one developer
523 		 *        has had need to render a custom template for a content
524 		 *        object.
525 		 *
526 		 * @private
527 		 * @param {string} template Template which will be rendered.
528 		 * @param {string} mode The rendering mode.  Valid values are "view",
529 		 *                      "edit", "pub."
530 		 * @param {function(object)} success A callback the receives the render
531 		 *                                   response.
532 		 * @param {function(GCNError):boolean} error Error handler.
533 		 */
534 		'!_renderTemplate' : function (template, mode, success, error) {
535 			var channelParam = GCN._getChannelParameter(this);
536 			var url = GCN.settings.BACKEND_PATH
537 			        + '/rest/' + this._type
538 			        + '/render/' + this.id()
539 			        + channelParam
540 			        + (channelParam ? '&' : '?')
541 			        + 'edit=' + ('edit' === mode)
542 			        + '&template=' + encodeURIComponent(template);
543 			this._authAjax({
544 				url: url,
545 				error: error,
546 				success: success
547 			});
548 		},
549 
550 		/**
551 		 * Wrapper for internal chainback _ajax method.
552 		 * 
553 		 * @ignore
554 		 * @private
555 		 * @param {object<string, *>} settings Settings for the ajax request.
556 		 *                                     The settings object is identical
557 		 *                                     to that of the `GCN.ajax'
558 		 *                                     method, which handles the actual
559 		 *                                     ajax transportation.
560 		 * @throws AJAX_ERROR
561 		 */
562 		'!_ajax': function (settings) {
563 			var that = this;
564 
565 			// force no cache for all API calls
566 			settings.cache = false;
567 			settings.success = (function (onSuccess, onError) {
568 				return function (data) {
569 					// Ajax calls that do not target the REST API servlet do
570 					// not response data with a `responseInfo' object.
571 					// "/CNPortletapp/alohatag" is an example.  So we cannot
572 					// just assume that it exists.
573 					if (data.responseInfo) {
574 						switch (data.responseInfo.responseCode) {
575 						case 'OK':
576 							break;
577 						case 'AUTHREQUIRED':
578 							GCN.clearSession();
579 							that._authAjax(settings);
580 							return;
581 						default:
582 							GCN.handleResponseError(data, onError);
583 							return;
584 						}
585 					}
586 
587 					if (onSuccess) {
588 						onSuccess(data);
589 					}
590 				};
591 			}(settings.success, settings.error, settings.url));
592 
593 			this._queueAjax(settings);
594 		},
595 
596 		/**
597 		 * Concrete implementatation of _fulfill().
598 		 *
599 		 * Resolves all promises made by this content object while ensuring
600 		 * that circularReferences, (which are completely possible, and valid)
601 		 * do not result in infinit recursion.
602 		 *
603 		 * @override
604 		 */
605 		'!_fulfill': function (success, error, stack) {
606 			var obj = this;
607 			if (obj._chain) {
608 				var circularReference =
609 						stack && -1 < jQuery.inArray(obj._chain, stack);
610 				if (!circularReference) {
611 					stack = stack || [];
612 					stack.push(obj._chain);
613 					obj._fulfill(function () {
614 						obj._read(success, error);
615 					}, error, stack);
616 					return;
617 				}
618 			}
619 			obj._read(success, error);
620 		},
621 
622 		/**
623 		 * Similar to `_ajax', except that it prefixes the ajax url with the
624 		 * current session's `sid', and will trigger an
625 		 * `authentication-required' event if the session is not authenticated.
626 		 *
627 		 * @ignore
628 		 * @TODO(petro): Consider simplifiying this function signature to read:
629 		 *               `_auth( url, success, error )'
630 		 *
631 		 * @private
632 		 * @param {object<string, *>} settings Settings for the ajax request.
633 		 * @throws AUTHENTICATION_FAILED
634 		 */
635 		_authAjax: function (settings) {
636 			var that = this;
637 
638 			if (GCN.isAuthenticating) {
639 				GCN.afterNextAuthentication(function () {
640 					that._authAjax(settings);
641 				});
642 				return;
643 			}
644 
645 			if (!GCN.sid) {
646 				var cancel;
647 
648 				if (settings.error) {
649 					/**
650 					 * @ignore
651 					 */
652 					cancel = function (error) {
653 						GCN.handleError(
654 							error || GCN.createError('AUTHENTICATION_FAILED'),
655 							settings.error
656 						);
657 					};
658 				} else {
659 					/**
660 					 * @ignore
661 					 */
662 					cancel = function (error) {
663 						if (error) {
664 							GCN.error(error.code, error.message, error.data);
665 						} else {
666 							GCN.error('AUTHENTICATION_FAILED');
667 						}
668 					};
669 				}
670 
671 				GCN.afterNextAuthentication(function () {
672 					that._authAjax(settings);
673 				});
674 
675 				if (GCN.usingSSO) {
676 					// First, try to automatically authenticate via
677 					// Single-SignOn
678 					GCN.loginWithSSO(GCN.onAuthenticated, function () {
679 						// ... if SSO fails, then fallback to requesting user
680 						// credentials: broadcast `authentication-required'
681 						// message.
682 						GCN.authenticate(cancel);
683 					});
684 				} else {
685 					// Trigger the `authentication-required' event to request
686 					// user credentials.
687 					GCN.authenticate(cancel);
688 				}
689 
690 				return;
691 			}
692 
693 			// Append "?sid=..." or "&sid=..." if needed.
694 
695 			var urlFragment = settings.url.substr(
696 				GCN.settings.BACKEND_PATH.length
697 			);
698 			var isSidInUrl = /[\?\&]sid=/.test(urlFragment);
699 			if (!isSidInUrl) {
700 				var isFirstParam = (jQuery.inArray('?',
701 					urlFragment.split('')) === -1);
702 				settings.url += (isFirstParam ? '?' : '&') + 'sid='
703 				             +  (GCN.sid || '');
704 			}
705 
706 			this._ajax(settings);
707 		},
708 
709 		/**
710 		 * Recursively call `_continueWith()'.
711 		 *
712 		 * @ignore
713 		 * @private
714 		 * @override
715 		 */
716 		'!_onContinue': function (success, error) {
717 			var that = this;
718 			this._continueWith(function () {
719 				that._read(success, error);
720 			}, error);
721 		},
722 
723 		/**
724 		 * Initializes this content object.  If a `success' callback is
725 		 * provided, it will cause this object's data to be fetched and passed
726 		 * to the callback.  This object's data will be fetched from the cache
727 		 * if is available, otherwise it will be fetched from the server.  If
728 		 * this content object API contains parent chainbacks, it will get its
729 		 * parent to fetch its own data first.
730 		 *
731 		 * <p>
732 		 * Basic content object implementation which all other content objects
733 		 * will inherit from.
734 		 * </p>
735 		 * 
736 		 * <p>
737 		 * If a `success' callback is provided,
738 		 * it will cause this object's data to be fetched and passed to the
739 		 * callback. This object's data will be fetched from the cache if is
740 		 * available, otherwise it will be fetched from the server. If this
741 		 * content object API contains parent chainbacks, it will get its parent
742 		 * to fetch its own data first.
743 		 * </p>
744 		 * 
745 		 * <p>
746 		 * You might also provide an object for initialization, to directly
747 		 * instantiate the object's data without loading it from the server. To
748 		 * do so just pass in a data object as received from the server instead
749 		 * of an id--just make sure this object has an `id' property.
750 		 * </p>
751 		 * 
752 		 * <p>
753 		 * If an `error' handler is provided, as the third parameter, it will
754 		 * catch any errors that have occured since the invocation of this call.
755 		 * It allows the global error handler to be intercepted before stopping
756 		 * the error or allowing it to propagate on to the global handler.
757 		 * </p>
758 		 * 
759 		 * @class
760 		 * @name ContentObjectAPI
761 		 * @param {number|string|object}
762 		 *            id
763 		 * @param {function(ContentObjectAPI))=}
764 		 *            success Optional success callback that will receive this
765 		 *            object as its only argument.
766 		 * @param {function(GCNError):boolean=}
767 		 *            error Optional custom error handler.
768 		 * @param {object}
769 		 *            settings Basic settings for this object - depends on the
770 		 *            ContentObjetAPI Object used.
771 		 * @throws INVALID_DATA
772 		 *             If no id is found when providing an object for
773 		 *             initialization.
774 		 */
775 		_init: function (data, success, error, settings) {
776 			this._settings = settings;
777 			var id;
778 
779 			if (jQuery.type(data) === 'object') {
780 				if (data.multichannelling) {
781 					this.multichannelling = data;
782 					// Remove the inherited object from the chain.
783 					if (this._chain) {
784 						this._chain = this._chain._chain;
785 					}
786 					id = this.multichannelling.derivedFrom.id();
787 				} else {
788 					if (!data.id) {
789 						var err = GCN.createError(
790 							'INVALID_DATA',
791 							'Data not sufficient for initalization: id is missing',
792 							data
793 						);
794 						GCN.handleError(err, error);
795 						return;
796 					}
797 					this._data = data;
798 					this._fetched = true;
799 					if (success) {
800 						this._invoke(success, [this]);
801 					}
802 					return;
803 				}
804 			} else {
805 				id = data;
806 			}
807 
808 			// Ensure that each object has its very own `_data' and `_shadow'
809 			// objects.
810 			if (!this._fetched) {
811 				this._data = {};
812 				this._shadow = {};
813 				this._data.id = id;
814 			}
815 			if (success) {
816 				this._read(success, error);
817 			}
818 		},
819 
820 		/**
821 		 * <p>Replaces tag blocks with appropriate "<node *>" notation in a given
822 		 * string. Given an element whose innerHTML is:<p>
823 		 * <pre>
824 		 *		<span id="GENTICS_BLOCK_123">My Tag</span>
825 		 * </pre>
826 		 * <p>encode() will return:</p>
827 		 * <pre>
828 		 *		<node 123>
829 		 * </pre>
830 		 *
831 		 * @name encode
832 		 * @function
833 		 * @memberOf ContentObjectAPI
834 		 * @param {!jQuery} $element
835 		 *       An element whose contents are to be encoded.
836 		 * @param {?function(!Element): string} serializeFn
837 		 *       A function that returns the serialized contents of the
838 		 *       given element as a HTML string, excluding the start and end
839 		 *       tag of the element. If not provided, jQuery.html() will
840 		 *       be used.
841 		 * @return {string} The encoded HTML string.
842 		 */
843 		'!encode': function ($element, serializeFn) {
844 			var $clone = $element.clone();
845 			var id;
846 			var $block;
847 			for (id in this._blocks) {
848 				if (this._blocks.hasOwnProperty(id)) {
849 					$block = $clone.find('#' + this._blocks[id].element);
850 					if ($block.length) {
851 						// Empty all content blocks of their innerHTML.
852 						$block.html('').attr('id', BLOCK_ENCODING_PREFIX +
853 							this._blocks[id].tagname);
854 					}
855 				}
856 			}
857 			serializeFn = serializeFn || function ($element) {
858 				return jQuery($element).html();
859 			};
860 			var html = serializeFn($clone[0]);
861 			return html.replace(CONTENT_BLOCK, function (substr, match) {
862 				return '<node ' + match + '>';
863 			});
864 		},
865 
866 		/**
867 		 * For a given string, replace all occurances of "<node>" with
868 		 * appropriate HTML markup, allowing notated tags to be rendered within
869 		 * the surrounding HTML content.
870 		 *
871 		 * The success() handler will receives a string containing the contents
872 		 * of the `str' string with references to "<node>" having been inflated
873 		 * into their appropriate tag rendering.
874 		 *
875 		 * @name decode
876 		 * @function
877 		 * @memberOf ContentObjectAPI
878 		 * @param {string} str The content string, in which  "<node *>" tags
879 		 *                     will be inflated with their HTML rendering.
880 		 * @param {function(ContentObjectAPI))} success Success callback that
881 		 *                                              will receive the
882 		 *                                              decoded string.
883 		 * @param {function(GCNError):boolean=} error Optional custom error
884 		 *                                            handler.
885 		 */
886 		'!decode': function (str, success, error) {
887 			if (!success) {
888 				return;
889 			}
890 
891 			var prefix = 'gcn-tag-placeholder-';
892 			var toRender = [];
893 			var html = replaceNodeTags(str, function (name, offset, str) {
894 				toRender.push('<node ', name, '>');
895 				return '<div id="' + prefix + name + '"></div>';
896 			});
897 
898 			if (!toRender.length) {
899 				success(html);
900 				return;
901 			}
902 
903 			// Instead of rendering each tag individually, we render them
904 			// together in one string, and map the results back into our
905 			// original html string.  This allows us to perform one request to
906 			// the server for any number of node tags found.
907 
908 			var parsed = jQuery('<div>' + html + '</div>');
909 			var template = toRender.join('');
910 			var that = this;
911 
912 			this._renderTemplate(template, 'edit', function (data) {
913 				var content = data.content;
914 				var tag;
915 				var tags = data.tags;
916 				var j = tags.length;
917 				var rendered = jQuery('<div>' + content + '</div>');
918 
919 				var replaceTag = (function (numTags) {
920 					return function (tag) {
921 						parsed.find('#' + prefix + tag.prop('name'))
922 							.replaceWith(
923 								rendered.find('#' + tag.prop('id'))
924 							);
925 
926 						if (0 === --numTags) {
927 							success(parsed.html());
928 						}
929 					};
930 				}(j));
931 
932 				while (j) {
933 					that.tag(tags[--j], replaceTag);
934 				}
935 			}, error);
936 		},
937 
938 		/**
939 		 * Clears this object from its constructor's cache so that the next
940 		 * attempt to access this object will result in a brand new instance
941 		 * being initialized and placed in the cache.
942 		 *
943 		 * @name clear
944 		 * @function
945 		 * @memberOf ContentObjectAPI
946 		 */
947 		'!clear': function () {
948 			// Do not clear the id from the _data.
949 			var id = this._data.id;
950 			this._data = {};
951 			this._data.id = id;
952 			this._shadow = {};
953 			this._fetched = false;
954 			this._clearCache();
955 		},
956 
957 		/**
958 		 * Retrieves this objects parent folder.
959 		 * 
960 		 * @name folder
961 		 * @function
962 		 * @memberOf ContentObjectAPI
963 		 * @param {function(FolderAPI)=}
964 		 *            success Callback that will receive the requested object.
965 		 * @param {function(GCNError):boolean=}
966 		 *            error Custom error handler.
967 		 * @return {FolderAPI} API object for the retrieved GCN folder.
968 		 */
969 		'!folder': function (success, error) {
970 			return this._continue(GCN.FolderAPI, this._data.folderId, success,
971 				error);
972 		},
973 
974 		/**
975 		 * Saves changes made to this content object to the backend.
976 		 * 
977 		 * @param {object=}
978 		 *            settings Optional settings to pass on to the ajax
979 		 *            function.
980 		 * @param {function(ContentObjectAPI)=}
981 		 *            success Optional callback that receives this object as its
982 		 *            only argument.
983 		 * @param {function(GCNError):boolean=}
984 		 *            error Optional customer error handler.
985 		 */
986 		save: function () {
987 			var settings;
988 			var success;
989 			var error;
990 			var args = Array.prototype.slice.call(arguments);
991 			var len = args.length;
992 			var i;
993 
994 			for (i = 0; i < len; ++i) {
995 				switch (jQuery.type(args[i])) {
996 				case 'object':
997 					if (!settings) {
998 						settings = args[i];
999 					}
1000 					break;
1001 				case 'function':
1002 					if (!success) {
1003 						success = args[i];
1004 					} else {
1005 						error = args[i];
1006 					}
1007 					break;
1008 				case 'undefined':
1009 					break;
1010 				default:
1011 					var err = GCN.createError('UNKNOWN_ARGUMENT',
1012 						'Don\'t know what to do with arguments[' + i + '] ' +
1013 						'value: "' + args[i] + '"', args);
1014 					GCN.handleError(err, error);
1015 					return;
1016 				}
1017 			}
1018 
1019 			this._save(settings, success, error);
1020 		},
1021 
1022 		/**
1023 		 * Persists this object's local data onto the server.  If the object
1024 		 * has not yet been fetched we need to get it first so we can update
1025 		 * its internals properly...
1026 		 *
1027 		 * @private
1028 		 * @param {object} settings Object which will extend the basic
1029 		 *                          settings of the ajax call
1030 		 * @param {function(ContentObjectAPI)=} success Optional callback that
1031 		 *                                              receives this object as
1032 		 *                                              its only argument.
1033 		 * @param {function(GCNError):boolean=} error Optional customer error
1034 		 *                                            handler.
1035 		 */
1036 		'!_save': function (settings, success, error) {
1037 			var obj = this;
1038 			this._fulfill(function () {
1039 				GCN.pub(obj._type + '.before-save');
1040 				obj._persist(settings, success, error);
1041 			}, error);
1042 		},
1043 
1044 		/**
1045 		 * Returns the bare data structure of this content object.
1046 		 * To be used for creating the save POST body data.
1047 		 *
1048 		 * @param {object<string, *>} Plain old object representation of this
1049 		 *                            content object.
1050 		 */
1051 		'!json': function () {
1052 			var json = {};
1053 
1054 			if (this._deletedTags.length) {
1055 				json['delete'] = this._deletedTags;
1056 			}
1057 
1058 			if (this._deletedBlocks.length) {
1059 				json['delete'] = json['delete']
1060 				               ? json['delete'].concat(this._deletedBlocks)
1061 				               : this._deletedBlocks;
1062 			}
1063 
1064 			json[this._type] = this._shadow;
1065 			json[this._type].id = this._data.id;
1066 			return json;
1067 		},
1068 
1069 		/**
1070 		 * Sends the current state of this content object to be stored on the
1071 		 * server.
1072 		 *
1073 		 * @private
1074 		 * @param {function(ContentObjectAPI)=} success Optional callback that
1075 		 *                                              receives this object as
1076 		 *                                              its only argument.
1077 		 * @param {function(GCNError):boolean=} error Optional customer error
1078 		 *                                            handler.
1079 		 * @throws HTTP_ERROR
1080 		 */
1081 		'!_persist': function (settings, success, error) {
1082 			var that = this;
1083 
1084 			if (!this._fetched) {
1085 				this._read(function () {
1086 					that._persist(settings, success, error);
1087 				}, error);
1088 				return;
1089 			}
1090 
1091 			var json = this.json();
1092 			jQuery.extend(json, settings);
1093 			var tags = json[this._type].tags;
1094 			var tagname;
1095 			for (tagname in tags) {
1096 				if (tags.hasOwnProperty(tagname)) {
1097 					tags[tagname].active = true;
1098 				}
1099 			}
1100 
1101 			this._authAjax({
1102 				url   : GCN.settings.BACKEND_PATH + '/rest/'
1103 				        + this._type + '/save/' + this.id()
1104 				        + GCN._getChannelParameter(this),
1105 				type  : 'POST',
1106 				error : error,
1107 				json  : json,
1108 				success : function (response) {
1109 					// We must not overwrite the `_data.tags' object with this
1110 					// one.
1111 					delete that._shadow.tags;
1112 
1113 					// Everything else in `_shadow' should be written over to
1114 					// `_data' before resetting the `_shadow' object.
1115 					jQuery.extend(that._data, that._shadow);
1116 					that._shadow = {};
1117 					that._deletedTags = [];
1118 					that._deletedBlocks = [];
1119 
1120 					if (success) {
1121 						that._invoke(success, [that]);
1122 					}
1123 				}
1124 			});
1125 		},
1126 
1127 		/**
1128 		 * Deletes this content object from its containing parent.
1129 		 * 
1130 		 * @param {function(ContentObjectAPI)=}
1131 		 *            success Optional callback that receives this object as its
1132 		 *            only argument.
1133 		 * @param {function(GCNError):boolean=}
1134 		 *            error Optional customer error handler.
1135 		 */
1136 		remove: function (success, error) {
1137 			this._remove(success, error);
1138 		},
1139 
1140 		/**
1141 		 * Get a channel-local copy of this content object.
1142 		 *
1143 		 * @public
1144 		 * @function
1145 		 * @name localize
1146 		 * @memberOf ContentObjectAPI
1147 		 * @param {funtion(ContentObjectAPI)=} success Optional callback to
1148 		 *                                             receive this content
1149 		 *                                             object as the only
1150 		 *                                             argument.
1151 		 * @param {function(GCNError):boolean=} error Optional custom error
1152 		 *                                            handler.
1153 		 */
1154 		'!localize': function (success, error) {
1155 			if (!this._channel && !GCN.channel()) {
1156 				var err = GCN.createError(
1157 					'NO_CHANNEL_ID_SET',
1158 					'No channel is set in which to get the localized object',
1159 					GCN
1160 				);
1161 				GCN.handleError(err, error);
1162 				return false;
1163 			}
1164 			var local = this._continue(
1165 				this._constructor,
1166 				{
1167 					derivedFrom: this,
1168 					multichannelling: true,
1169 					read: GCN.multichannelling.localize
1170 				},
1171 				success,
1172 				error
1173 			);
1174 			return local;
1175 		},
1176 
1177 		/**
1178 		 * Remove this channel-local object, and delete its local copy in the
1179 		 * backend.
1180 		 *
1181 		 * @public
1182 		 * @function
1183 		 * @name unlocalize
1184 		 * @memberOf ContentObjectAPI
1185 		 * @param {funtion(ContentObjectAPI)=} success Optional callback to
1186 		 *                                             receive this content
1187 		 *                                             object as the only
1188 		 *                                             argument.
1189 		 * @param {function(GCNError):boolean=} error Optional custom error
1190 		 *                                            handler.
1191 		 */
1192 		'!unlocalize': function (success, error) {
1193 			if (!this._channel && !GCN.channel()) {
1194 				var err = GCN.createError(
1195 					'NO_CHANNEL_ID_SET',
1196 					'No channel is set in which to get the unlocalized object',
1197 					GCN
1198 				);
1199 				GCN.handleError(err, error);
1200 				return false;
1201 			}
1202 			var placeholder = {
1203 				multichannelling: {
1204 					derivedFrom: this
1205 				}
1206 			};
1207 			var that = this;
1208 			GCN.multichannelling.unlocalize(placeholder, function () {
1209 				// TODO: This should be done inside of
1210 				// multichannelling.unlocalize() and not in this callback.
1211 				// Clean cache & reset object to make sure it can't be used
1212 				// properly any more.
1213 				that._clearCache();
1214 				that._data = {};
1215 				that._shadow = {};
1216 				if (success) {
1217 					success();
1218 				}
1219 			}, error);
1220 		},
1221 
1222 		/**
1223 		 * Performs a REST API request to delete this object from the server.
1224 		 *
1225 		 * @private
1226 		 * @param {function()=} success Optional callback that
1227 		 *                                              will be invoked once
1228 		 *                                              this object has been
1229 		 *                                              removed.
1230 		 * @param {function(GCNError):boolean=} error Optional customer error
1231 		 *                                            handler.
1232 		 */
1233 		'!_remove': function (success, error) {
1234 			var that = this;
1235 			this._authAjax({
1236 				url     : GCN.settings.BACKEND_PATH + '/rest/'
1237 				          + this._type + '/delete/' + this.id()
1238 				          + GCN._getChannelParameter(that),
1239 				type    : 'POST',
1240 				error   : error,
1241 				success : function (response) {
1242 					// Clean cache & reset object to make sure it can't be used
1243 					// properly any more.
1244 					that._clearCache();
1245 					that._data = {};
1246 					that._shadow = {};
1247 
1248 					// Don't forward the object to the success handler since
1249 					// it's been deleted.
1250 					if (success) {
1251 						that._invoke(success);
1252 					}
1253 				}
1254 			});
1255 		},
1256 
1257 		/**
1258 		 * Removes any additionaly data stored on this objec which pertains to
1259 		 * a tag matching the given tagname.  This function will be called when
1260 		 * a tag is being removed in order to bring the content object to a
1261 		 * consistant state.
1262 		 * Should be overriden by subclasses.
1263 		 *
1264 		 * @param {string} tagid The Id of the tag whose associated data we
1265 		 *                       want we want to remove.
1266 		 */
1267 		'!_removeAssociatedTagData': function (tagname) {}
1268 
1269 	});
1270 
1271 	GCN.ContentObjectAPI.update = update;
1272 
1273 	/**
1274 	 * Generates a factory method for chainback classes.  The method signature
1275 	 * used with this factory function will match that of the target class'
1276 	 * constructor.  Therefore this function is expected to be invoked with the
1277 	 * follow combination of arguments ...
1278 	 *
1279 	 * Examples for GCN.pages api:
1280 	 *
1281 	 * To get an array containing 1 page:
1282 	 * pages(1)
1283 	 * pages(1, function () {})
1284 	 *
1285 	 * To get an array containing 2 pages:
1286 	 * pages([1, 2])
1287 	 * pages([1, 2], function () {})
1288 	 *
1289 	 * To get an array containing any and all pages:
1290 	 * pages()
1291 	 * pages(function () {})
1292 	 *
1293 	 * To get an array containing no pages:
1294 	 * pages([])
1295 	 * pages([], function () {});
1296 	 *
1297 	 * @param {Chainback} ctor The Chainback constructor we want to expose.
1298 	 * @throws UNKNOWN_ARGUMENT
1299 	 */
1300 	GCN.exposeAPI = function (ctor) {
1301 		return function () {
1302 			// Convert arguments into an array
1303 			// https://developer.mozilla.org/en/JavaScript/Reference/...
1304 			// ...Functions_and_function_scope/arguments
1305 			var args = Array.prototype.slice.call(arguments);
1306 			var id;
1307 			var ids;
1308 			var success;
1309 			var error;
1310 			var settings;
1311 
1312 			// iterate over arguments to find id || ids, succes, error and
1313 			// settings
1314 			jQuery.each(args, function (i, arg) {
1315 				switch (jQuery.type(arg)) {
1316 				// set id
1317 				case 'string':
1318 				case 'number':
1319 					if (!id && !ids) {
1320 						id = arg;
1321 					} else {
1322 						GCN.error('UNKNOWN_ARGUMENT',
1323 							'id is already set. Don\'t know what to do with ' +
1324 							'arguments[' + i + '] value: "' + arg + '"');
1325 					}
1326 					break;
1327 				// set ids
1328 				case 'array':
1329 					if (!id && !ids) {
1330 						ids = args[0];
1331 					} else {
1332 						GCN.error('UNKNOWN_ARGUMENT',
1333 							'ids is already set. Don\'t know what to do with' +
1334 							' arguments[' + i + '] value: "' + arg + '"');
1335 					}
1336 					break;
1337 				// success and error handlers
1338 				case 'function':
1339 					if (!success) {
1340 						success = arg;
1341 					} else if (success && !error) {
1342 						error = arg;
1343 					} else {
1344 						GCN.error('UNKNOWN_ARGUMENT',
1345 							'success and error handler already set. Don\'t ' +
1346 							'know what to do with arguments[' + i + ']');
1347 					}
1348 					break;
1349 				// settings
1350 				case 'object':
1351 					if (!id && !ids) {
1352 						id = arg;
1353 					} else if (!settings) {
1354 						settings = arg;
1355 					} else {
1356 						GCN.error('UNKNOWN_ARGUMENT',
1357 							'settings are already present. Don\'t know what ' +
1358 							'to do with arguments[' + i + '] value:' + ' "' +
1359 							arg + '"');
1360 					}
1361 					break;
1362 				default:
1363 					GCN.error('UNKNOWN_ARGUMENT',
1364 						'Don\'t know what to do with arguments[' + i +
1365 						'] value: "' + arg + '"');
1366 				}
1367 			});
1368 
1369 			// Prepare a new set of arguments to pass on during initialzation
1370 			// of callee object.
1371 			args = [];
1372 
1373 			// settings should always be an object, even if it's just empty
1374 			if (!settings) {
1375 				settings = {};
1376 			}
1377 
1378 			args[0] = (typeof id !== 'undefined') ? id : ids;
1379 			args[1] = success || settings.success || null;
1380 			args[2] = error || settings.error || null;
1381 			args[3] = settings;
1382 
1383 			// We either add 0 (no channel) or the channelid to the hash
1384 			var channel = GCN.settings.channel;
1385 
1386 			// Check if the value is false, and set it to 0 in this case
1387 			if (!channel) {
1388 				channel = 0;
1389 			}
1390 
1391 			var hash = (id || ids)
1392 			         ? ctor._makeHash(channel + '/' + (ids ? ids.sort().join(',') : id))
1393 			         : null;
1394 
1395 			return GCN.getChainback(ctor, hash, null, args);
1396 		};
1397 
1398 	};
1399 
1400 }(GCN));
1401