1 /*jslint regexp: false */
  2 (function (GCN) {
  3 
  4 	'use strict';
  5 
  6 	/**
  7 	 * @private
  8 	 * @const
  9 	 * @type {object.<string, boolean>} Default page settings.
 10 	 */
 11 	var DEFAULT_SETTINGS = {
 12 		// Load folder information
 13 		folder: true,
 14 
 15 		// Lock page when loading it
 16 		update: true,
 17 
 18 		// Have language variants be included in the page response.
 19 		langvars: true,
 20 
 21 		// Have page variants be included in the page response.
 22 		pagevars: true
 23 	};
 24 
 25 	/**
 26 	 * Match URL to anchor
 27 	 *
 28 	 * @const
 29 	 * @type {RegExp}
 30 	 */
 31 	var ANCHOR_LINK = /([^#]*)#(.*)/;
 32 
 33 	/**
 34 	 * Checks whether the given tag is a magic link block.
 35 	 *
 36 	 * @param {TagAPI} tag A tag that must already have been fetched.
 37 	 * @param {Object} constructs Set of constructs.
 38 	 * @return {boolean} True if the given tag's constructId is equal to the
 39 	 *                   `MAGIC_LINK' value.
 40 	 */
 41 	function isMagicLinkTag(tag, constructs) {
 42 		return !!(constructs[GCN.settings.MAGIC_LINK]
 43 					&& (constructs[GCN.settings.MAGIC_LINK].constructId
 44 						=== tag.prop('constructId')));
 45 	}
 46 
 47 	/**
 48 	 * Given a page object, returns a jQuery set containing DOM elements for
 49 	 * each of the page's editable that is attached to the document.
 50 	 *
 51 	 * @param {PageAPI} page A page object.
 52 	 * @return {jQuery.<HTMLElement>} A jQuery set of editable DOM elements.
 53 	 */
 54 	function getEditablesInDocument(page) {
 55 		var id;
 56 		var $editables = jQuery();
 57 		var editables = page._editables;
 58 		for (id in editables) {
 59 			if (editables.hasOwnProperty(id)) {
 60 				$editables = $editables.add('#' + id);
 61 			}
 62 		}
 63 		return $editables;
 64 	}
 65 
 66 	/**
 67 	 * Returns all editables associated with the given page that have been
 68 	 * rendered in the document for editing.
 69 	 *
 70 	 * @param {PageAPI} page
 71 	 * @return {object} A set of editable objects.
 72 	 */
 73 	function getEditedEditables(page) {
 74 		return page._editables;
 75 	}
 76 
 77 	/**
 78 	 * Derives a list of the blocks that were rendered inside at least one of
 79 	 * the given page's edit()ed editables.
 80 	 *
 81 	 * @param {PageAPI} page Page object.
 82 	 * @return {Array.<object>} The set of blocks contained in any of the
 83 	 *                          page's rendered editables.
 84 	 */
 85 	function getRenderedBlocks(page) {
 86 		var editables = getEditedEditables(page);
 87 		var id;
 88 		var renderedBlocks = [];
 89 		for (id in editables) {
 90 			if (editables.hasOwnProperty(id)) {
 91 				if (editables[id]._gcnContainedBlocks) {
 92 					renderedBlocks = renderedBlocks.concat(
 93 						editables[id]._gcnContainedBlocks
 94 					);
 95 				}
 96 			}
 97 		}
 98 		return renderedBlocks;
 99 	}
100 
101 	/**
102 	 * Gets the DOM element associated with the given block.
103 	 *
104 	 * @param {object} block
105 	 * @return {?jQuery.<HTMLElement>} A jQuery unit set of the block's
106 	 *                                 corresponding DOM element, or null if no
107 	 *                                 element for the given block exists in
108 	 *                                 the document.
109 	 */
110 	function getElement(block) {
111 		var $element = jQuery('#' + block.element);
112 		return $element.length ? $element : null;
113 	}
114 
115 	/**
116 	 * Retrieves a jQuery set of all link elements that are contained in
117 	 * editables associated with the given page.
118 	 *
119 	 * @param {PageAPI} page
120 	 * @return {jQuery.<HTMLElement>} A jQuery set of link elements.
121 	 */
122 	function getEditableLinks(page) {
123 		return getEditablesInDocument(page).find('a[href]');
124 	}
125 
126 	/**
127 	 * Determines all blocks that no longer need their tags to be kept in the
128 	 * given page's tag list.
129 	 *
130 	 * @param {PageAPI} page
131 	 * @param {function(Array.<object>)} success A callback function that
132 	 *                                           receives a list of obsolete
133 	 *                                           blocks.
134 	 * @param {function(GCNError):boolean=} error Optional custom error
135 	 *                                            handler.
136 	 */
137 	function getObsoleteBlocks(page, success, error) {
138 		var blocks = getRenderedBlocks(page);
139 		if (0 === blocks.length) {
140 			success([]);
141 			return;
142 		}
143 		var $links = getEditableLinks(page);
144 		var numToProcess = blocks.length;
145 		var obsolete = [];
146 		var onSuccess = function () {
147 			if ((0 === --numToProcess) && success) {
148 				success(obsolete);
149 			}
150 		};
151 		var onError = function (GCNError) {
152 			if (error) {
153 				return error(GCNError);
154 			}
155 		};
156 		page.constructs(function (constructs) {
157 			var processTag = function (block) {
158 				page.tag(block.tagname, function (tag) {
159 					if (isMagicLinkTag(tag, constructs) && !getElement(block)) {
160 						obsolete.push(block);
161 					}
162 					onSuccess();
163 				}, onError);
164 			};
165 			var i;
166 			for (i = 0; i < blocks.length; i++) {
167 				processTag(blocks[i]);
168 			}
169 		});
170 	}
171 
172 	/**
173 	 * Checks whether or not the given block has a corresponding element in the
174 	 * document DOM.
175 	 *
176 	 * @private
177 	 * @static
178 	 * @param {object}
179 	 * @return {boolean} True if an inline element for this block exists.
180 	 */
181 	function hasInlineElement(block) {
182 		return !!getElement(block);
183 	}
184 
185 	/**
186 	 * Matches "aloha-*" class names.
187 	 *
188 	 * @const
189 	 * @type {RegExp}
190 	 */
191 	var ALOHA_CLASS_NAMES = /\baloha-[a-z0-9\-\_]*\b/gi;
192 
193 	/**
194 	 * Strips unwanted names from the given className string.
195 	 *
196 	 * All class names beginning with "aloha-block*" will be removed.
197 	 *
198 	 * @param {string} classes Space seperated list of classes.
199 	 * @return {string} Sanitized classes string.
200 	 */
201 	function cleanBlockClasses(classes) {
202 		return classes ? jQuery.trim(classes.replace(ALOHA_CLASS_NAMES, ''))
203 		               : '';
204 	}
205 
206 	/**
207 	 * Determines the backend object that was set to the given link.
208 	 *
209 	 * @param {jQuery.<HTMLElement>} $link A link in an editable.
210 	 * @return {Object} An object containing the gtxalohapagelink part keyword
211 	 *                  and value.  The keyword may be either be "url" or
212 	 *                  "fileurl" depending on the type of object linked to.
213 	 *                  The value may be a string url ("http://...") for
214 	 *                  external links or an integer for internal links.
215 	 */
216 	function getTagPartsFromLink($link) {
217 		var linkData = $link.attr('data-gentics-aloha-object-id');
218 		var href = $link.attr('href') || '';
219 		var anchorUrlMatch = href.match(ANCHOR_LINK);
220 		var tagparts = {
221 			text: $link.html(),
222 			anchor: $link.attr('data-gentics-gcn-anchor'),
223 			title: $link.attr('title'),
224 			target: $link.attr('target'),
225 			language: $link.attr('hreflang'),
226 			'class': cleanBlockClasses($link.attr('class'))
227 		};
228 
229 		if (anchorUrlMatch) {
230 			href = anchorUrlMatch[1];
231 		}
232 
233 		if (href === window.location.href) {
234 			href = '';
235 		}
236 
237 		if (linkData) {
238 			var idParts = linkData.split('.');
239 
240 			if (2 !== idParts.length) {
241 				tagparts.url = linkData;
242 			} else if ('10007' === idParts[0]) {
243 				tagparts.url = parseInt(idParts[1], 10);
244 				tagparts.fileurl = 0;
245 			} else if ('10008' === idParts[0] || '10011' === idParts[0]) {
246 				tagparts.url = 0;
247 				tagparts.fileurl = parseInt(idParts[1], 10);
248 			} else {
249 				tagparts.url = href;
250 			}
251 		} else {
252 			// check whether the href contains links to internal pages or files
253 			var result = GCN.settings.checkForInternalLink(href);
254 
255 			tagparts.url = result.url;
256 			tagparts.fileurl = result.fileurl;
257 
258 			if (result.match) {
259 				href = '';
260 			}
261 		}
262 
263 		if (!tagparts.anchor) {
264 			tagparts.anchor = anchorUrlMatch ? anchorUrlMatch[2] : '';
265 		}
266 
267 		// Make sure the href attribute of the link is consistent with the
268 		// data fields after saving.
269 		var linkHref = href;
270 
271 		if (tagparts.anchor) {
272 			linkHref += '#' + tagparts.anchor;
273 		}
274 
275 		if (!linkHref) {
276 			linkHref = '#';
277 		}
278 
279 		$link.attr('href', linkHref);
280 		$link.attr('data-gentics-gcn-url', tagparts.url);
281 		$link.attr('data-gentics-gcn-fileurl', tagparts.fileurl);
282 		$link.attr('data-gentics-gcn-anchor', tagparts.anchor);
283 
284 		return tagparts;
285 	}
286 
287 	/**
288 	 * Checks whether a page object has a corresponding tag for a given link
289 	 * DOM element.
290 	 *
291 	 * @param {PageAPI} page The page object in which to look for the link tag.
292 	 * @param {jQuery.<HTMLElement>} $link jQuery unit set containing a link
293 	 *                                     DOM element.
294 	 * @return {boolean} True if there is a tag on the page that corresponds with
295 	 *                   the givn link.
296 	 */
297 	function hasTagForLink(page, $link) {
298 		var id = $link.attr('id');
299 		return !!(id && page._getBlockById(id));
300 	}
301 
302 	/**
303 	 * Checks whether or not the given part has a part type of the given
304 	 * name
305 	 *
306 	 * @param {TagAPI} tag
307 	 * @param {string} part Part name
308 	 * @return {boolean} True of part exists in the given tag.
309 	 */
310 	function hasTagPart(tag, part) {
311 		return !!tag._data.properties[part];
312 	}
313 
314 	/**
315 	 * Updates the parts of a tag in the page object that corresponds to the
316 	 * given link DOM element.
317 	 *
318 	 * @param {PageAPI} page
319 	 * @param {jQuery.<HTMLElement>} $link jQuery unit set containing a link
320 	 *                                     DOM element.
321 	 */
322 	function updateTagForLink(page, $link) {
323 		var block = page._getBlockById($link.attr('id'));
324 		// ASSERT(block)
325 		var tag = page.tag(block.tagname);
326 		var parts = getTagPartsFromLink($link);
327 		var part;
328 		for (part in parts) {
329 			if (parts.hasOwnProperty(part) && hasTagPart(tag, part)) {
330 				tag.part(part, parts[part]);
331 			}
332 		}
333 	}
334 
335 	/**
336 	 * Creates a new tag for the given link in the page.
337 	 *
338 	 * @param {PageAPI} page
339 	 * @param {jQuery.<HTMLElement>} $link jQuery unit set containing a link
340 	 *                                     element.
341 	 * @param {function} success Callback function that whill be called when
342 	 *                           the new tag is created.
343 	 * @param {function(GCNError):boolean=} error Optional custom error
344 	 *                                            handler.
345 	 */
346 	function createTagForLink(page, $link, success, error) {
347 		page.createTag({
348 			keyword: GCN.settings.MAGIC_LINK,
349 			magicValue: $link.html()
350 		}).edit(function (html, tag) {
351 			// Copy over the rendered id value for the link so that we can bind
352 			// the link in the DOM with the newly created block.
353 			$link.attr('id', jQuery(html).attr('id'));
354 			updateTagForLink(page, $link);
355 			success();
356 		}, error);
357 	}
358 
359 	/**
360 	 * Create tags for all new links in the page
361 	 * 
362 	 * @param {PageApi} page
363 	 * @param {jQuery.<HTMLElement>} $gcnlinks jQuery unit set containing links
364 	 * @param {function} success Callback function that will be called when the tags are created
365 	 * @param {function(GCNError)} error Optional custom error handler
366 	 */
367 	function createMissingLinkTags(page, $gcnlinks, success, error) {
368 		var $newGcnLinks = $gcnlinks.filter(function () {
369 			return !hasTagForLink(page, jQuery(this));
370 		}), linkData = {create:{}}, i = 0, id;
371 
372 		if ($newGcnLinks.length > 0) {
373 			$newGcnLinks.each(function (index) {
374 				id = 'link' + (i++);
375 				linkData.create[id] = {
376 					data: {
377 						keyword: GCN.settings.MAGIC_LINK,
378 						magicValue: jQuery(this).html()
379 					},
380 					obj: jQuery(this)
381 				};
382 			});
383 			page._createTags(linkData, function () {
384 				var id;
385 				for (id in linkData.create) {
386 					if (linkData.create.hasOwnProperty(id)) {
387 						linkData.create[id].obj.attr('id', jQuery(linkData.create[id].response.html).attr('id'));
388 					}
389 				}
390 				page._processRenderedTags(linkData.response);
391 				success();
392 			}, error);
393 		} else {
394 			success();
395 		}
396 
397 	}
398 
399 	/**
400 	 * Identifies internal GCN links in the given page's rendered editables,
401 	 * and updates their corresponding content tags, or create new tags for the
402 	 * if they are new links.
403 	 *
404 	 *  @param {PageAPI} page
405 	 *  @param {function} success
406 	 *  @param {function} error
407 	 */
408 	function processGCNLinks(page, success, error) {
409 		var $links = getEditableLinks(page);
410 		var $gcnlinks = $links.filter(function () {
411 			return this.isContentEditable;
412 		}).filter(':not(.aloha-editable)');
413 		if (0 === $gcnlinks.length) {
414 			if (success) {
415 				success();
416 			}
417 			return;
418 		}
419 		var numToProcess = $gcnlinks.length;
420 		var onSuccess = function () {
421 			if ((0 === --numToProcess) && success) {
422 				success();
423 			}
424 		};
425 		var onError = function (GCNError) {
426 			if (error) {
427 				return error(GCNError);
428 			}
429 		};
430 
431 		// When a link was copied it would result in two magic link tags
432 		// with the same ID. We remove the id attribute from such duplicates
433 		// so that hasTagForLink() will return false and create a new tag
434 		// for the copied link.
435 		var alreadyExists = {};
436 
437 		$links.each(function () {
438 			var $link = jQuery(this);
439 			var id = $link.attr('id');
440 
441 			if (id) {
442 				if (alreadyExists[id]) {
443 					$link.removeAttr('id');
444 				} else {
445 					alreadyExists[id] = true;
446 				}
447 			}
448 		});
449 
450 		createMissingLinkTags(page, $gcnlinks, function () {
451 			var i;
452 			for (i = 0; i < $gcnlinks.length; i++) {
453 				if (hasTagForLink(page, $gcnlinks.eq(i))) {
454 					updateTagForLink(page, $gcnlinks.eq(i));
455 					onSuccess();
456 				} else {
457 					onError(GCN.error('500', 'Missing Tag for Link', $gcnlinks.get(i)));
458 				}
459 			}
460 		}, onError);
461 	}
462 
463 	/**
464 	 * Adds the given blocks into the page's list of blocks that are to be
465 	 * deleted when the page is saved.
466 	 *
467 	 * @param {PageAPI} page
468 	 * @param {Array.<object>} blocks Blocks that are to be marked for deletion.
469 	 */
470 	function deleteBlocks(page, blocks) {
471 		blocks = jQuery.isArray(blocks) ? blocks : [blocks];
472 		var i;
473 		var success = function(tag) {
474 			tag.remove();
475 		};
476 		for (i = 0; i < blocks.length; i++) {
477 			if (-1 ===
478 					jQuery.inArray(blocks[i].tagname, page._deletedBlocks)) {
479 				page._deletedBlocks.push(blocks[i].tagname);
480 			}
481 			delete page._blocks[blocks[i].element];
482 
483 			page.tag(blocks[i].tagname, success);
484 		}
485 	}
486 
487 	/**
488 	 * Removes all tags on the given page which belong to links that are no
489 	 * longer present in any of the page's rendered editables.
490 	 *
491 	 * @param {PageAPI} page
492 	 * @param {function} success Callback function that will be invoked when
493 	 *                           all obsolete tags have been successfully
494 	 *                           marked for deletion.
495 	 * @param {function(GCNError):boolean=} error Optional custom error
496 	 *                                            handler.
497 	 */
498 	function deleteObsoleteLinkTags(page, success, error) {
499 		getObsoleteBlocks(page, function (obsolete) {
500 			deleteBlocks(page, obsolete);
501 			if (success) {
502 				success();
503 			}
504 		}, error);
505 	}
506 
507 	/**
508 	 * Searches for the an Aloha editable object of the given id.
509 	 *
510 	 * @TODO: Once Aloha.getEditableById() is patched to not cause an
511 	 *        JavaScript exception if the element for the given ID is not found
512 	 *        then we can deprecate this function and use Aloha's instead.
513 	 *
514 	 * @static
515 	 * @param {string} id Id of Aloha.Editable object to find.
516 	 * @return {Aloha.Editable=} The editable object, if wound; otherwise null.
517 	 */
518 	function getAlohaEditableById(id) {
519 		var Aloha = (typeof window !== 'undefined') && window.Aloha;
520 		if (!Aloha) {
521 			return null;
522 		}
523 
524 		// If the element is a textarea then route to the editable div.
525 		var element = jQuery('#' + id);
526 		if (element.length &&
527 				element[0].nodeName.toLowerCase() === 'textarea') {
528 			id += '-aloha';
529 		}
530 
531 		var editables = Aloha.editables;
532 		var j = editables.length;
533 		while (j) {
534 			if (editables[--j].getId() === id) {
535 				return editables[j];
536 			}
537 		}
538 
539 		return null;
540 	}
541 
542 	/**
543 	 * For a given list of editables and a list of blocks, determines in which
544 	 * editable each block is contained.  The result is a map of block sets.
545 	 * Each of these sets of blocks are mapped against the id of the editable
546 	 * in which they are rendered.
547 	 *
548 	 * @param {string} content The rendered content in which both the list of
549 	 *                         editables, and blocks are contained.
550 	 * @param {Array.<object>} editables A list of editables contained in the
551 	 *                                   content.
552 	 * @param {Array.<object>} blocks A list of blocks containd in the content.
553 	 * @return {object<string, Array>} A object whose keys are editable ids,
554 	 *                                  and whose values are arrays of blocks
555 	 *                                  contained in the corresponding
556 	 *                                  editable.
557 	 */
558 	function categorizeBlocksAgainstEditables(content, editables, blocks) {
559 		var i;
560 		var $content = jQuery('<div>' + content + '</div>');
561 		var sets = {};
562 		var editableId;
563 
564 		var editablesSelectors = [];
565 		for (i = 0; i < editables.length; i++) {
566 			editablesSelectors.push('#' + editables[i].element);
567 		}
568 
569 		var markerClass = 'aloha-editable-tmp-marker__';
570 		var $editables = $content.find(editablesSelectors.join(','));
571 		$editables.addClass(markerClass);
572 
573 		var $block;
574 		var $parent;
575 		for (i = 0; i < blocks.length; i++) {
576 			$block = $content.find('#' + blocks[i].element);
577 			if ($block.length) {
578 				$parent = $block.closest('.' + markerClass);
579 				if ($parent.length) {
580 					editableId = $parent.attr('id');
581 					if (editableId) {
582 						if (!sets[editableId]) {
583 							sets[editableId] = [];
584 						}
585 						sets[editableId].push(blocks[i]);
586 					}
587 				}
588 			}
589 		}
590 
591 		return sets;
592 	}
593 
594 	/**
595 	 * Causes the given editables to be tracked, so that when the content
596 	 * object is saved, these editables will be processed.
597 	 *
598 	 * @private
599 	 * @param {PageAPI} page
600 	 * @param {Array.<object>} editables A set of object representing
601 	 *                                   editable tags that have been
602 	 *                                   rendered.
603 	 */
604 	function trackEditables(page, editables) {
605 		if (!page.hasOwnProperty('_editables')) {
606 			page._editables = {};
607 		}
608 		var i;
609 		for (i = 0; i < editables.length; i++) {
610 			page._editables[editables[i].element] = editables[i];
611 		}
612 	}
613 
614 	/**
615 	 * Causes the given blocks to be tracked so that when the content object is
616 	 * saved, these editables will be processed.
617 	 *
618 	 * @private
619 	 * @param {PageAPI} page
620 	 * @param {Array.<object>} blocks An set of object representing block
621 	 *                                tags that have been rendered.
622 	 */
623 	function trackBlocks(page, blocks) {
624 		if (!page.hasOwnProperty('_blocks')) {
625 			page._blocks = {};
626 		}
627 		var i;
628 		for (i = 0; i < blocks.length; i++) {
629 			page._blocks[blocks[i].element] = blocks[i];
630 		}
631 	}
632 
633 	/**
634 	 * Associates a list of blocks with an editable so that it can later be
635 	 * determined which blocks are contained inside which editable.
636 	 *
637 	 * @param object
638 	 */
639 	function associateBlocksWithEditable(editable, blocks) {
640 		if (!jQuery.isArray(editable._gcnContainedBlocks)) {
641 			editable._gcnContainedBlocks = [];
642 		}
643 
644 		var i, j;
645 		for (i = 0; i < blocks.length; i++) {
646 			for (j = 0; j < editable._gcnContainedBlocks.length; j++) {
647 				if (blocks[i].element === editable._gcnContainedBlocks[j].element
648 						&& blocks[i].tagname === editable._gcnContainedBlocks[j].tagname) {
649 					// Prevent duplicates
650 					continue;
651 				}
652 
653 				editable._gcnContainedBlocks.push(blocks[i]);
654 			}
655 		}
656 	}
657 
658 	/**
659 	 * Extracts the editables and blocks that have been rendered from the
660 	 * REST API render call's response data, and stores them in the page.
661 	 *
662 	 * @param {PageAPI} page The page inwhich to track the incoming tags.
663 	 * @param {object} data Raw data containing editable and block tags
664 	 * information.
665 	 * @return {object} A object containing to lists: one list of blocks, and
666 	 *                  another of editables.
667 	 */
668 	function trackRenderedTags(page, data) {
669 		var tags = GCN.TagContainerAPI.getEditablesAndBlocks(data);
670 
671 		var containment = categorizeBlocksAgainstEditables(
672 			data.content,
673 			tags.editables,
674 			tags.blocks
675 		);
676 
677 		trackEditables(page, tags.editables);
678 		trackBlocks(page, tags.blocks);
679 
680 		jQuery.each(containment, function (editable, blocks) {
681 			if (page._editables[editable]) {
682 				associateBlocksWithEditable(page._editables[editable], blocks);
683 			}
684 		});
685 
686 		return tags;
687 	}
688 
689 	/**
690 	 * @private
691 	 * @const
692 	 * @type {number}
693 	 */
694 	//var TYPE_ID = 10007;
695 
696 	/**
697 	 * @private
698 	 * @const
699 	 * @type {Enum}
700 	 */
701 	var STATUS = {
702 
703 		// page was not found in the database
704 		NOTFOUND: -1,
705 
706 		// page is locally modified and not yet (re-)published
707 		MODIFIED: 0,
708 
709 		// page is marked to be published (dirty)
710 		TOPUBLISH: 1,
711 
712 		// page is published and online
713 		PUBLISHED: 2,
714 
715 		// Page is offline
716 		OFFLINE: 3,
717 
718 		// Page is in the queue (publishing of the page needs to be affirmed)
719 		QUEUE: 4,
720 
721 		// page is in timemanagement and outside of the defined timespan
722 		// (currently offline)
723 		TIMEMANAGEMENT: 5,
724 
725 		// page is to be published at a given time (not yet)
726 		TOPUBLISH_AT: 6
727 	};
728 
729 	/**
730 	 * @class
731 	 * @name PageAPI
732 	 * @extends ContentObjectAPI
733 	 * @extends TagContainerAPI
734 	 * 
735 	 * @param {number|string}
736 	 *            id of the page to be loaded
737 	 * @param {function(ContentObjectAPI))=}
738 	 *            success Optional success callback that will receive this
739 	 *            object as its only argument.
740 	 * @param {function(GCNError):boolean=}
741 	 *            error Optional custom error handler.
742 	 * @param {object}
743 	 *            settings additional settings for object creation. These
744 	 *            correspond to options available from the REST-API and will
745 	 *            extend or modify the PageAPI object.
746 	 *            <dl>
747 	 *            <dt>update: true</dt>
748 	 *            <dd>Whether the page should be locked in the backend when
749 	 *            loading it. default: true</dd>
750 	 *            <dt>template: true</dt>
751 	 *            <dd>Whether the template information should be embedded in
752 	 *            the page object. default: true</dd>
753 	 *            <dt>folder: true</dt>
754 	 *            <dd>Whether the folder information should be embedded in the
755 	 *            page object. default: true <b>WARNING</b>: do not turn this
756 	 *            option off - it will leave the API in a broken state.</dd>
757 	 *            <dt>langvars: true</dt>
758 	 *            <dd>When the language variants shall be embedded in the page
759 	 *            response. default: true</dd>
760 	 *            <dt>workflow: false</dt>
761 	 *            <dd>When the workflow information shall be embedded in the
762 	 *            page response. default: false</dd>
763 	 *            <dt>pagevars: true</dt>
764 	 *            <dd>When the page variants shall be embedded in the page
765 	 *            response. Page variants will contain folder information.
766 	 *            default: true</dd>
767 	 *            <dt>translationstatus: false</dt>
768 	 *            <dd>Will return information on the page's translation status.
769 	 *            default: false</dd>
770 	 *            </dl>
771 	 */
772 	var PageAPI = GCN.defineChainback({
773 		/** @lends PageAPI */
774 
775 		__chainbacktype__: 'PageAPI',
776 		_extends: [ GCN.TagContainerAPI, GCN.ContentObjectAPI ],
777 		_type: 'page',
778 
779 		/**
780 		 * A hash set of block tags belonging to this page.  This set grows as
781 		 * this page's tags are rendered.
782 		 *
783 		 * @private
784 		 * @type {Array.<object>}
785 		 */
786 		_blocks: {},
787 
788 		/**
789 		 * A hash set of editable tags belonging to this page.  This set grows
790 		 * as this page's tags are rendered.
791 		 *
792 		 * @private
793 		 * @type {Array.<object>}
794 		 */
795 		_editables: {},
796 
797 		/**
798 		 * Writable properties for the page object. Currently the following
799 		 * properties are writeable: cdate, description, fileName, folderId,
800 		 * name, priority, templateId. WARNING: changing the folderId might not
801 		 * work as expected.
802 		 * 
803 		 * @type {Array.string}
804 		 * @const
805 		 */
806 		WRITEABLE_PROPS: [
807 		                  'cdate',
808 		                  'description',
809 		                  'fileName',
810 		                  'folderId', // @TODO Check if moving a page is
811 		                              //       implemented correctly.
812 		                  'name',
813 		                  'priority',
814 		                  'templateId',
815 		                  'timeManagement'
816 		                  ],
817 
818 		/**
819 		 * @type {object} Constraints for writeable props
820 		 * @const
821 		 *
822 		 */
823 		WRITEABLE_PROPS_CONSTRAINTS: {
824 			'name': {
825 				maxLength: 255
826 			}
827 		},
828 
829 		/**
830 		 * Gets all blocks that are associated with this page.
831 		 *
832 		 * It is important to note that the set of blocks in the returned array
833 		 * will only include those that are the returned by the server when
834 		 * calling  edit() on a tag that belongs to this page.
835 		 *
836 		 * @return {Array.<object>} The set of blocks that have been
837 		 *                          initialized by calling edit() on one of
838 		 *                          this page's tags.
839 		 */
840 		'!blocks': function () {
841 			return this._blocks;
842 		},
843 
844 		/**
845 		 * Retrieves a block with the given id among the blocks that are
846 		 * tracked by this page content object.
847 		 *
848 		 * @private
849 		 * @param {string} id The block's id.
850 		 * @return {?object} The block data object.
851 		 */
852 		'!_getBlockById': function (id) {
853 			return this._blocks[id];
854 		},
855 
856 		/**
857 		 * Extracts the editables and blocks that have been rendered from the
858 		 * REST API render call's response data, and stores them in the page.
859 		 *
860 		 * @override
861 		 */
862 		'!_processRenderedTags': function (data) {
863 			return trackRenderedTags(this, data);
864 		},
865 
866 		/**
867 		 * Processes this page's tags in preparation for saving.
868 		 *
869 		 * The preparation process:
870 		 *
871 		 * 1. For all editables associated with this page, determine which of
872 		 *    their blocks have been rendered into the DOM for editing so that
873 		 *    changes to the DOM can be reflected in the corresponding data
874 		 *    structures before pushing the tags to the server.
875 		 *
876 		 * 2.
877 		 *
878 		 * Processes rendered tags, and updates the `_blocks' and `_editables'
879 		 * arrays accordingly.  This function is called during pre-saving to
880 		 * update this page's editable tags.
881 		 *
882 		 * @private
883 		 */
884 		'!_prepareTagsForSaving': function (success, error) {
885 			if (!this.hasOwnProperty('_deletedBlocks')) {
886 				this._deletedBlocks = [];
887 			}
888 			var page = this;
889 			processGCNLinks(page, function () {
890 				deleteObsoleteLinkTags(page, function () {
891 					page._updateEditableBlocks();
892 					if (success) {
893 						success();
894 					}
895 				}, error);
896 			}, error);
897 		},
898 
899 		/**
900 		 * Writes the contents of editables back into their corresponding tags.
901 		 * If a corresponding tag cannot be found for an editable, a new one
902 		 * will be created for it.
903 		 *
904 		 * A reference for each editable tag is then added to the `_shadow'
905 		 * object in order that the tag will be sent with the save request.
906 		 *
907 		 * @private
908 		 */
909 		'!_updateEditableBlocks': function () {
910 			var $element;
911 			var id;
912 			var editables = this._editables;
913 			var tags = this._data.tags;
914 			var tagname;
915 			var html;
916 			var alohaEditable;
917 			var $cleanElement;
918 			var customSerializer;
919 
920 			for (id in editables) {
921 				if (editables.hasOwnProperty(id)) {
922 					$element = jQuery('#' + id);
923 
924 					// Because the editable may not have have been rendered into
925 					// the document DOM.
926 					if (0 === $element.length) {
927 						continue;
928 					}
929 
930 					tagname = editables[id].tagname;
931 
932 					if (!tags[tagname]) {
933 						tags[tagname] = {
934 							name       : tagname,
935 							active     : true,
936 							properties : {}
937 						};
938 					} else {
939 						// Because it is sensible to assume that every editable
940 						// that was rendered for editing is intended to be an
941 						// activate tag.
942 						tags[tagname].active = true;
943 					}
944 
945 					// Because editables that have been aloha()fied, must have
946 					// their contents retrieved by getContents() in order to get
947 					// clean HTML.
948 
949 					alohaEditable = getAlohaEditableById(id);
950 
951 					if (alohaEditable) {
952 						// Avoid the unnecessary overhead of custom editable
953 						// serialization by calling html ourselves.
954 						$cleanElement = jQuery('<div>').append(
955 							alohaEditable.getContents(true)
956 						);
957 						alohaEditable.setUnmodified();
958 						// Apply the custom editable serialization as the last step.
959 						customSerializer = window.Aloha.Editable.getContentSerializer();
960 						html = this.encode($cleanElement, customSerializer);
961 					} else {
962 						html = this.encode($element);
963 					}
964 					// If the editable is backed by a parttype, that
965 					// would replace newlines by br tags while
966 					// rendering, remove all newlines before saving back
967 					if ($element.hasClass('GENTICS_parttype_text') ||
968 						$element.hasClass('GENTICS_parttype_texthtml') ||
969 						$element.hasClass('GENTICS_parttype_java_editor') ||
970 						$element.hasClass('GENTICS_parttype_texthtml_long')) {
971 						html = html.replace(/(\r\n|\n|\r)/gm,"");
972 					}
973 
974 					tags[tagname].properties[editables[id].partname] = {
975 						stringValue: html,
976 						type: 'RICHTEXT'
977 					};
978 
979 					this._update('tags.' + GCN.escapePropertyName(tagname),
980 						tags[tagname]);
981 				}
982 			}
983 		},
984 
985 		/**
986 		 * @see ContentObjectAPI.!_loadParams
987 		 */
988 		'!_loadParams': function () {
989 			return jQuery.extend(DEFAULT_SETTINGS, this._settings);
990 		},
991 
992 		/**
993 		 * Get this page's template.
994 		 *
995 		 * @public
996 		 * @function
997 		 * @name template
998 		 * @memberOf PageAPI
999 		 * @param {funtion(TemplateAPI)=} success Optional callback to receive
1000 		 *                                        a {@link TemplateAPI} object
1001 		 *                                        as the only argument.
1002 		 * @param {function(GCNError):boolean=} error Optional custom error
1003 		 *                                            handler.
1004 		 * @return {TemplateAPI} This page's parent template.
1005 		 */
1006 		'!template': function (success, error) {
1007 			var id = this._fetched ? this.prop('templateId') : null;
1008 			return this._continue(GCN.TemplateAPI, id, success, error);
1009 		},
1010 
1011 		/**
1012 		 * Cache of constructs for this page.
1013 		 * Should be cleared when page is saved.
1014 		 */
1015 		_constructs: null,
1016 
1017 		/**
1018 		 * List of success and error callbacks that need to be called
1019 		 * once the constructs are loaded
1020 		 * @private
1021 		 * @type {array.<object>}
1022 		 */
1023 		_constructLoadHandlers: null,
1024 
1025 		/**
1026 		 * Retrieve the list of constructs of the tag that are used in this
1027 		 * page.
1028 		 *
1029 		 * Note that tags that have been created on this page locally, but have
1030 		 * yet to be persisted to the server (unsaved tags), will not have their
1031 		 * constructs included in the list unless their constructs are used by
1032 		 * other saved tags.
1033 		 */
1034 		'!constructs': function (success, error) {
1035 			var page = this;
1036 			if (page._constructs) {
1037 				return success(page._constructs);
1038 			}
1039 
1040 			// if someone else is already loading the constructs, just add the callbacks
1041 			page._constructLoadHandlers = page._constructLoadHandlers || [];
1042 			if (page._constructLoadHandlers.length > 0) {
1043 				page._constructLoadHandlers.push({success: success, error: error});
1044 				return;
1045 			}
1046 
1047 			// we are the first to load the constructs, register the callbacks and
1048 			// trigger the ajax call
1049 			page._constructLoadHandlers.push({success: success, error: error});
1050 			page._authAjax({
1051 				url: GCN.settings.BACKEND_PATH
1052 				     + '/rest/construct/list.json?pageId=' + page.id(),
1053 				type: 'GET',
1054 				error: function (xhr, status, msg) {
1055 					var i;
1056 					for (i = 0; i < page._constructLoadHandlers.length; i++) {
1057 						GCN.handleHttpError(xhr, msg, page._constructLoadHandlers[i].error);
1058 					}
1059 				},
1060 				success: function (response) {
1061 					var i;
1062 					if (GCN.getResponseCode(response) === 'OK') {
1063 						page._constructs = GCN.mapConstructs(response.constructs);
1064 						for (i = 0; i < page._constructLoadHandlers.length; i++) {
1065 							page._invoke(page._constructLoadHandlers[i].success, [page._constructs]);
1066 						}
1067 					} else {
1068 						for (i = 0; i < page._constructLoadHandlers.length; i++) {
1069 							GCN.handleResponseError(response, page._constructLoadHandlers[i].error);
1070 						}
1071 					}
1072 				},
1073 
1074 				complete: function () {
1075 					page._constructLoadHandlers = [];
1076 				}
1077 			});
1078 		},
1079 
1080 		/**
1081 		 * @override
1082 		 * @see ContentObjectAPI._save
1083 		 */
1084 		'!_save': function (settings, success, error) {
1085 			var page = this;
1086 			this._fulfill(function () {
1087 				page._read(function () {
1088 					var fork = page._fork();
1089 					fork._prepareTagsForSaving(function () {
1090 						GCN.pub('page.before-saved', fork);
1091 						fork._persist(settings, function () {
1092 							if (success) {
1093 								page._constructs = null;
1094 								fork._merge(false);
1095 								page._invoke(success, [page]);
1096 								page._vacate();
1097 							} else {
1098 								fork._merge();
1099 							}
1100 						}, error);
1101 					}, error);
1102 				}, error);
1103 			}, error);
1104 		},
1105 
1106 		//---------------------------------------------------------------------
1107 		// Surface the tag container methods that are applicable for GCN page
1108 		// objects.
1109 		//---------------------------------------------------------------------
1110 
1111 		/**
1112 		 * Creates a tag of a given tagtype in this page.
1113 		 * The first parameter should either be the construct keyword or ID,
1114 		 * or an object containing exactly one of the following property sets:<br/>
1115 		 * <ol>
1116 		 *   <li><i>keyword</i> to create a tag based on the construct with given keyword</li>
1117 		 *   <li><i>constructId</i> to create a tag based on the construct with given ID</li>
1118 		 *   <li><i>sourcePageId</i> and <i>sourceTagname</i> to create a tag as copy of the given tag from the page</li>
1119 		 * </ol>
1120 		 *
1121 		 * Exmaple:
1122 		 * <pre>
1123 		 *  createTag('link', onSuccess, onError);
1124 		 * </pre>
1125 		 * or
1126 		 * <pre>
1127 		 *  createTag({keyword: 'link', magicValue: 'http://www.gentics.com'}, onSuccess, onError);
1128 		 * </pre>
1129 		 * or
1130 		 * <pre>
1131 		 *  createTag({sourcePageId: 4711, sourceTagname: 'link'}, onSuccess, onError);
1132 		 * </pre>
1133 		 *
1134 		 * @public
1135 		 * @function
1136 		 * @name createTag
1137 		 * @memberOf PageAPI
1138 		 * @param {string|number|object} construct either the keyword of the
1139 		 *                               construct, or the ID of the construct
1140 		 *                               or an object with the following
1141 		 *                               properties
1142 		 *                               <ul>
1143 		 *                                <li><i>keyword</i> keyword of the construct</li>
1144 		 *                                <li><i>constructId</i> ID of the construct</li>
1145 		 *                                <li><i>magicValue</i> magic value to be filled into the tag</li>
1146 		 *                                <li><i>sourcePageId</i> source page id</li>
1147 		 *                                <li><i>sourceTagname</i> source tag name</li>
1148 		 *                               </ul>
1149 		 * @param {function(TagAPI)=} success Optional callback that will
1150 		 *                                    receive the newly created tag as
1151 		 *                                    its only argument.
1152 		 * @param {function(GCNError):boolean=} error Optional custom error
1153 		 *                                            handler.
1154 		 * @return {TagAPI} The newly created tag.
1155 		 * @throws INVALID_ARGUMENTS
1156 		 */
1157 		'!createTag': function () {
1158 			return this._createTag.apply(this, arguments);
1159 		},
1160 
1161 		/**
1162 		 * Deletes the specified tag from this page.
1163 		 * You should pass a keyword here not an Id.
1164 		 * 
1165 		 * Note: Due to how the underlying RestAPI layer works,
1166 		 * the success callback will also be called if the specified tag
1167 		 * does not exist.
1168 		 * 
1169 		 * @public
1170 		 * @function
1171 		 * @memberOf PageAPI
1172 		 * @param {string}
1173 		 *            keyword The keyword of the tag to be deleted.
1174 		 * @param {function(PageAPI)=}
1175 		 *            success Optional callback that receive this object as its
1176 		 *            only argument.
1177 		 * @param {function(GCNError):boolean=}
1178 		 *            error Optional custom error handler.
1179 		 */
1180 		removeTag: function () {
1181 			this._removeTag.apply(this, arguments);
1182 		},
1183 
1184 		/**
1185 		 * Deletes a set of tags from this page.
1186 		 * 
1187 		 * @public
1188 		 * @function
1189 		 * @memberOf PageAPI
1190 		 * @param {Array.
1191 		 *            <string>} keywords The keywords of the tags to be deleted.
1192 		 * @param {function(PageAPI)=}
1193 		 *            success Optional callback that receive this object as its
1194 		 *            only argument.
1195 		 * @param {function(GCNError):boolean=}
1196 		 *            error Optional custom error handler.
1197 		 */
1198 		removeTags: function () {
1199 			this._removeTags.apply(this, arguments);
1200 		},
1201 
1202 		/**
1203 		 * Takes the page offline.
1204 		 * If instant publishing is enabled, this will take the page offline
1205 		 * immediately. Otherwise it will be taken offline during the next
1206 		 * publish run.
1207 		 *
1208 		 * @public
1209 		 * @function
1210 		 * @memberOf PageAPI
1211 		 * @param {funtion(PageAPI)=} success Optional callback to receive this
1212 		 *                                    page object as the only argument.
1213 		 * @param {function(GCNError):boolean=} error Optional custom error
1214 		 *                                            handler.
1215 		 */
1216 		takeOffline: function (success, error) {
1217 			var page = this;
1218 			page._fulfill(function () {
1219 				page._authAjax({
1220 					url: GCN.settings.BACKEND_PATH + '/rest/' + page._type +
1221 					     '/takeOffline/' + page.id(),
1222 					type: 'POST',
1223 					json: {}, // There needs to be at least empty content
1224 					          // because of a bug in Jersey.
1225 					error: error,
1226 					success: function (response) {
1227 						if (success) {
1228 							page._invoke(success, [page]);
1229 						}
1230 					}
1231 				});
1232 			});
1233 		},
1234 
1235 		/**
1236 		 * Trigger publish process for the page.
1237 		 *
1238 		 * @public
1239 		 * @function
1240 		 * @memberOf PageAPI
1241 		 * @param {funtion(PageAPI)=} success Optional callback to receive this
1242 		 *                                    page object as the only argument.
1243 		 * @param {function(GCNError):boolean=} error Optional custom error
1244 		 *                                            handler.
1245 		 */
1246 		publish: function (success, error) {
1247 			var page = this;
1248 			GCN.pub('page.before-publish', page);
1249 			this._fulfill(function () {
1250 				page._authAjax({
1251 					url: GCN.settings.BACKEND_PATH + '/rest/' + page._type +
1252 					     '/publish/' + page.id() + GCN._getChannelParameter(page),
1253 					type: 'POST',
1254 					json: {}, // There needs to be at least empty content
1255 					          // because of a bug in Jersey.
1256 					success: function (response) {
1257 						page._data.status = STATUS.PUBLISHED;
1258 						if (success) {
1259 							page._invoke(success, [page]);
1260 						}
1261 					},
1262 					error: error
1263 				});
1264 			});
1265 		},
1266 
1267 		/**
1268 		 * Renders a preview of the current page.
1269 		 * 
1270 		 * @public
1271 		 * @function
1272 		 * @memberOf PageAPI
1273 		 * @param {function(string,
1274 		 *            PageAPI)} success Callback to receive the rendered page
1275 		 *            preview as the first argument, and this page object as the
1276 		 *            second.
1277 		 * @param {function(GCNError):boolean=}
1278 		 *            error Optional custom error handler.
1279 		 */
1280 		preview: function (success, error) {
1281 			var that = this;
1282 
1283 			this._read(function () {
1284 				that._authAjax({
1285 					url: GCN.settings.BACKEND_PATH + '/rest/' + that._type +
1286 					     '/preview/' + GCN._getChannelParameter(that),
1287 					json: {
1288 						page: that._data, // @FIXME Shouldn't this a be merge of
1289 						                 //        the `_shadow' object and the
1290 										 //        `_data'.
1291 						nodeId: that.nodeId()
1292 					},
1293 					type: 'POST',
1294 					error: error,
1295 					success: function (response) {
1296 						if (success) {
1297 							GCN._handleContentRendered(response.preview, that,
1298 								function (html) {
1299 									that._invoke(success, [html, that]);
1300 								});
1301 						}
1302 					}
1303 				});
1304 			}, error);
1305 		},
1306 
1307 		/**
1308 		 * Unlocks the page when finishing editing
1309 		 * 
1310 		 * @public
1311 		 * @function
1312 		 * @memberOf PageAPI
1313 		 * @param {funtion(PageAPI)=}
1314 		 *            success Optional callback to receive this page object as
1315 		 *            the only argument.
1316 		 * @param {function(GCNError):boolean=}
1317 		 *            error Optional custom error handler.
1318 		 */
1319 		unlock: function (success, error) {
1320 			var that = this;
1321 			this._fulfill(function () {
1322 				that._authAjax({
1323 					url: GCN.settings.BACKEND_PATH + '/rest/' + that._type +
1324 					     '/cancel/' + that.id() + GCN._getChannelParameter(that),
1325 					type: 'POST',
1326 					json: {}, // There needs to be at least empty content
1327 					          // because of a bug in Jersey.
1328 					error: error,
1329 					success: function (response) {
1330 						if (success) {
1331 							that._invoke(success, [that]);
1332 						}
1333 					}
1334 				});
1335 			});
1336 		},
1337 
1338 		/**
1339 		 * @see GCN.ContentObjectAPI._processResponse
1340 		 */
1341 		'!_processResponse': function (data) {
1342 			this._data = jQuery.extend(true, {}, data[this._type], this._data);
1343 
1344 			// if data contains page variants turn them into page objects
1345 			if (this._data.pageVariants) {
1346 				var pagevars = [];
1347 				var i;
1348 				for (i = 0; i < this._data.pageVariants.length; i++) {
1349 					pagevars.push(this._continue(GCN.PageAPI,
1350 						this._data.pageVariants[i]));
1351 				}
1352 				this._data.pageVariants = pagevars;
1353 			}
1354 		},
1355 
1356 		/**
1357 		 * @override
1358 		 */
1359 		'!_removeAssociatedTagData': function (tagid) {
1360 			var block;
1361 			for (block in this._blocks) {
1362 				if (this._blocks.hasOwnProperty(block) &&
1363 						this._blocks[block].tagname === tagid) {
1364 					delete this._blocks[block];
1365 				}
1366 			}
1367 
1368 			var editable, containedBlocks, i;
1369 			for (editable in this._editables) {
1370 				if (this._editables.hasOwnProperty(editable)) {
1371 					if (this._editables[editable].tagname === tagid) {
1372 						delete this._editables[editable];
1373 					} else {
1374 						containedBlocks = this._editables[editable]._gcnContainedBlocks;
1375 						if (jQuery.isArray(containedBlocks)) {
1376 							for (i = containedBlocks.length -1; i >= 0; i--) {
1377 								if (containedBlocks[i].tagname === tagid) {
1378 									containedBlocks.splice(i, 1);
1379 								}
1380 							}
1381 						}
1382 					}
1383 				}
1384 			}
1385 		}
1386 
1387 	});
1388 
1389 	/**
1390 	 * Creates a new instance of PageAPI.
1391 	 * See the {@link PageAPI} constructor for detailed information.
1392 	 * 
1393 	 * @function
1394 	 * @name page
1395 	 * @memberOf GCN
1396 	 * @see PageAPI
1397 	 */
1398 	GCN.page = GCN.exposeAPI(PageAPI);
1399 	GCN.PageAPI = PageAPI;
1400 
1401 	GCN.PageAPI.trackRenderedTags = trackRenderedTags;
1402 
1403 }(GCN));
1404