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 adds any new data
440 		 * in the internal `_data' object.
441 		 *
442 		 * Note that data already present in `_data' will not be removed or
443 		 * overwritten.
444 		 *
445 		 * @private
446 		 * @param {object} data Parsed JSON response data.
447 		 */
448 		'!_processResponse': function (data) {
449 			this._data = jQuery.extend(true, {}, data[this._type], this._data);
450 		},
451 
452 		/**
453 		 * Specifies a list of parameters that will be added to the url when
454 		 * loading the content object from the server.
455 		 *
456 		 * @private
457 		 * @return {object} object With parameters to be appended to the load
458 		 *                         request
459 		 */
460 		'!_loadParams': function () {},
461 
462 		/**
463 		 * Reads the property `property' of this content object if this
464 		 * property is among those in the WRITEABLE_PROPS array. If a second
465 		 * argument is provided, them the property is updated with that value.
466 		 *
467 		 * @name prop
468 		 * @function
469 		 * @memberOf ContentObjectAPI
470 		 * @param {String} property Name of the property to be read or updated.
471 		 * @param {String} value Optional value to set property to. If omitted the property will just be read.
472 		 * @param {function(GCNError):boolean=} error Custom error handler to 
473 		 *                                      stop error propagation for this
474 		 *                                      synchronous call. 
475 		 * @return {?*} Meta attribute.
476 		 * @throws UNFETCHED_OBJECT_ACCESS if the object has not been fetched from the server yet
477 		 * @throws READONLY_ATTRIBUTE whenever trying to write to an attribute that's readonly
478 		 */
479 		'!prop': function (property, value, error) {
480 			if (!this._fetched) {
481 				GCN.handleError(GCN.createError(
482 					'UNFETCHED_OBJECT_ACCESS',
483 					'Object not fetched yet.'
484 				), error);
485 				return;
486 			}
487 
488 			if (typeof value !== 'undefined') {
489 				// Check whether the property is writable
490 				if (jQuery.inArray(property, this.WRITEABLE_PROPS) >= 0) {
491 					// Check wether the property has a constraint and verify it
492 					var constraint = this.WRITEABLE_PROPS_CONSTRAINTS[property];
493 					if (constraint) {
494 						// verify maxLength
495 						if (constraint.maxLength && value.length >= constraint.maxLength) {
496 							var data = { name: property, value: value, maxLength: constraint.maxLength };
497 							var constraintError = GCN.createError('ATTRIBUTE_CONSTRAINT_VIOLATION',
498 								'Attribute "' + property + '" of ' + this._type +
499 								' is too long. The \'maxLength\' was set to {' + constraint.maxLength + '} ', data);
500 							GCN.handleError(constraintError, error);
501 							return;
502 						}
503 					}
504 					this._update(GCN.escapePropertyName(property), value);
505 				} else {
506 					GCN.handleError(GCN.createError('READONLY_ATTRIBUTE',
507 						'Attribute "' + property + '" of ' + this._type +
508 						' is read-only. Writeable properties are: ' +
509 						this.WRITEABLE_PROPS, this.WRITEABLE_PROPS), error);
510 					return;
511 				}
512 			}
513 
514 			return (
515 				(jQuery.type(this._shadow[property]) !== 'undefined'
516 					? this._shadow
517 					: this._data)[property]
518 			);
519 		},
520 
521 		/**
522 		 * Sends the a template string to the Aloha Servlet for rendering.
523 		 *
524 		 * @ignore
525 		 * @TODO: Consider making this function public.  At least one developer
526 		 *        has had need to render a custom template for a content
527 		 *        object.
528 		 *
529 		 * @private
530 		 * @param {string} template Template which will be rendered.
531 		 * @param {string} mode The rendering mode.  Valid values are "view",
532 		 *                      "edit", "pub."
533 		 * @param {function(object)} success A callback the receives the render
534 		 *                                   response.
535 		 * @param {function(GCNError):boolean} error Error handler.
536 		 */
537 		'!_renderTemplate' : function (template, mode, success, error) {
538 			var channelParam = GCN._getChannelParameter(this);
539 			var url = GCN.settings.BACKEND_PATH +
540 			        '/rest/' + this._type +
541 			        '/render' +
542 			        channelParam +
543 			        (channelParam ? '&' : '?') +
544 			        'edit=' + ('edit' === mode) +
545 			        '&template=' + encodeURIComponent(template);
546 			if (mode === 'edit') {
547 				url += '&links=' + encodeURIComponent(GCN.settings.linksRenderMode);
548 			}
549 			this._authAjax({
550 				type: 'POST',
551 				json: this._data,
552 				url: url,
553 				error: error,
554 				success: success
555 			});
556 		},
557 
558 		/**
559 		 * Wrapper for internal chainback _ajax method.
560 		 * 
561 		 * @ignore
562 		 * @private
563 		 * @param {object<string, *>} settings Settings for the ajax request.
564 		 *                                     The settings object is identical
565 		 *                                     to that of the `GCN.ajax'
566 		 *                                     method, which handles the actual
567 		 *                                     ajax transportation.
568 		 * @throws AJAX_ERROR
569 		 */
570 		'!_ajax': function (settings) {
571 			var that = this;
572 
573 			// force no cache for all API calls
574 			settings.cache = false;
575 			settings.success = (function (onSuccess, onError) {
576 				return function (data) {
577 					// Ajax calls that do not target the REST API servlet do
578 					// not response data with a `responseInfo' object.
579 					// "/CNPortletapp/alohatag" is an example.  So we cannot
580 					// just assume that it exists.
581 					if (data.responseInfo) {
582 						switch (data.responseInfo.responseCode) {
583 						case 'OK':
584 							break;
585 						case 'AUTHREQUIRED':
586 							GCN.clearSession();
587 							that._authAjax(settings);
588 							return;
589 						default:
590 							// Since GCN.handleResponseError can throw an error,
591 							// we pass this function to _invoke, so the error is caught,
592 							// remembered and thrown in the end.
593 							that._invoke(GCN.handleResponseError, [data, onError]);
594 							return;
595 						}
596 					}
597 
598 					if (onSuccess) {
599 						onSuccess(data);
600 					}
601 				};
602 			}(settings.success, settings.error, settings.url));
603 
604 			this._queueAjax(settings);
605 		},
606 
607 		/**
608 		 * Concrete implementatation of _fulfill().
609 		 *
610 		 * Resolves all promises made by this content object while ensuring
611 		 * that circularReferences, (which are completely possible, and valid)
612 		 * do not result in infinit recursion.
613 		 *
614 		 * @override
615 		 */
616 		'!_fulfill': function (success, error, stack) {
617 			var obj = this;
618 			if (obj._chain) {
619 				var circularReference =
620 						stack && -1 < jQuery.inArray(obj._chain, stack);
621 				if (!circularReference) {
622 					stack = stack || [];
623 					stack.push(obj._chain);
624 					obj._fulfill(function () {
625 						obj._read(success, error);
626 					}, error, stack);
627 					return;
628 				}
629 			}
630 			obj._read(success, error);
631 		},
632 
633 		/**
634 		 * Similar to `_ajax', except that it prefixes the ajax url with the
635 		 * current session's `sid', and will trigger an
636 		 * `authentication-required' event if the session is not authenticated.
637 		 *
638 		 * @ignore
639 		 * @TODO(petro): Consider simplifiying this function signature to read:
640 		 *               `_auth( url, success, error )'
641 		 *
642 		 * @private
643 		 * @param {object<string, *>} settings Settings for the ajax request.
644 		 * @throws AUTHENTICATION_FAILED
645 		 */
646 		_authAjax: function (settings) {
647 			var that = this;
648 
649 			if (GCN.isAuthenticating) {
650 				GCN.afterNextAuthentication(function () {
651 					that._authAjax(settings);
652 				});
653 				return;
654 			}
655 
656 			if (!GCN.sid) {
657 				var cancel;
658 
659 				if (settings.error) {
660 					/**
661 					 * @ignore
662 					 */
663 					cancel = function (error) {
664 						GCN.handleError(
665 							error || GCN.createError('AUTHENTICATION_FAILED'),
666 							settings.error
667 						);
668 					};
669 				} else {
670 					/**
671 					 * @ignore
672 					 */
673 					cancel = function (error) {
674 						if (error) {
675 							GCN.error(error.code, error.message, error.data);
676 						} else {
677 							GCN.error('AUTHENTICATION_FAILED');
678 						}
679 					};
680 				}
681 
682 				GCN.afterNextAuthentication(function () {
683 					that._authAjax(settings);
684 				});
685 
686 				if (GCN.usingSSO) {
687 					// First, try to automatically authenticate via
688 					// Single-SignOn
689 					GCN.loginWithSSO(GCN.onAuthenticated, function () {
690 						// ... if SSO fails, then fallback to requesting user
691 						// credentials: broadcast `authentication-required'
692 						// message.
693 						GCN.authenticate(cancel);
694 					});
695 				} else {
696 					// Trigger the `authentication-required' event to request
697 					// user credentials.
698 					GCN.authenticate(cancel);
699 				}
700 
701 				return;
702 			}
703 
704 			// Append "?sid=..." or "&sid=..." if needed.
705 
706 			var urlFragment = settings.url.substr(
707 				GCN.settings.BACKEND_PATH.length
708 			);
709 			var isSidInUrl = /[\?\&]sid=/.test(urlFragment);
710 			if (!isSidInUrl) {
711 				var isFirstParam = (jQuery.inArray('?',
712 					urlFragment.split('')) === -1);
713 				settings.url += (isFirstParam ? '?' : '&') + 'sid='
714 				             +  (GCN.sid || '');
715 			}
716 
717 			this._ajax(settings);
718 		},
719 
720 		/**
721 		 * Recursively call `_continueWith()'.
722 		 *
723 		 * @ignore
724 		 * @private
725 		 * @override
726 		 */
727 		'!_onContinue': function (success, error) {
728 			var that = this;
729 			this._continueWith(function () {
730 				that._read(success, error);
731 			}, error);
732 		},
733 
734 		/**
735 		 * Initializes this content object.  If a `success' callback is
736 		 * provided, it will cause this object's data to be fetched and passed
737 		 * to the callback.  This object's data will be fetched from the cache
738 		 * if is available, otherwise it will be fetched from the server.  If
739 		 * this content object API contains parent chainbacks, it will get its
740 		 * parent to fetch its own data first.
741 		 *
742 		 * <p>
743 		 * Basic content object implementation which all other content objects
744 		 * will inherit from.
745 		 * </p>
746 		 * 
747 		 * <p>
748 		 * If a `success' callback is provided,
749 		 * it will cause this object's data to be fetched and passed to the
750 		 * callback. This object's data will be fetched from the cache if is
751 		 * available, otherwise it will be fetched from the server. If this
752 		 * content object API contains parent chainbacks, it will get its parent
753 		 * to fetch its own data first.
754 		 * </p>
755 		 * 
756 		 * <p>
757 		 * You might also provide an object for initialization, to directly
758 		 * instantiate the object's data without loading it from the server. To
759 		 * do so just pass in a data object as received from the server instead
760 		 * of an id--just make sure this object has an `id' property.
761 		 * </p>
762 		 * 
763 		 * <p>
764 		 * If an `error' handler is provided, as the third parameter, it will
765 		 * catch any errors that have occured since the invocation of this call.
766 		 * It allows the global error handler to be intercepted before stopping
767 		 * the error or allowing it to propagate on to the global handler.
768 		 * </p>
769 		 * 
770 		 * @class
771 		 * @name ContentObjectAPI
772 		 * @param {number|string|object}
773 		 *            id
774 		 * @param {function(ContentObjectAPI))=}
775 		 *            success Optional success callback that will receive this
776 		 *            object as its only argument.
777 		 * @param {function(GCNError):boolean=}
778 		 *            error Optional custom error handler.
779 		 * @param {object}
780 		 *            settings Basic settings for this object - depends on the
781 		 *            ContentObjetAPI Object used.
782 		 * @throws INVALID_DATA
783 		 *             If no id is found when providing an object for
784 		 *             initialization.
785 		 */
786 		_init: function (data, success, error, settings) {
787 			this._settings = settings;
788 			var id;
789 
790 			if (jQuery.type(data) === 'object') {
791 				if (data.multichannelling) {
792 					this.multichannelling = data;
793 					// Remove the inherited object from the chain.
794 					if (this._chain) {
795 						this._chain = this._chain._chain;
796 					}
797 					id = this.multichannelling.derivedFrom.id();
798 				} else {
799 					if (!data.id) {
800 						var err = GCN.createError(
801 							'INVALID_DATA',
802 							'Data not sufficient for initalization: id is missing',
803 							data
804 						);
805 						GCN.handleError(err, error);
806 						return;
807 					}
808 					this._data = data;
809 					this._fetched = true;
810 					if (success) {
811 						this._invoke(success, [this]);
812 					}
813 					return;
814 				}
815 			} else {
816 				id = data;
817 			}
818 
819 			// Ensure that each object has its very own `_data' and `_shadow'
820 			// objects.
821 			if (!this._fetched) {
822 				this._data = {};
823 				this._shadow = {};
824 				this._data.id = id;
825 			}
826 			if (success) {
827 				this._read(success, error);
828 			}
829 		},
830 
831 		/**
832 		 * <p>
833 		 * Replaces tag blocks and editables with appropriate "<node *>"
834 		 * notation in a given string. Given an element whose innerHTML is:
835 		 *
836 		 * <pre>
837 		 *		<span id="GENTICS_BLOCK_123">My Tag</span>
838 		 * </pre>
839 		 *
840 		 * <p>
841 		 * encode() will return:
842 		 *
843 		 * <pre>
844 		 *		<node 123>
845 		 * </pre>
846 		 *
847 		 * @name encode
848 		 * @function
849 		 * @memberOf ContentObjectAPI
850 		 * @param {!jQuery} $element
851 		 *       An element whose contents are to be encoded.
852 		 * @param {?function(!Element): string} serializeFn
853 		 *       A function that returns the serialized contents of the
854 		 *       given element as a HTML string, excluding the start and end
855 		 *       tag of the element. If not provided, jQuery.html() will
856 		 *       be used.
857 		 * @return {string} The encoded HTML string.
858 		 */
859 		'!encode': function ($element, serializeFn) {
860 			var $clone = $element.clone();
861 			var id;
862 			var $block;
863 			var tags = jQuery.extend({}, this._blocks, this._editables);
864 			for (id in tags) {
865 				if (tags.hasOwnProperty(id)) {
866 					$block = $clone.find('#' + tags[id].element);
867 					if ($block.length) {
868 						// Empty all content blocks of their innerHTML.
869 						$block.html('').attr('id', BLOCK_ENCODING_PREFIX +
870 							tags[id].tagname);
871 					}
872 				}
873 			}
874 			serializeFn = serializeFn || function ($element) {
875 				return jQuery($element).html();
876 			};
877 			var html = serializeFn($clone[0]);
878 			return html.replace(CONTENT_BLOCK, function (substr, match) {
879 				return '<node ' + match + '>';
880 			});
881 		},
882 
883 		/**
884 		 * For a given string, replace all occurances of "<node>" with
885 		 * appropriate HTML markup, allowing notated tags to be rendered within
886 		 * the surrounding HTML content.
887 		 *
888 		 * The success() handler will receives a string containing the contents
889 		 * of the `str' string with references to "<node>" having been inflated
890 		 * into their appropriate tag rendering.
891 		 *
892 		 * @name decode
893 		 * @function
894 		 * @memberOf ContentObjectAPI
895 		 * @param {string} str The content string, in which  "<node *>" tags
896 		 *                     will be inflated with their HTML rendering.
897 		 * @param {function(ContentObjectAPI))} success Success callback that
898 		 *                                              will receive the
899 		 *                                              decoded string.
900 		 * @param {function(GCNError):boolean=} error Optional custom error
901 		 *                                            handler.
902 		 */
903 		'!decode': function (str, success, error) {
904 			if (!success) {
905 				return;
906 			}
907 
908 			var prefix = 'gcn-tag-placeholder-';
909 			var toRender = [];
910 			var html = replaceNodeTags(str, function (name, offset, str) {
911 				toRender.push('<node ', name, '>');
912 				return '<div id="' + prefix + name + '"></div>';
913 			});
914 
915 			if (!toRender.length) {
916 				success(html);
917 				return;
918 			}
919 
920 			// Instead of rendering each tag individually, we render them
921 			// together in one string, and map the results back into our
922 			// original html string.  This allows us to perform one request to
923 			// the server for any number of node tags found.
924 
925 			var parsed = jQuery('<div>' + html + '</div>');
926 			var template = toRender.join('');
927 			var that = this;
928 
929 			this._renderTemplate(template, 'edit', function (data) {
930 				var content = data.content;
931 				var tag;
932 				var tags = data.tags;
933 				var j = tags.length;
934 				var rendered = jQuery('<div>' + content + '</div>');
935 
936 				var replaceTag = (function (numTags) {
937 					return function (tag) {
938 						parsed.find('#' + prefix + tag.prop('name'))
939 							.replaceWith(
940 								rendered.find('#' + tag.prop('id'))
941 							);
942 
943 						if (0 === --numTags) {
944 							success(parsed.html());
945 						}
946 					};
947 				}(j));
948 
949 				while (j) {
950 					that.tag(tags[--j], replaceTag);
951 				}
952 			}, error);
953 		},
954 
955 		/**
956 		 * Clears this object from its constructor's cache so that the next
957 		 * attempt to access this object will result in a brand new instance
958 		 * being initialized and placed in the cache.
959 		 *
960 		 * @name clear
961 		 * @function
962 		 * @memberOf ContentObjectAPI
963 		 */
964 		'!clear': function () {
965 			// Do not clear the id from the _data.
966 			var id = this._data.id;
967 			this._data = {};
968 			this._data.id = id;
969 			this._shadow = {};
970 			this._fetched = false;
971 			this._clearCache();
972 		},
973 
974 		/**
975 		 * Retrieves this objects parent folder.
976 		 * 
977 		 * @name folder
978 		 * @function
979 		 * @memberOf ContentObjectAPI
980 		 * @param {function(FolderAPI)=}
981 		 *            success Callback that will receive the requested object.
982 		 * @param {function(GCNError):boolean=}
983 		 *            error Custom error handler.
984 		 * @return {FolderAPI} API object for the retrieved GCN folder.
985 		 */
986 		'!folder': function (success, error) {
987 			return this._continue(GCN.FolderAPI, this._data.folderId, success,
988 				error);
989 		},
990 
991 		/**
992 		 * Saves changes made to this content object to the backend.
993 		 * 
994 		 * @param {object=}
995 		 *            settings Optional settings to pass on to the ajax
996 		 *            function.
997 		 * @param {function(ContentObjectAPI)=}
998 		 *            success Optional callback that receives this object as its
999 		 *            only argument.
1000 		 * @param {function(GCNError):boolean=}
1001 		 *            error Optional customer error handler.
1002 		 */
1003 		save: function () {
1004 			var settings;
1005 			var success;
1006 			var error;
1007 			var args = Array.prototype.slice.call(arguments);
1008 			var len = args.length;
1009 			var i;
1010 
1011 			for (i = 0; i < len; ++i) {
1012 				switch (jQuery.type(args[i])) {
1013 				case 'object':
1014 					if (!settings) {
1015 						settings = args[i];
1016 					}
1017 					break;
1018 				case 'function':
1019 					if (!success) {
1020 						success = args[i];
1021 					} else {
1022 						error = args[i];
1023 					}
1024 					break;
1025 				case 'undefined':
1026 					break;
1027 				default:
1028 					var err = GCN.createError('UNKNOWN_ARGUMENT',
1029 						'Don\'t know what to do with arguments[' + i + '] ' +
1030 						'value: "' + args[i] + '"', args);
1031 					GCN.handleError(err, error);
1032 					return;
1033 				}
1034 			}
1035 
1036 			this._save(settings, success, error);
1037 		},
1038 
1039 		/**
1040 		 * Persists this object's local data onto the server.  If the object
1041 		 * has not yet been fetched we need to get it first so we can update
1042 		 * its internals properly...
1043 		 *
1044 		 * @private
1045 		 * @param {object} settings Object which will extend the basic
1046 		 *                          settings of the ajax call
1047 		 * @param {function(ContentObjectAPI)=} success Optional callback that
1048 		 *                                              receives this object as
1049 		 *                                              its only argument.
1050 		 * @param {function(GCNError):boolean=} error Optional customer error
1051 		 *                                            handler.
1052 		 */
1053 		'!_save': function (settings, success, error) {
1054 			var obj = this;
1055 			this._fulfill(function () {
1056 				GCN.pub(obj._type + '.before-save');
1057 				obj._persist(settings, success, error);
1058 			}, error);
1059 		},
1060 
1061 		/**
1062 		 * Returns the bare data structure of this content object.
1063 		 * To be used for creating the save POST body data.
1064 		 *
1065 		 * @param {object<string, *>} Plain old object representation of this
1066 		 *                            content object.
1067 		 */
1068 		'!json': function () {
1069 			var json = {};
1070 
1071 			if (this._deletedTags.length) {
1072 				json['delete'] = this._deletedTags;
1073 			}
1074 
1075 			if (this._deletedBlocks.length) {
1076 				json['delete'] = json['delete']
1077 				               ? json['delete'].concat(this._deletedBlocks)
1078 				               : this._deletedBlocks;
1079 			}
1080 
1081 			json[this._type] = jQuery.extend(true, {}, this._shadow);
1082 			json[this._type].id = this._data.id;
1083 			return json;
1084 		},
1085 
1086 		/**
1087 		 * Sends the current state of this content object to be stored on the
1088 		 * server.
1089 		 *
1090 		 * @private
1091 		 * @param {function(ContentObjectAPI)=} success Optional callback that
1092 		 *                                              receives this object as
1093 		 *                                              its only argument.
1094 		 * @param {function(GCNError):boolean=} error Optional customer error
1095 		 *                                            handler.
1096 		 * @throws HTTP_ERROR
1097 		 */
1098 		_persist: function (settings, success, error) {
1099 			var that = this;
1100 
1101 			if (!this._fetched) {
1102 				this._read(function () {
1103 					that._persist(settings, success, error);
1104 				}, error);
1105 				return;
1106 			}
1107 
1108 			this._authAjax({
1109 				url   : GCN.settings.BACKEND_PATH + '/rest/'
1110 				        + this._type + '/save/' + this.id()
1111 				        + GCN._getChannelParameter(this),
1112 				type  : 'POST',
1113 				error : error,
1114 				json  : jQuery.extend(this.json(), settings),
1115 				success : function (response) {
1116 					// We must not overwrite the `_data.tags' object with this
1117 					// one.
1118 					delete that._shadow.tags;
1119 
1120 					// Everything else in `_shadow' should be written over to
1121 					// `_data' before resetting the `_shadow' object.
1122 					jQuery.extend(that._data, that._shadow);
1123 					that._shadow = {};
1124 					that._deletedTags = [];
1125 					that._deletedBlocks = [];
1126 
1127 					if (success) {
1128 						that._invoke(success, [that]);
1129 					}
1130 				}
1131 			});
1132 		},
1133 
1134 		/**
1135 		 * Deletes this content object from its containing parent.
1136 		 * 
1137 		 * @param {function(ContentObjectAPI)=}
1138 		 *            success Optional callback that receives this object as its
1139 		 *            only argument.
1140 		 * @param {function(GCNError):boolean=}
1141 		 *            error Optional customer error handler.
1142 		 */
1143 		remove: function (success, error) {
1144 			this._remove(success, error);
1145 		},
1146 
1147 		/**
1148 		 * Get a channel-local copy of this content object.
1149 		 *
1150 		 * @public
1151 		 * @function
1152 		 * @name localize
1153 		 * @memberOf ContentObjectAPI
1154 		 * @param {funtion(ContentObjectAPI)=} success Optional callback to
1155 		 *                                             receive this content
1156 		 *                                             object as the only
1157 		 *                                             argument.
1158 		 * @param {function(GCNError):boolean=} error Optional custom error
1159 		 *                                            handler.
1160 		 */
1161 		'!localize': function (success, error) {
1162 			if (!this._channel && !GCN.channel()) {
1163 				var err = GCN.createError(
1164 					'NO_CHANNEL_ID_SET',
1165 					'No channel is set in which to get the localized object',
1166 					GCN
1167 				);
1168 				GCN.handleError(err, error);
1169 				return false;
1170 			}
1171 			var local = this._continue(
1172 				this._constructor,
1173 				{
1174 					derivedFrom: this,
1175 					multichannelling: true,
1176 					read: GCN.multichannelling.localize
1177 				},
1178 				success,
1179 				error
1180 			);
1181 			return local;
1182 		},
1183 
1184 		/**
1185 		 * Remove this channel-local object, and delete its local copy in the
1186 		 * backend.
1187 		 *
1188 		 * @public
1189 		 * @function
1190 		 * @name unlocalize
1191 		 * @memberOf ContentObjectAPI
1192 		 * @param {funtion(ContentObjectAPI)=} success Optional callback to
1193 		 *                                             receive this content
1194 		 *                                             object as the only
1195 		 *                                             argument.
1196 		 * @param {function(GCNError):boolean=} error Optional custom error
1197 		 *                                            handler.
1198 		 */
1199 		'!unlocalize': function (success, error) {
1200 			if (!this._channel && !GCN.channel()) {
1201 				var err = GCN.createError(
1202 					'NO_CHANNEL_ID_SET',
1203 					'No channel is set in which to get the unlocalized object',
1204 					GCN
1205 				);
1206 				GCN.handleError(err, error);
1207 				return false;
1208 			}
1209 			var placeholder = {
1210 				multichannelling: {
1211 					derivedFrom: this
1212 				}
1213 			};
1214 			var that = this;
1215 			GCN.multichannelling.unlocalize(placeholder, function () {
1216 				// TODO: This should be done inside of
1217 				// multichannelling.unlocalize() and not in this callback.
1218 				// Clean cache & reset object to make sure it can't be used
1219 				// properly any more.
1220 				that._clearCache();
1221 				that._data = {};
1222 				that._shadow = {};
1223 				if (success) {
1224 					success();
1225 				}
1226 			}, error);
1227 		},
1228 
1229 		/**
1230 		 * Performs a REST API request to delete this object from the server.
1231 		 *
1232 		 * @private
1233 		 * @param {function()=} success Optional callback that
1234 		 *                                              will be invoked once
1235 		 *                                              this object has been
1236 		 *                                              removed.
1237 		 * @param {function(GCNError):boolean=} error Optional customer error
1238 		 *                                            handler.
1239 		 */
1240 		'!_remove': function (success, error) {
1241 			var that = this;
1242 			this._authAjax({
1243 				url     : GCN.settings.BACKEND_PATH + '/rest/'
1244 				          + this._type + '/delete/' + this.id()
1245 				          + GCN._getChannelParameter(that),
1246 				type    : 'POST',
1247 				error   : error,
1248 				success : function (response) {
1249 					// Clean cache & reset object to make sure it can't be used
1250 					// properly any more.
1251 					that._clearCache();
1252 					that._data = {};
1253 					that._shadow = {};
1254 
1255 					// Don't forward the object to the success handler since
1256 					// it's been deleted.
1257 					if (success) {
1258 						that._invoke(success);
1259 					}
1260 				}
1261 			});
1262 		},
1263 
1264 		/**
1265 		 * Removes any additionaly data stored on this objec which pertains to
1266 		 * a tag matching the given tagname.  This function will be called when
1267 		 * a tag is being removed in order to bring the content object to a
1268 		 * consistant state.
1269 		 * Should be overriden by subclasses.
1270 		 *
1271 		 * @param {string} tagid The Id of the tag whose associated data we
1272 		 *                       want we want to remove.
1273 		 */
1274 		'!_removeAssociatedTagData': function (tagname) {},
1275 
1276 		/**
1277 		 * Return the replacement value, when this object is transformed to stringified JSON.
1278 		 * This is necessary to avoid endless loops, because objects may have chainback objects
1279 		 * stored in their _data.
1280 		 * 
1281 		 * @private
1282 		 * @param {string} key
1283 		 * @return {object} _data
1284 		 */
1285 		'!toJSON': function (key) {
1286 			return this._data;
1287 		}
1288 	});
1289 
1290 	GCN.ContentObjectAPI.update = update;
1291 
1292 	/**
1293 	 * Generates a factory method for chainback classes.  The method signature
1294 	 * used with this factory function will match that of the target class'
1295 	 * constructor.  Therefore this function is expected to be invoked with the
1296 	 * follow combination of arguments ...
1297 	 *
1298 	 * Examples for GCN.pages api:
1299 	 *
1300 	 * To get an array containing 1 page:
1301 	 * pages(1)
1302 	 * pages(1, function () {})
1303 	 *
1304 	 * To get an array containing 2 pages:
1305 	 * pages([1, 2])
1306 	 * pages([1, 2], function () {})
1307 	 *
1308 	 * To get an array containing any and all pages:
1309 	 * pages()
1310 	 * pages(function () {})
1311 	 *
1312 	 * To get an array containing no pages:
1313 	 * pages([])
1314 	 * pages([], function () {});
1315 	 *
1316 	 * @param {Chainback} ctor The Chainback constructor we want to expose.
1317 	 * @throws UNKNOWN_ARGUMENT
1318 	 */
1319 	GCN.exposeAPI = function (ctor) {
1320 		return function () {
1321 			// Convert arguments into an array
1322 			// https://developer.mozilla.org/en/JavaScript/Reference/...
1323 			// ...Functions_and_function_scope/arguments
1324 			var args = Array.prototype.slice.call(arguments);
1325 			var id;
1326 			var ids;
1327 			var success;
1328 			var error;
1329 			var settings;
1330 
1331 			// iterate over arguments to find id || ids, succes, error and
1332 			// settings
1333 			jQuery.each(args, function (i, arg) {
1334 				switch (jQuery.type(arg)) {
1335 				// set id
1336 				case 'string':
1337 				case 'number':
1338 					if (!id && !ids) {
1339 						id = arg;
1340 					} else {
1341 						GCN.error('UNKNOWN_ARGUMENT',
1342 							'id is already set. Don\'t know what to do with ' +
1343 							'arguments[' + i + '] value: "' + arg + '"');
1344 					}
1345 					break;
1346 				// set ids
1347 				case 'array':
1348 					if (!id && !ids) {
1349 						ids = args[0];
1350 					} else {
1351 						GCN.error('UNKNOWN_ARGUMENT',
1352 							'ids is already set. Don\'t know what to do with' +
1353 							' arguments[' + i + '] value: "' + arg + '"');
1354 					}
1355 					break;
1356 				// success and error handlers
1357 				case 'function':
1358 					if (!success) {
1359 						success = arg;
1360 					} else if (success && !error) {
1361 						error = arg;
1362 					} else {
1363 						GCN.error('UNKNOWN_ARGUMENT',
1364 							'success and error handler already set. Don\'t ' +
1365 							'know what to do with arguments[' + i + ']');
1366 					}
1367 					break;
1368 				// settings
1369 				case 'object':
1370 					if (!id && !ids) {
1371 						id = arg;
1372 					} else if (!settings) {
1373 						settings = arg;
1374 					} else {
1375 						GCN.error('UNKNOWN_ARGUMENT',
1376 							'settings are already present. Don\'t know what ' +
1377 							'to do with arguments[' + i + '] value:' + ' "' +
1378 							arg + '"');
1379 					}
1380 					break;
1381 				default:
1382 					GCN.error('UNKNOWN_ARGUMENT',
1383 						'Don\'t know what to do with arguments[' + i +
1384 						'] value: "' + arg + '"');
1385 				}
1386 			});
1387 
1388 			// Prepare a new set of arguments to pass on during initialzation
1389 			// of callee object.
1390 			args = [];
1391 
1392 			// settings should always be an object, even if it's just empty
1393 			if (!settings) {
1394 				settings = {};
1395 			}
1396 
1397 			args[0] = (typeof id !== 'undefined') ? id : ids;
1398 			args[1] = success || settings.success || null;
1399 			args[2] = error || settings.error || null;
1400 			args[3] = settings;
1401 
1402 			// We either add 0 (no channel) or the channelid to the hash
1403 			var channel = GCN.settings.channel;
1404 
1405 			// Check if the value is false, and set it to 0 in this case
1406 			if (!channel) {
1407 				channel = 0;
1408 			}
1409 
1410 			var hash = (id || ids)
1411 			         ? ctor._makeHash(channel + '/' + (ids ? ids.sort().join(',') : id))
1412 			         : null;
1413 
1414 			return GCN.getChainback(ctor, hash, null, args);
1415 		};
1416 
1417 	};
1418 
1419 }(GCN));
1420