<commit_before>;(function() {

	var toString = Object.prototype.toString;

	var isFunction = function(obj) {
		return toString.call(obj) === "[object Function]";
	};

	// Based on jQuery.extend
	var apply = function() {
		var target = arguments[0] || {},
			i = 1,
			length = arguments.length,
			deep = false,
			options;

		if (typeof target === 'boolean') {
			deep = target;
			target = arguments[1] || {};
			i = 2;
		}

		if (typeof target !== 'object' && !isFunction(target)) {
			target = {};
		}

		if (length == i) {
			target = this;
			--i;
		}

		for (; i < length; i++) {
			if ((options = arguments[i]) != null) {
				for (var name in options) {
					var src = target[name],
						copy = options[name];

					if (target === copy) {
						continue;
					}

					if (deep && copy && typeof copy === 'object' && !copy.nodeType) {
						target[name] = apply(
							deep,
							src || (copy.length != null ? [] : {}),
							copy
						);
					}

					else if (copy !== undefined) {
						target[name] = copy;
					}

				}
			}
		}

		return target;
	};

	/*
	 * Alloy JavaScript Library v@VERSION
	 * http://alloyui.com/
	 *
	 * Copyright (c) 2009 Liferay Inc.
	 * Licensed under the MIT license.
	 * http://alloyui.com/License
	 *
	 * Nate Cavanaugh (nate.cavanaugh@liferay.com)
	 * Eduardo Lundgren (eduardo.lundgren@liferay.com)
	 *
	 * Date: @DATE
	 * Revision: @REVISION
	 */

	window.AUI = window.AUI || {};

	var defaults = AUI.defaults || {};
	var defaultModules = defaults.defaultModules || [];

	apply(
		YUI.prototype,
		{
			apply: apply,
			ready: function() {
				var instance = this;

				var slice = Array.prototype.slice;
				var args = slice.call(arguments, 0), index = args.length - 1;

				var fn = args[index];

				var modules = slice.call(arguments, 0, index);

				modules.push('event');

				modules.push(
					function(instance) {
						var args = arguments;

						instance.on(
							'domready',
							function() {
								fn.apply(this, args);
							}
						);
					}
				);

				instance.use.apply(instance, modules);
			},

			fromQueryString: function(str, allowMultipleValues) {
				var instance = this;

				var obj = {};
				var params = str.split('&');
				var name, value, param;

				var length = params.length;

				for (var i = 0; i < length; i++) {
					param = params[i];

					param = param.split('=');

					name = decodeURIComponent(param[0]);
					value = decodeURIComponent(param[1]);

					if (allowMultipleValues) {
						obj[name] = [].concat(obj[name]).concat(value);
					}
					else {
						obj[name] = value;
					}
				}

				return obj;
			},

			toQueryString: function(obj) {
				var instance = this;

				var Lang = instance.Lang;
				var isArray = Lang.isArray;
				var isFunction = Lang.isFunction;

				var buffer = [];
				var isNodeList = false;

				if (isArray(obj) || (isNodeList = (instance.NodeList && (obj instanceof instance.NodeList)))) {
					if (isNodeList) {
						obj = instance.NodeList.getDOMNodes(obj);
					}

					var length = obj.length;

					for (var i=0; i < length; i++) {
						var el = obj[i];

						buffer.push(encodeURIComponent(el.name) + '=' + encodeURIComponent(el.value));
					}
				}
				else {
					for (var i in obj){
						var value = obj[i];

						if (isArray(value)) {
							var vlength = value.length;

							for (var j = 0; j < vlength; j++) {
								buffer.push(encodeURIComponent(i) + '=' + encodeURIComponent(value[j]));
							}
						}
						else {
							if (isFunction(value)) {
								value = value();
							}

							buffer.push(encodeURIComponent(i) + '=' + encodeURIComponent(value));
						}
					}
				}

				return buffer.join('&').replace(/%20/g, '+');
			}
		}
	);

	var ALLOY = YUI(apply({}, defaults));

	ALLOY.Env._guidp = ['aui', ALLOY.version, ALLOY.Env._yidx, new Date().getTime()].join('-').replace(/\./g, '-');

	var originalConfig = ALLOY.config;

	defaultModules.push(
		function(A, result) {
			if (!result.success) {
				throw result.msg;
			}
		}
	);

	ALLOY.use.apply(ALLOY, defaultModules);

	AUI = function(o) {
		var instance = this;

		ALLOY.config = ALLOY.merge(originalConfig, AUI.defaults);

		if (o || instance instanceof AUI) {
			return YUI(ALLOY.merge(ALLOY.config, o));
		}

		return ALLOY;
	};

	apply(
		AUI,
		YUI,
		{
			__version: '@VERSION',

			apply: apply,

			defaults: defaults
		}
	);

	/*
	* AUI support constants
	*/
	AUI.support = {
		scriptEval: false
	};

	var checkScriptEvalSupport = function() {
		var root = document.documentElement;
		var script = document.createElement("script");

		var TYPE = 'text/javascript',
			TPL_EVAL_SCRIPT_TRUE = 'AUI.support.scriptEval = true;';

		script.type = TYPE;

		try {
			script.appendChild(document.createTextNode(TPL_EVAL_SCRIPT_TRUE));
			root.insertBefore(script, root.firstChild);
			root.removeChild(script);
		}
		catch(e) {
		}
	};

	checkScriptEvalSupport();

	/*
		UA extensions
	*/

	var UA = ALLOY.UA;

	var p = navigator.platform;
	var u = navigator.userAgent;
	var b = /(Firefox|Opera|Safari|KDE|iCab|Flock|IE)/.exec(u);
	var os = /(Win|Mac|Linux|iPhone|Sun|Solaris)/.exec(p);
	var versionDefaults = [0,0];

	b = (!b || !b.length) ? (/(Mozilla)/.exec(u) || ['']) : b;
	os = (!os || !os.length) ? [''] : os;

	apply(
		UA,
		{
			gecko: /Gecko/.test(u) && !/like Gecko/.test(u),
			webkit: /WebKit/.test(u),

			aol: /America Online Browser/.test(u),
			camino: /Camino/.test(u),
			firefox: /Firefox/.test(u),
			flock: /Flock/.test(u),
			icab: /iCab/.test(u),
			konqueror: /KDE/.test(u),
			mozilla: /mozilla/.test(u),
			ie: /MSIE/.test(u),
			netscape: /Netscape/.test(u),
			opera: /Opera/.test(u),
			safari: /Safari/.test(u),
			browser: b[0].toLowerCase(),

			win: /Win/.test(p),
			mac: /Mac/.test(p),
			linux: /Linux/.test(p),
			iphone: /iPhone/.test(p),
			sun: /Solaris|SunOS/.test(p),
			os: os[0].toLowerCase(),

			platform: p,
			agent: u
		}
	);

	UA.version = {
		string: ''
	};

	if (UA.ie) {
		UA.version.string = (/MSIE ([^;]+)/.exec(u) || versionDefaults)[1];
	}
	else if (UA.firefox) {
		UA.version.string = (/Firefox\/(.+)/.exec(u) || versionDefaults)[1];
	}
	else if (UA.safari) {
		UA.version.string = (/Version\/([^\s]+)/.exec(u) || versionDefaults)[1];
	}
	else if (UA.opera) {
		UA.version.string = (/Opera\/([^\s]+)/.exec(u) || versionDefaults)[1];
	}

	UA.version.number = parseFloat(UA.version.string) || versionDefaults[0];
	UA.version.major = (/([^\.]+)/.exec(UA.version.string) || versionDefaults)[1];

	UA[UA.browser + UA.version.major] = true;

	UA.renderer = '';

	if (UA.ie) {
		UA.renderer = 'trident';
	}
	else if (UA.gecko) {
		UA.renderer = 'gecko';
	}
	else if (UA.webkit) {
		UA.renderer = 'webkit';
	}
	else if (UA.opera) {
		UA.renderer = 'presto';
	}

	/*
		Browser selectors
	*/

	var selectors = [
		UA.renderer,
		UA.browser,
		UA.browser + UA.version.major,
		UA.os,
		'js'
	];

	if (UA.os == 'macintosh') {
		selectors.push('mac');
	}
	else if (UA.os == 'windows') {
		selectors.push('win');
	}

	if (UA.mobile) {
		selectors.push('mobile');
	}

	if (UA.secure) {
		selectors.push('secure');
	}

	UA.selectors = selectors.join(' ');

	document.getElementsByTagName('html')[0].className += ' ' + UA.selectors;
})();<commit_msg>Proposed fix for updating defaults<commit_after>;(function() {

	var toString = Object.prototype.toString;

	var isFunction = function(obj) {
		return toString.call(obj) === "[object Function]";
	};

	// Based on jQuery.extend
	var apply = function() {
		var target = arguments[0] || {},
			i = 1,
			length = arguments.length,
			deep = false,
			options;

		if (typeof target === 'boolean') {
			deep = target;
			target = arguments[1] || {};
			i = 2;
		}

		if (typeof target !== 'object' && !isFunction(target)) {
			target = {};
		}

		if (length == i) {
			target = this;
			--i;
		}

		for (; i < length; i++) {
			if ((options = arguments[i]) != null) {
				for (var name in options) {
					var src = target[name],
						copy = options[name];

					if (target === copy) {
						continue;
					}

					if (deep && copy && typeof copy === 'object' && !copy.nodeType) {
						target[name] = apply(
							deep,
							src || (copy.length != null ? [] : {}),
							copy
						);
					}

					else if (copy !== undefined) {
						target[name] = copy;
					}

				}
			}
		}

		return target;
	};

	/*
	 * Alloy JavaScript Library v@VERSION
	 * http://alloyui.com/
	 *
	 * Copyright (c) 2009 Liferay Inc.
	 * Licensed under the MIT license.
	 * http://alloyui.com/License
	 *
	 * Nate Cavanaugh (nate.cavanaugh@liferay.com)
	 * Eduardo Lundgren (eduardo.lundgren@liferay.com)
	 *
	 * Date: @DATE
	 * Revision: @REVISION
	 */

	window.AUI = window.AUI || {};

	var defaults = AUI.defaults || {};
	var defaultModules = defaults.defaultModules || [];

	apply(
		YUI.prototype,
		{
			apply: apply,
			ready: function() {
				var instance = this;

				var slice = Array.prototype.slice;
				var args = slice.call(arguments, 0), index = args.length - 1;

				var fn = args[index];

				var modules = slice.call(arguments, 0, index);

				modules.push('event');

				modules.push(
					function(instance) {
						var args = arguments;

						instance.on(
							'domready',
							function() {
								fn.apply(this, args);
							}
						);
					}
				);

				instance.use.apply(instance, modules);
			},

			fromQueryString: function(str, allowMultipleValues) {
				var instance = this;

				var obj = {};
				var params = str.split('&');
				var name, value, param;

				var length = params.length;

				for (var i = 0; i < length; i++) {
					param = params[i];

					param = param.split('=');

					name = decodeURIComponent(param[0]);
					value = decodeURIComponent(param[1]);

					if (allowMultipleValues) {
						obj[name] = [].concat(obj[name]).concat(value);
					}
					else {
						obj[name] = value;
					}
				}

				return obj;
			},

			toQueryString: function(obj) {
				var instance = this;

				var Lang = instance.Lang;
				var isArray = Lang.isArray;
				var isFunction = Lang.isFunction;

				var buffer = [];
				var isNodeList = false;

				if (isArray(obj) || (isNodeList = (instance.NodeList && (obj instanceof instance.NodeList)))) {
					if (isNodeList) {
						obj = instance.NodeList.getDOMNodes(obj);
					}

					var length = obj.length;

					for (var i=0; i < length; i++) {
						var el = obj[i];

						buffer.push(encodeURIComponent(el.name) + '=' + encodeURIComponent(el.value));
					}
				}
				else {
					for (var i in obj){
						var value = obj[i];

						if (isArray(value)) {
							var vlength = value.length;

							for (var j = 0; j < vlength; j++) {
								buffer.push(encodeURIComponent(i) + '=' + encodeURIComponent(value[j]));
							}
						}
						else {
							if (isFunction(value)) {
								value = value();
							}

							buffer.push(encodeURIComponent(i) + '=' + encodeURIComponent(value));
						}
					}
				}

				return buffer.join('&').replace(/%20/g, '+');
			}
		}
	);

	var ALLOY = YUI(apply({}, defaults));

	ALLOY.Env._guidp = ['aui', ALLOY.version, ALLOY.Env._yidx, new Date().getTime()].join('-').replace(/\./g, '-');

	var originalConfig = ALLOY.config;

	defaultModules.push(
		function(A, result) {
			if (!result.success) {
				throw result.msg;
			}
		}
	);

	ALLOY.use.apply(ALLOY, defaultModules);

	ALLOY.config = ALLOY.merge(originalConfig, AUI.defaults);

	AUI = function(o) {
		var instance = this;

		if (o || instance instanceof AUI) {
			return YUI(ALLOY.merge(ALLOY.config, o));
		}

		return ALLOY;
	};

	apply(
		AUI,
		YUI,
		{
			__version: '@VERSION',

			apply: apply,

			defaults: defaults,

			setDefaults: function(defaults) {
				var instance = this;

				ALLOY.config = ALLOY.merge(AUI.defaults, defaults);
			}
		}
	);

	/*
	* AUI support constants
	*/
	AUI.support = {
		scriptEval: false
	};

	var checkScriptEvalSupport = function() {
		var root = document.documentElement;
		var script = document.createElement("script");

		var TYPE = 'text/javascript',
			TPL_EVAL_SCRIPT_TRUE = 'AUI.support.scriptEval = true;';

		script.type = TYPE;

		try {
			script.appendChild(document.createTextNode(TPL_EVAL_SCRIPT_TRUE));
			root.insertBefore(script, root.firstChild);
			root.removeChild(script);
		}
		catch(e) {
		}
	};

	checkScriptEvalSupport();

	/*
		UA extensions
	*/

	var UA = ALLOY.UA;

	var p = navigator.platform;
	var u = navigator.userAgent;
	var b = /(Firefox|Opera|Safari|KDE|iCab|Flock|IE)/.exec(u);
	var os = /(Win|Mac|Linux|iPhone|Sun|Solaris)/.exec(p);
	var versionDefaults = [0,0];

	b = (!b || !b.length) ? (/(Mozilla)/.exec(u) || ['']) : b;
	os = (!os || !os.length) ? [''] : os;

	apply(
		UA,
		{
			gecko: /Gecko/.test(u) && !/like Gecko/.test(u),
			webkit: /WebKit/.test(u),

			aol: /America Online Browser/.test(u),
			camino: /Camino/.test(u),
			firefox: /Firefox/.test(u),
			flock: /Flock/.test(u),
			icab: /iCab/.test(u),
			konqueror: /KDE/.test(u),
			mozilla: /mozilla/.test(u),
			ie: /MSIE/.test(u),
			netscape: /Netscape/.test(u),
			opera: /Opera/.test(u),
			safari: /Safari/.test(u),
			browser: b[0].toLowerCase(),

			win: /Win/.test(p),
			mac: /Mac/.test(p),
			linux: /Linux/.test(p),
			iphone: /iPhone/.test(p),
			sun: /Solaris|SunOS/.test(p),
			os: os[0].toLowerCase(),

			platform: p,
			agent: u
		}
	);

	UA.version = {
		string: ''
	};

	if (UA.ie) {
		UA.version.string = (/MSIE ([^;]+)/.exec(u) || versionDefaults)[1];
	}
	else if (UA.firefox) {
		UA.version.string = (/Firefox\/(.+)/.exec(u) || versionDefaults)[1];
	}
	else if (UA.safari) {
		UA.version.string = (/Version\/([^\s]+)/.exec(u) || versionDefaults)[1];
	}
	else if (UA.opera) {
		UA.version.string = (/Opera\/([^\s]+)/.exec(u) || versionDefaults)[1];
	}

	UA.version.number = parseFloat(UA.version.string) || versionDefaults[0];
	UA.version.major = (/([^\.]+)/.exec(UA.version.string) || versionDefaults)[1];

	UA[UA.browser + UA.version.major] = true;

	UA.renderer = '';

	if (UA.ie) {
		UA.renderer = 'trident';
	}
	else if (UA.gecko) {
		UA.renderer = 'gecko';
	}
	else if (UA.webkit) {
		UA.renderer = 'webkit';
	}
	else if (UA.opera) {
		UA.renderer = 'presto';
	}

	/*
		Browser selectors
	*/

	var selectors = [
		UA.renderer,
		UA.browser,
		UA.browser + UA.version.major,
		UA.os,
		'js'
	];

	if (UA.os == 'macintosh') {
		selectors.push('mac');
	}
	else if (UA.os == 'windows') {
		selectors.push('win');
	}

	if (UA.mobile) {
		selectors.push('mobile');
	}

	if (UA.secure) {
		selectors.push('secure');
	}

	UA.selectors = selectors.join(' ');

	document.getElementsByTagName('html')[0].className += ' ' + UA.selectors;
})();<|endoftext|>


<commit_before>AUI().add(
	'tabs',
	function(A) {
		var Lang = A.Lang,

			getClassName = A.ClassNameManager.getClassName,

			TAB = 'tab',
			TABVIEW = 'tabview',

			BOUNDING_BOX = 'boundingBox',
			CONTENT_BOX = 'contentBox',
			CONTENT_NODE = 'contentNode',

			CSS_TAB = getClassName(TAB),
			CSS_TAB_LABEL = getClassName(TAB, 'label'),
			CSS_TAB_DISABLED = getClassName(TAB, 'disabled'),
			CSS_TAB_ACTIVE = getClassName(TAB, 'active'),

			CSS_TABVIEW_LIST = [getClassName(TABVIEW, 'list'), getClassName('widget', 'hd')].join(' '),
			CSS_TABVIEW_CONTENT = [getClassName(TABVIEW, 'content'), getClassName('widget', 'bd')].join(' '),

			CSS_HIDDEN = getClassName('helper-hidden'),

			TPL_DIV = '

',
			TPL_SPAN = '',
			TPL_UL = '

',

			TPL_LABEL = TPL_SPAN,
			TPL_TAB_CONTAINER = TPL_UL,
			TPL_CONTENT_ITEM = TPL_DIV,
			TPL_CONTENT_CONTAINER = TPL_DIV;

		var Tab = function() {
			Tab.superclass.constructor.apply(this, arguments);
		};

		Tab.NAME = TAB;

		Tab.ATTRS = {
			label: {
				lazyAdd: false,
				valueFn: function() {
					var instance = this;

					var boundingBox = instance.get(BOUNDING_BOX);

					var label = boundingBox.one('.' + CSS_TAB_LABEL);

					var value;

					if (label) {
						value = label.html();

						instance.set('labelNode', label);
					}
					else {
						value = boundingBox.html();
						boundingBox.html('');
					}

					return value;
				},

				setter: function(value) {
					var instance = this;

					var labelNode = instance.get('labelNode');

					labelNode.html(value);

					return value;
				}
			},

			labelNode: {
				valueFn: function() {
					var instance = this;

					var labelNode = instance.get(BOUNDING_BOX).one('.' + CSS_TAB_LABEL);

					if (!labelNode) {
						labelNode = instance._createDefaultLabel();
					}

					instance.get(CONTENT_BOX).appendChild(labelNode);

					return labelNode;
				},
				setter: function(value) {
					var instance = this;

					var node = A.Node.get(value);

					if (!node) {
						node = instance._createDefaultLabel();

						instance.get(CONTENT_BOX).appendChild(node);
					}

					node.addClass(CSS_TAB_LABEL);

					return node;
				}
			},

			contentNode: {
				value: null,
				setter: function(value) {
					var instance = this;

					var node = A.Node.get(value);

					if (!node) {
						node = instance._createDefaultContentEl();

						instance.get(CONTENT_BOX).prepend(node);
					}

					node.addClass(CSS_TABVIEW_CONTENT);

					var current = instance.get(CONTENT_NODE);

					if (current) {
						if (!instance.get('active')) {
							node.addClass(CSS_HIDDEN);
						}

						var currentHTML = node.html();

						instance.set('content', currentHTML);
					}

					return node;
				}
			},

			content: {
				lazyAdd: false,
				valueFn: function() {
					var instance = this;

					var value = '';
					var contentNode = instance.get(CONTENT_NODE);

					if (contentNode) {
						value = contentNode.html();
					}

					return value;
				},
				setter: function(value) {
					var instance = this;

					var node = instance.get(CONTENT_NODE);

					var currentHTML = node.html();

					if (currentHTML != value) {
						node.html(value);
					}

					return value;
				}
			},

			active: {
				valueFn: function() {
					var instance = this;

					return instance.get(BOUNDING_BOX).hasClass(CSS_TAB_ACTIVE);
				},
				validator: function(value) {
					var instance = this;

					return Lang.isBoolean(value) && !instance.get('disabled');
				},
				setter: function(value) {
					var instance = this;

					var action = 'addClass';
					var boundingBox = instance.get(BOUNDING_BOX);

					if (value === false) {
						action = 'removeClass';
					}

					instance.StateInteraction.set('active', value);

					boundingBox[action](CSS_TAB_ACTIVE);

					instance.set('contentVisible', value);

					return value;
				}
			},

			disabled: {
				valueFn: function() {
					var instance = this;

					return instance.get(BOUNDING_BOX).hasClass(CSS_TAB_DISABLED);
				},
				setter: function(value) {
					var instance = this;

					var action = 'addClass';
					var boundingBox = instance.get(BOUNDING_BOX);

					if (value === false) {
						action = 'removeClass';
					}

					boundingBox[action](CSS_TAB_DISABLED);

					return value;
				}
			},

			contentVisible: {
				value: false,
				setter: function(value) {
					var instance = this;

					var action = 'addClass';
					var contentNode = instance.get(CONTENT_NODE);

					if (value === true) {
						action = 'removeClass';
					}

					contentNode[action](CSS_HIDDEN);

					return value;
				}
			},

			tabView: {
				value: null
			}
		};

		A.extend(
			Tab,
			A.Component,
			{
				BOUNDING_TEMPLATE: '

',
				CONTENT_TEMPLATE: '',
				bindUI: function() {
					var instance = this;

					var boundingBox = instance.get(BOUNDING_BOX);

					boundingBox.plug(
						A.StateInteractionPlugin,
						{
							bubbleTarget: instance
						}
					);

					boundingBox.StateInteraction.on('click', instance._onActivateTab, instance);

					instance.StateInteraction = boundingBox.StateInteraction;

					instance.get('labelNode').on('click', instance._onLabelClick, instance);
				},

				destructor: function() {
					var instance = this;

					var boundingBox = instance.get(BOUNDING_BOX);
					var contentNode = instance.get(CONTENT_NODE);

					A.Event.purgeElement(boundingBox, true);
					A.Event.purgeElement(contentNode, true);

					boundingBox.remove();
					contentNode.remove();
				},

				_createDefaultLabel: function() {
					var instance = this;

					return A.Node.create(TPL_LABEL);
				},

				_createDefaultContentEl: function() {
					var instance = this;

					return A.Node.create(TPL_CONTENT_ITEM);
				},

				_onActivateTab: function(event) {
					var instance = this;

					event.halt();

					var tabView = instance.get('tabView');

					tabView.set('activeTab', instance);
				},

				_onLabelClick: function(event) {
					event.preventDefault();
				}
			}
		);

		A.Tab = Tab;

		var TabView = function() {
			TabView.superclass.constructor.apply(this, arguments);
		};

		TabView.NAME = TABVIEW;

		TabView.ATTRS = {
			listNode: {
				value: null,
				setter: function(value) {
					var instance = this;

					var node = A.Node.get(value);

					if (!node) {
						node = instance._createDefaultList();
					}

					instance.get(CONTENT_BOX).prepend(node);

					node.addClass(CSS_TABVIEW_LIST);

					return node;
				}
			},

			contentNode: {
				value: null,
				setter: function(value) {
					var instance = this;

					var node = A.Node.get(value);

					if (!node) {
						node = instance._createDefaultContentContainer();
					}

					instance.get(CONTENT_BOX).appendChild(node);

					node.addClass(CSS_TABVIEW_CONTENT);

					return node;
				}
			},

			items: {
				value: []
			},

			activeTab: {
				value: null,
				setter: function(value) {
					var instance = this;

					var activeTab = instance.get('activeTab');

					if (activeTab && activeTab != value) {
						activeTab.set('active', false);
					}

					return value;
				},
				validator: function(value) {
					return Lang.isNull(value) || (value && !value.get('disabled'));
				}
			}
		};

		A.extend(
			TabView,
			A.Component,
			{
				renderUI: function() {
					var instance = this;

					instance.after('activeTabChange', instance._onActiveTabChange);

					instance._renderContentSections();
					instance._renderTabs();
				},

				addTab: function(tab, index) {
					var instance = this;

					var before = instance.getTab(index);

					var items = instance.get('items');

					if (Lang.isUndefined(index)) {
						index = A.Array.indexOf(items, tab);
					}

					var inArray = index > -1;

					if (!inArray) {
						index = items.length;

						items.splice(index, 0, tab);
					}

					if (!instance.get('rendered') && !inArray) {
						return;
					}

					if (!(tab instanceof Tab)) {
						tab = new Tab(tab);

						items.splice(index, 1, tab);
					}

					var listNode = instance.get('listNode');

					tab.render(listNode);

					if (before) {
						listNode.insert(tab.get(BOUNDING_BOX), before.get(BOUNDING_BOX));
					}
					else {
						listNode.appendChild(tab.get(BOUNDING_BOX));
					}

					var tabContentNode = tab.get(CONTENT_NODE);

					var tabViewContentNode = instance.get(CONTENT_NODE);

					if (!tabViewContentNode.contains(tabContentNode)) {
						tabViewContentNode.appendChild(tabContentNode);
					}

					if (tab.get('active')) {
						instance.set('activeTab', tab);
					}

					tab.set('tabView', instance);
				},

				deselectTab: function(index){
					var instance = this;

					if (instance.getTab(index) === instance.get('activeTab')) {
						instance.set('activeTab', null);
					}
				},

				disableTab: function(index){
					var instance = this;

					var tab;

					if (Lang.isNumber(index)) {
						tab = instance.getTab(index);
					}
					else {
						tab = index;
					}

					if (tab) {
						tab.set('disabled', true);
					}
				},

				enableTab: function(index){
					var instance = this;

					var tab;

					if (Lang.isNumber(index)) {
						tab = instance.getTab(index);
					}
					else {
						tab = index;
					}

					if (tab) {
						tab.set('disabled', false);
					}
				},

				getTab: function(index){
					var instance = this;

					return instance.get('items')[index];
				},

				getTabIndex: function(tab){
					var instance = this;

					var items = instance.get('items');

					return A.Array.indexOf(items, tab);
				},

				removeTab: function(index){
					var instance = this;

					var tab;

					if (Lang.isNumber(index)) {
						tab = instance.getTab(index);
					}
					else {
						tab = index;
					}

					if (tab) {
						var items = instance.get('items');

						var tabCount = items.length;

						if (tab === instance.get('activeTab')) {
							if (tabCount > 1) {
								if (index + 1 === tabCount) {
									instance.selectTab(index - 1);
								}
								else {
									instance.selectTab(index + 1);
								}
							}
							else {
								instance.set('activeTab', null);
							}
						}

						tab.destroy();

						items.splice(index, 1);
					}
				},

				selectTab: function(index){
					var instance = this;

					var selectedTab = instance.getTab(index);

					instance.set('activeTab', selectedTab);
				},

				_createDefaultList: function() {
					var instance = this;

					return A.Node.create(TPL_TAB_CONTAINER);
				},

				_createDefaultContentContainer: function() {
					var instance = this;

					return A.Node.create(TPL_CONTENT_CONTAINER);
				},

				_onActiveTabChange: function(event) {
					var instance = this;

					var oldTab = event.prevVal;
					var newTab = event.newVal;

					if (newTab) {
						newTab.set('active', true);
					}

					if (oldTab) {
						oldTab.set('active', false);
					}
				},

				_renderContentSections: function() {
					var instance = this;

					instance._renderSection('list');
					instance._renderSection('content');
				},

				_renderSection: function(section) {
					var instance = this;

					instance.get(section + 'Node');
				},

				_renderTabs: function() {
					var instance = this;

					var contentNode = instance.get(CONTENT_NODE);
					var listNode = instance.get('listNode');

					var tabs = listNode.get('children');
					var tabContent = contentNode.get('children');

					var items = instance.get('items');

					tabs.each(
						function(node, i, nodeList) {
							var config = {
								boundingBox: node,
								contentNode: tabContent.item(i)
							};

							items.splice(i, 0, config);
						}
					);

					var length = items.length;

					for (var i = 0; i < items.length; i++) {
						instance.addTab(items[i]);
					}

					if (!instance.get('activeTab')) {
						instance.selectTab(0);
					}
				}
			}
		);

		A.TabView = TabView;
	},
	'0.1a',
	{
		requires: ['component', 'state-interaction', 'tabs-css'],
		use: []
	}
);<commit_msg>Tabs fixing toggle section when click on active tab<commit_after>AUI().add(
	'tabs',
	function(A) {
		var Lang = A.Lang,

			getClassName = A.ClassNameManager.getClassName,

			TAB = 'tab',
			TABVIEW = 'tabview',

			BOUNDING_BOX = 'boundingBox',
			CONTENT_BOX = 'contentBox',
			CONTENT_NODE = 'contentNode',

			CSS_TAB = getClassName(TAB),
			CSS_TAB_LABEL = getClassName(TAB, 'label'),
			CSS_TAB_DISABLED = getClassName(TAB, 'disabled'),
			CSS_TAB_ACTIVE = getClassName(TAB, 'active'),

			CSS_TABVIEW_LIST = [getClassName(TABVIEW, 'list'), getClassName('widget', 'hd')].join(' '),
			CSS_TABVIEW_CONTENT = [getClassName(TABVIEW, 'content'), getClassName('widget', 'bd')].join(' '),

			CSS_HIDDEN = getClassName('helper-hidden'),

			TPL_DIV = '

',
			TPL_SPAN = '',
			TPL_UL = '

',

			TPL_LABEL = TPL_SPAN,
			TPL_TAB_CONTAINER = TPL_UL,
			TPL_CONTENT_ITEM = TPL_DIV,
			TPL_CONTENT_CONTAINER = TPL_DIV;

		var Tab = function() {
			Tab.superclass.constructor.apply(this, arguments);
		};

		Tab.NAME = TAB;

		Tab.ATTRS = {
			label: {
				lazyAdd: false,
				valueFn: function() {
					var instance = this;

					var boundingBox = instance.get(BOUNDING_BOX);

					var label = boundingBox.one('.' + CSS_TAB_LABEL);

					var value;

					if (label) {
						value = label.html();

						instance.set('labelNode', label);
					}
					else {
						value = boundingBox.html();
						boundingBox.html('');
					}

					return value;
				},

				setter: function(value) {
					var instance = this;

					var labelNode = instance.get('labelNode');

					labelNode.html(value);

					return value;
				}
			},

			labelNode: {
				valueFn: function() {
					var instance = this;

					var labelNode = instance.get(BOUNDING_BOX).one('.' + CSS_TAB_LABEL);

					if (!labelNode) {
						labelNode = instance._createDefaultLabel();
					}

					instance.get(CONTENT_BOX).appendChild(labelNode);

					return labelNode;
				},
				setter: function(value) {
					var instance = this;

					var node = A.Node.get(value);

					if (!node) {
						node = instance._createDefaultLabel();

						instance.get(CONTENT_BOX).appendChild(node);
					}

					node.addClass(CSS_TAB_LABEL);

					return node;
				}
			},

			contentNode: {
				value: null,
				setter: function(value) {
					var instance = this;

					var node = A.Node.get(value);

					if (!node) {
						node = instance._createDefaultContentEl();

						instance.get(CONTENT_BOX).prepend(node);
					}

					node.addClass(CSS_TABVIEW_CONTENT);

					var current = instance.get(CONTENT_NODE);

					if (current) {
						if (!instance.get('active')) {
							node.addClass(CSS_HIDDEN);
						}

						var currentHTML = node.html();

						instance.set('content', currentHTML);
					}

					return node;
				}
			},

			content: {
				lazyAdd: false,
				valueFn: function() {
					var instance = this;

					var value = '';
					var contentNode = instance.get(CONTENT_NODE);

					if (contentNode) {
						value = contentNode.html();
					}

					return value;
				},
				setter: function(value) {
					var instance = this;

					var node = instance.get(CONTENT_NODE);

					var currentHTML = node.html();

					if (currentHTML != value) {
						node.html(value);
					}

					return value;
				}
			},

			active: {
				valueFn: function() {
					var instance = this;

					return instance.get(BOUNDING_BOX).hasClass(CSS_TAB_ACTIVE);
				},
				validator: function(value) {
					var instance = this;

					return Lang.isBoolean(value) && !instance.get('disabled');
				},
				setter: function(value) {
					var instance = this;

					var action = 'addClass';
					var boundingBox = instance.get(BOUNDING_BOX);

					if (value === false) {
						action = 'removeClass';
					}

					instance.StateInteraction.set('active', value);

					boundingBox[action](CSS_TAB_ACTIVE);

					instance.set('contentVisible', value);

					return value;
				}
			},

			disabled: {
				valueFn: function() {
					var instance = this;

					return instance.get(BOUNDING_BOX).hasClass(CSS_TAB_DISABLED);
				},
				setter: function(value) {
					var instance = this;

					var action = 'addClass';
					var boundingBox = instance.get(BOUNDING_BOX);

					if (value === false) {
						action = 'removeClass';
					}

					boundingBox[action](CSS_TAB_DISABLED);

					return value;
				}
			},

			contentVisible: {
				value: false,
				setter: function(value) {
					var instance = this;

					var action = 'addClass';
					var contentNode = instance.get(CONTENT_NODE);

					if (value === true) {
						action = 'removeClass';
					}

					if (!instance.get('active')) {
						contentNode[action](CSS_HIDDEN);
					}

					return value;
				}
			},

			tabView: {
				value: null
			}
		};

		A.extend(
			Tab,
			A.Component,
			{
				BOUNDING_TEMPLATE: '

',
				CONTENT_TEMPLATE: '',
				bindUI: function() {
					var instance = this;

					var boundingBox = instance.get(BOUNDING_BOX);

					boundingBox.plug(
						A.StateInteractionPlugin,
						{
							bubbleTarget: instance
						}
					);

					boundingBox.StateInteraction.on('click', instance._onActivateTab, instance);

					instance.StateInteraction = boundingBox.StateInteraction;

					instance.get('labelNode').on('click', instance._onLabelClick, instance);
				},

				destructor: function() {
					var instance = this;

					var boundingBox = instance.get(BOUNDING_BOX);
					var contentNode = instance.get(CONTENT_NODE);

					A.Event.purgeElement(boundingBox, true);
					A.Event.purgeElement(contentNode, true);

					boundingBox.remove();
					contentNode.remove();
				},

				_createDefaultLabel: function() {
					var instance = this;

					return A.Node.create(TPL_LABEL);
				},

				_createDefaultContentEl: function() {
					var instance = this;

					return A.Node.create(TPL_CONTENT_ITEM);
				},

				_onActivateTab: function(event) {
					var instance = this;

					event.halt();

					var tabView = instance.get('tabView');

					tabView.set('activeTab', instance);
				},

				_onLabelClick: function(event) {
					event.preventDefault();
				}
			}
		);

		A.Tab = Tab;

		var TabView = function() {
			TabView.superclass.constructor.apply(this, arguments);
		};

		TabView.NAME = TABVIEW;

		TabView.ATTRS = {
			listNode: {
				value: null,
				setter: function(value) {
					var instance = this;

					var node = A.Node.get(value);

					if (!node) {
						node = instance._createDefaultList();
					}

					instance.get(CONTENT_BOX).prepend(node);

					node.addClass(CSS_TABVIEW_LIST);

					return node;
				}
			},

			contentNode: {
				value: null,
				setter: function(value) {
					var instance = this;

					var node = A.Node.get(value);

					if (!node) {
						node = instance._createDefaultContentContainer();
					}

					instance.get(CONTENT_BOX).appendChild(node);

					node.addClass(CSS_TABVIEW_CONTENT);

					return node;
				}
			},

			items: {
				value: []
			},

			activeTab: {
				value: null,
				setter: function(value) {
					var instance = this;

					var activeTab = instance.get('activeTab');

					if (activeTab && activeTab != value) {
						activeTab.set('active', false);
					}

					return value;
				},
				validator: function(value) {
					return Lang.isNull(value) || (value && !value.get('disabled'));
				}
			}
		};

		A.extend(
			TabView,
			A.Component,
			{
				renderUI: function() {
					var instance = this;

					instance.after('activeTabChange', instance._onActiveTabChange);

					instance._renderContentSections();
					instance._renderTabs();
				},

				addTab: function(tab, index) {
					var instance = this;

					var before = instance.getTab(index);

					var items = instance.get('items');

					if (Lang.isUndefined(index)) {
						index = A.Array.indexOf(items, tab);
					}

					var inArray = index > -1;

					if (!inArray) {
						index = items.length;

						items.splice(index, 0, tab);
					}

					if (!instance.get('rendered') && !inArray) {
						return;
					}

					if (!(tab instanceof Tab)) {
						tab = new Tab(tab);

						items.splice(index, 1, tab);
					}

					var listNode = instance.get('listNode');

					tab.render(listNode);

					if (before) {
						listNode.insert(tab.get(BOUNDING_BOX), before.get(BOUNDING_BOX));
					}
					else {
						listNode.appendChild(tab.get(BOUNDING_BOX));
					}

					var tabContentNode = tab.get(CONTENT_NODE);

					var tabViewContentNode = instance.get(CONTENT_NODE);

					if (!tabViewContentNode.contains(tabContentNode)) {
						tabViewContentNode.appendChild(tabContentNode);
					}

					if (tab.get('active')) {
						instance.set('activeTab', tab);
					}

					tab.set('tabView', instance);
				},

				deselectTab: function(index){
					var instance = this;

					if (instance.getTab(index) === instance.get('activeTab')) {
						instance.set('activeTab', null);
					}
				},

				disableTab: function(index){
					var instance = this;

					var tab;

					if (Lang.isNumber(index)) {
						tab = instance.getTab(index);
					}
					else {
						tab = index;
					}

					if (tab) {
						tab.set('disabled', true);
					}
				},

				enableTab: function(index){
					var instance = this;

					var tab;

					if (Lang.isNumber(index)) {
						tab = instance.getTab(index);
					}
					else {
						tab = index;
					}

					if (tab) {
						tab.set('disabled', false);
					}
				},

				getTab: function(index){
					var instance = this;

					return instance.get('items')[index];
				},

				getTabIndex: function(tab){
					var instance = this;

					var items = instance.get('items');

					return A.Array.indexOf(items, tab);
				},

				removeTab: function(index){
					var instance = this;

					var tab;

					if (Lang.isNumber(index)) {
						tab = instance.getTab(index);
					}
					else {
						tab = index;
					}

					if (tab) {
						var items = instance.get('items');

						var tabCount = items.length;

						if (tab === instance.get('activeTab')) {
							if (tabCount > 1) {
								if (index + 1 === tabCount) {
									instance.selectTab(index - 1);
								}
								else {
									instance.selectTab(index + 1);
								}
							}
							else {
								instance.set('activeTab', null);
							}
						}

						tab.destroy();

						items.splice(index, 1);
					}
				},

				selectTab: function(index){
					var instance = this;

					var selectedTab = instance.getTab(index);

					instance.set('activeTab', selectedTab);
				},

				_createDefaultList: function() {
					var instance = this;

					return A.Node.create(TPL_TAB_CONTAINER);
				},

				_createDefaultContentContainer: function() {
					var instance = this;

					return A.Node.create(TPL_CONTENT_CONTAINER);
				},

				_onActiveTabChange: function(event) {
					var instance = this;

					var oldTab = event.prevVal;
					var newTab = event.newVal;

					if (newTab) {
						newTab.set('active', true);
					}

					if (newTab != oldTab) {
						if (oldTab) {
							oldTab.set('active', false);
						}
					}
				},

				_renderContentSections: function() {
					var instance = this;

					instance._renderSection('list');
					instance._renderSection('content');
				},

				_renderSection: function(section) {
					var instance = this;

					instance.get(section + 'Node');
				},

				_renderTabs: function() {
					var instance = this;

					var contentNode = instance.get(CONTENT_NODE);
					var listNode = instance.get('listNode');

					var tabs = listNode.get('children');
					var tabContent = contentNode.get('children');

					var items = instance.get('items');

					tabs.each(
						function(node, i, nodeList) {
							var config = {
								boundingBox: node,
								contentNode: tabContent.item(i)
							};

							items.splice(i, 0, config);
						}
					);

					var length = items.length;

					for (var i = 0; i < items.length; i++) {
						instance.addTab(items[i]);
					}

					if (!instance.get('activeTab')) {
						instance.selectTab(0);
					}
				}
			}
		);

		A.TabView = TabView;
	},
	'0.1a',
	{
		requires: ['component', 'state-interaction', 'tabs-css'],
		use: []
	}
);<|endoftext|>


<commit_before>'use strict';

(function () {
  var EVENT_NAMES = {
    ALL_IDS_COMPLETE: 'allIdsComplete',
    ID_ADDED: 'idAdded',
    ID_RETAINED: 'idRetained'
  };

  CKEDITOR.plugins.add('autoid', {
    init: function (editor) {
      var self = this;

      // This configures the Advanced Content Filter to allow all headings
      // to have id attributes
      editor.addFeature({
        allowedContent: 'h1 h2 h3 h4 h5 h6 *[id]'
      });

      if (editor && !editor.config.autoid) {
        editor.config.autoid = {};
      }
      self.settings = editor.config.autoid;
      if (!self.settings) {
        self.settings = {};
      }

      editor.addCommand('autoid', {
        exec: function (editor) {
          var autoId = editor.getCommand('autoid');
          autoId.toggleState();
          if (autoId.state === CKEDITOR.TRISTATE_ON)
            addAllIds();
        },
        editorFocus: true
      });

      editor.on("instanceReady", function () {
        if (self.settings.autostart !== false) {
          editor.getCommand('autoid').setState(CKEDITOR.TRISTATE_ON);
          addAllIds();
        }
      });

      CKEDITOR.on('dialogDefinition', modifyLinkDialog);

      editor.on('selectionChange', addIdIfNewHeading);

      editor.on('paste', checkPastedContentForHeadings);

      function addAllIds() {
        var headings = findAllHeadings(),
          i, heading;

        for (i = 0; i < headings.count(); i++) {
          heading = headings.getItem(i);
          if (heading.hasAttribute('id')) {
            continue;
          }
          addId(heading);
        }
        editor.fire(EVENT_NAMES.ALL_IDS_COMPLETE);
      }

      function findAllHeadings() {
        return editor.document.find('h1, h2, h3, h4, h5, h6');
      }

      function findHeadingIds(headings) {
        var ids = [],
          i, heading, id;

        for (i = 0; i < headings.count(); i++) {
          heading = headings.getItem(i);
          if (id = heading.getAttribute('id')) {
            ids.push(id)
          }
        }
        return ids;
      }

      function addId(heading) {
        var uuid = CKEDITOR.tools.getUniqueId();
        heading.setAttributes({ id: uuid });
        editor.fire(EVENT_NAMES.ID_ADDED);
      }

      function addIdIfNewHeading() {
        var element = editor.getSelection().getStartElement();
        if (isHeading(element) && !element.hasAttribute('id')) {
          addId(element);
        }
      }

      function isHeading(element) {
        return element.is('h1', 'h2', 'h3', 'h4', 'h5', 'h6');
      }

      function checkPastedContentForHeadings(ev) {
        var pastedContent = ev.data.dataValue,
          pastedContentAsHtml = CKEDITOR.htmlParser.fragment.fromHtml(pastedContent),
          pastedElements = pastedContentAsHtml.children,
          writer = new CKEDITOR.htmlParser.basicWriter(),
          i, element, id, originalHeading;

        for (i = 0; i < pastedElements.length; i++) {
          element = pastedElements[i];
          if (element.type === CKEDITOR.NODE_ELEMENT) {
            id = element.attributes.id;
            originalHeading = checkForDuplicateId(id);
            if (originalHeading) {
              element = resolveDuplicateIds(element, originalHeading);
            }
          }
        }

        pastedContentAsHtml.writeHtml(writer);
        ev.data.dataValue = writer.getHtml();
      }

      function checkForDuplicateId(id) {
        var headingIds = findHeadingIds(findAllHeadings()),
          i, headingId, originalHeading;

        for (i = 0; i < headingIds.length; i++) {
          headingId = headingIds[i];
          if (id === headingId) {
            return originalHeading = editor.document.getById(headingId);
          }
        }
      }

      function resolveDuplicateIds(newHeading, originalHeading) {
        var newHeadingText = newHeading.children[0].value,
          originalHeadingText = originalHeading.getText();

        // if the original heading has no content (blank or just a line-feed
        // character is left when all the content is cut), the original heading
        // will be removed and the new heading will retain the id
        if ( originalHeadingText.length <= 1 && notWordCharacter(originalHeadingText.charAt(0))) {
          originalHeading.remove();
          editor.fire(EVENT_NAMES.ID_RETAINED);
          return newHeading;
        }

        // if the original heading text is not blank, the original should retain its
        // id and the new heading should get a new one.
        if (originalHeadingText) {
          newHeading.attributes.id = CKEDITOR.tools.getUniqueId();
          editor.fire(EVENT_NAMES.ID_ADDED);
          return newHeading;
        }

      }

      function notWordCharacter(character) {
        if (!character)
          return true;

        return !(/\w/.test(character));
      }

      // This modifies the dialog for the 'link' plugin to allow the option of
      // internal document linking to autoid headings. Original 'link' plugin
      // code can be found at:
      // https://github.com/ckeditor/ckeditor-dev/tree/master/plugins/link

      function modifyLinkDialog(ev) {
        var dialog = ev.data;

        if (dialog.name == 'link') {
          var def = ev.data.definition,
            infoTab = def.contents[0],
            linkTypeTab = infoTab.elements[1];

          linkTypeTab.items.push(['Link to heading in the text', 'heading']);
          linkTypeTab.onChange = modifiedLinkTypeChanged;
        }
      }

      function modifiedLinkTypeChanged() {
        var dialog = this.getDialog(),
          partIds = [ 'urlOptions', 'anchorOptions', 'emailOptions', 'headingOptions' ],
          typeValue = this.getValue(),
          uploadTab = dialog.definition.getContents( 'upload' ),
          uploadInitiallyHidden = uploadTab && uploadTab.hidden;

        if ( typeValue == 'url' ) {
          if ( editor.config.linkShowTargetTab )
            dialog.showPage( 'target' );
          if ( !uploadInitiallyHidden )
            dialog.showPage( 'upload' );
          } else {
            dialog.hidePage( 'target' );
          if ( !uploadInitiallyHidden )
            dialog.hidePage( 'upload' );
        }

        for ( var i = 0; i < partIds.length; i++ ) {
          var element = dialog.getContentElement( 'info', partIds[ i ] );
          if ( !element )
            continue;

          element = element.getElement().getParent().getParent();
          if ( partIds[ i ] == typeValue + 'Options' )
            element.show();
          else
            element.hide();
        }

        dialog.layout();
      }

    }
  });
})();
<commit_msg>Add some comments<commit_after>'use strict';

(function () {
  var EVENT_NAMES = {
    ALL_IDS_COMPLETE: 'allIdsComplete',
    ID_ADDED: 'idAdded',
    ID_RETAINED: 'idRetained'
  };

  CKEDITOR.plugins.add('autoid', {
    init: function (editor) {
      var self = this;

      // This configures the Advanced Content Filter to allow all headings
      // to have id attributes
      editor.addFeature({
        allowedContent: 'h1 h2 h3 h4 h5 h6 *[id]'
      });

      if (editor && !editor.config.autoid) {
        editor.config.autoid = {};
      }
      self.settings = editor.config.autoid;
      if (!self.settings) {
        self.settings = {};
      }

      editor.addCommand('autoid', {
        exec: function (editor) {
          var autoId = editor.getCommand('autoid');
          autoId.toggleState();
          if (autoId.state === CKEDITOR.TRISTATE_ON)
            addAllIds();
        },
        editorFocus: true
      });

      editor.on("instanceReady", function () {
        if (self.settings.autostart !== false) {
          editor.getCommand('autoid').setState(CKEDITOR.TRISTATE_ON);
          addAllIds();
        }
      });

      CKEDITOR.on('dialogDefinition', modifyLinkDialog);

      editor.on('selectionChange', addIdIfNewHeading);

      editor.on('paste', checkPastedContentForHeadings);

      function addAllIds() {
        var headings = findAllHeadings(),
          i, heading;

        for (i = 0; i < headings.count(); i++) {
          heading = headings.getItem(i);
          if (heading.hasAttribute('id')) {
            continue;
          }
          addId(heading);
        }
        editor.fire(EVENT_NAMES.ALL_IDS_COMPLETE);
      }

      function findAllHeadings() {
        return editor.document.find('h1, h2, h3, h4, h5, h6');
      }

      function findHeadingIds(headings) {
        var ids = [],
          i, heading, id;

        for (i = 0; i < headings.count(); i++) {
          heading = headings.getItem(i);
          if (id = heading.getAttribute('id')) {
            ids.push(id)
          }
        }
        return ids;
      }

      function addId(heading) {
        var uuid = CKEDITOR.tools.getUniqueId();
        heading.setAttributes({ id: uuid });
        editor.fire(EVENT_NAMES.ID_ADDED);
      }

      function addIdIfNewHeading() {
        var element = editor.getSelection().getStartElement();
        if (isHeading(element) && !element.hasAttribute('id')) {
          addId(element);
        }
      }

      function isHeading(element) {
        return element.is('h1', 'h2', 'h3', 'h4', 'h5', 'h6');
      }

      function checkPastedContentForHeadings(ev) {
        var pastedContent = ev.data.dataValue,
          pastedContentAsHtml = CKEDITOR.htmlParser.fragment.fromHtml(pastedContent),
          pastedElements = pastedContentAsHtml.children,
          writer = new CKEDITOR.htmlParser.basicWriter(),
          i, element, id, originalHeading;

        for (i = 0; i < pastedElements.length; i++) {
          element = pastedElements[i];
          if (element.type === CKEDITOR.NODE_ELEMENT) {
            id = element.attributes.id;
            originalHeading = checkForDuplicateId(id);
            if (originalHeading) {
              element = resolveDuplicateIds(element, originalHeading);
            }
          }
        }

        pastedContentAsHtml.writeHtml(writer);
        ev.data.dataValue = writer.getHtml();
      }

      function checkForDuplicateId(id) {
        var headingIds = findHeadingIds(findAllHeadings()),
          i, headingId, originalHeading;

        for (i = 0; i < headingIds.length; i++) {
          headingId = headingIds[i];
          if (id === headingId) {
            return originalHeading = editor.document.getById(headingId);
          }
        }
      }

      function resolveDuplicateIds(newHeading, originalHeading) {
        var newHeadingText = newHeading.children[0].value,
          originalHeadingText = originalHeading.getText();

        // if the original heading has no content (blank or just a line-feed
        // character is left when all the content is cut), the original heading
        // will be removed and the new heading will retain the id
        if ( originalHeadingText.length <= 1 && notWordCharacter(originalHeadingText.charAt(0))) {
          originalHeading.remove();
          editor.fire(EVENT_NAMES.ID_RETAINED);
          return newHeading;
        }

        // if the original heading text is not blank, the original should retain its
        // id and the new heading should get a new one.
        if (originalHeadingText) {
          newHeading.attributes.id = CKEDITOR.tools.getUniqueId();
          editor.fire(EVENT_NAMES.ID_ADDED);
          return newHeading;
        }

      }

      function notWordCharacter(character) {
        if (!character)
          return true;

        return !(/\w/.test(character));
      }

      // This modifies the dialog for the 'link' plugin to allow the option of
      // internal document linking to autoid headings. Original 'link' plugin
      // code can be found at:
      // https://github.com/ckeditor/ckeditor-dev/tree/master/plugins/link

      function modifyLinkDialog(ev) {
        var dialog = ev.data;

        if (dialog.name == 'link') {
          var def = ev.data.definition,
            infoTab = def.contents[0],
            linkTypeTab = infoTab.elements[1];

          // Add option for heading links to linkType dropdown
          linkTypeTab.items.push(['Link to heading in the text', 'heading']);

          // Modify linkType's 'onChange' function to accomodate new heading option
          linkTypeTab.onChange = modifiedLinkTypeChanged;
        }
      }

      function modifiedLinkTypeChanged() {
        var dialog = this.getDialog(),
          partIds = [ 'urlOptions', 'anchorOptions', 'emailOptions', 'headingOptions' ],
          typeValue = this.getValue(),
          uploadTab = dialog.definition.getContents( 'upload' ),
          uploadInitiallyHidden = uploadTab && uploadTab.hidden;

        if ( typeValue == 'url' ) {
          if ( editor.config.linkShowTargetTab )
            dialog.showPage( 'target' );
          if ( !uploadInitiallyHidden )
            dialog.showPage( 'upload' );
          } else {
            dialog.hidePage( 'target' );
          if ( !uploadInitiallyHidden )
            dialog.hidePage( 'upload' );
        }

        for ( var i = 0; i < partIds.length; i++ ) {
          var element = dialog.getContentElement( 'info', partIds[ i ] );
          if ( !element )
            continue;

          element = element.getElement().getParent().getParent();
          if ( partIds[ i ] == typeValue + 'Options' )
            element.show();
          else
            element.hide();
        }

        dialog.layout();
      }

    }
  });
})();
<|endoftext|>


<commit_before>var templates = [
    "root/externallib/text!root/plugins/contents/sections.html",
    "root/externallib/text!root/plugins/contents/contents.html",
    "root/externallib/text!root/plugins/contents/folder.html",
    "root/externallib/text!root/plugins/contents/mimetypes.json"
];

define(templates,function (sectionsTpl, contentsTpl, folderTpl, mimeTypes) {
    var plugin = {
        settings: {
            name: "contents",
            type: "course",
            menuURL: "#course/contents/",
            lang: {
                component: "core"
            }
        },

        storage: {
            content: {type: "model"},
            contents: {type: "collection", model: "content"}
        },

        routes: [
            ["course/contents/:courseid", "course_contents", "viewCourseContents"],
            ["course/contents/:courseid/section/:sectionId", "course_contents_section", "viewCourseContentsSection"],
            ["course/contents/:courseid/section/:sectionId/folder/:contentid", "course_contents_folder", "viewFolder"],
            ["course/contents/:courseid/section/:sectionId/download/:contentid", "course_contents_download", "downloadContent"],
            ["course/contents/:courseid/section/:sectionId/info/:contentid", "course_contents_info", "infoContent"],
            ["course/contents/:courseid/section/:sectionId/download/:contentid/:index", "course_contents_download_folder", "downloadContent"],
            ["course/contents/:courseid/section/:sectionId/info/:contentid/:index", "course_contents_info_folder", "infoContent"],
        ],

        viewCourseContents: function(courseId) {

            MM.panels.showLoading('center');

            if (MM.deviceType == "tablet") {
                MM.panels.showLoading('right');
            }

            var data = {
            "options[0][name]" : "",
            "options[0][value]" : ""
            };
            data.courseid = courseId;

            MM.moodleWSCall('core_course_get_contents', data, function(contents) {
                var course = MM.db.get("courses", MM.config.current_site.id + "-" + courseId);

                var tpl = {
                    sections: contents,
                    course: course.toJSON() // Convert a model to a plain javascript object.
                }
                var html = MM.tpl.render(MM.plugins.contents.templates.sections.html, tpl);
                MM.panels.show("center", html);
                if (MM.deviceType == "tablet" && contents.length > 0) {
                    // First section.
                    MM.plugins.contents.viewCourseContentsSection(courseId, 0);
                }
            });
        },

        viewCourseContentsSection: function(courseId, sectionId) {

            if (MM.deviceType == "tablet") {
                MM.panels.showLoading('right');
            }

            var data = {
            "options[0][name]" : "",
            "options[0][value]" : ""
            };
            data.courseid = courseId;

            MM.moodleWSCall('core_course_get_contents', data, function(contents) {
                var course = MM.db.get("courses", MM.config.current_site.id + "-" + courseId);
                var courseName = course.get("fullname");

                var firstContent = 0;

				var contentsStored = [];
				MM.db.each("contents", function(el){
					contentsStored.push(el.get("id"));
				});

                var finalContents = [];
				$.each(JSON.parse(JSON.stringify(contents)), function(index1, sections){

                    // Skip sections deleting contents..
                    if (sectionId > -1 && sectionId != index1) {
                        // This is a continue.
                        return true;
                    }

                    $.each(sections.modules, function(index2, content){

                        content.contentid = content.id;
                        content.courseid = courseId;
                        content.id = MM.config.current_site.id + "-" + content.contentid;

                        if(!firstContent) {
                            firstContent = content.contentid;
                        }

                        // This content is currently in the database.
                        if (contentsStored.indexOf(content.id) > -1) {
                            var c = MM.db.get("contents", content.id);
                            c = c.toJSON();
                            sections.modules[index2].mainExtension = c.mainExtension;
                            sections.modules[index2].webOnly = c.webOnly;

                            if (!sections.modules[index2].webOnly) {
                                var downloaded = false;
                                if (content.modname != "folder") {
                                    downloaded = typeof(c.contents[0].localpath) != "undefined";
                                } else {
                                    downloaded = true;
                                    $.each(c.contents, function (index5, filep) {
                                        if (typeof(filep.localpath) == "undefined") {
                                            downloaded = false;
                                        }
                                    });
                                }
                                sections.modules[index2].downloaded = downloaded;
                            }

                            return true; // This is a continue;
                        }

                        // The mod url also exports contents but are external contents not downloadable by the app.
                        var modContents = ["folder","page","resource"];

                        if (modContents.indexOf(content.modname) == -1) {
                            content.webOnly = true;
                        } else {
                            content.webOnly = false;
                        }
                        sections.modules[index2].webOnly = content.webOnly;

                        MM.db.insert("contents", content);

                        // Sync content files.

                        if (typeof(content.contents) != "undefined") {
                            $.each(content.contents, function (index3, file) {

                                if (file.fileurl.indexOf(MM.config.current_site.siteurl) == -1) {
                                	return true;
                                }

                                var paths = MM.plugins.contents.getLocalPaths(courseId, content.contentid, file);

                                var el = {
                                    id: hex_md5(MM.config.current_site.id + file.fileurl),
                                    url: file.fileurl,
                                    path: paths.directory,
                                    newfile: paths.file,
                                    contentid: content.id,
                                    index: index3,
                                    syncData: {
                                        name: MM.lang.s("content") + ": " + courseName + ": " + content.name,
                                        description: file.fileurl
                                    },
                                    siteid: MM.config.current_site.id,
                                    type: "content"
                                   };

                                // Disabled auto sync temporaly
                                //MM.log("Sync: Adding content: " + el.syncData.name + ": " + el.url);
                                //MM.db.insert("sync", el);

                                var extension = file.filename.substr(file.filename.lastIndexOf(".") + 1);

                                // Exception for folder type, we use the resource icon.
                                if (content.modname != "folder" && typeof(MM.plugins.contents.templates.mimetypes[extension]) != "undefined") {
                                    sections.modules[index2].mainExtension = MM.plugins.contents.templates.mimetypes[extension]["icon"];
                                    content.mainExtension = sections.modules[index2].mainExtension;
                                    MM.db.insert("contents", content);
                                }
                            });
                        }
                    });

                    finalContents.push(sections);

                });

                var tpl = {
                    sections: finalContents,
                    sectionId: sectionId,
                    courseId: courseId,
                    course: course.toJSON() // Convert a model to a plain javascript object.
                }
                var html = MM.tpl.render(MM.plugins.contents.templates.contents.html, tpl);
                $('#panel-right').css('width', $(document).innerWidth());
                MM.panels.show('right', html);
                // Ugly fix - See MOBILE-201
                $('#panel-right .content-index').css('width', $(document).innerWidth() - 5);
                setTimeout(function() { $('#panel-right').css('padding-right', '49px'); }, 500);

            });
        },

        downloadContent: function(courseId, sectionId, contentId, index) {

            var content = MM.db.get("contents", MM.config.current_site.id + "-" + contentId);
            content = content.toJSON();

            var downCssId = "#download-" + contentId;
            var linkCssId = "#link-" + contentId;

            if (typeof(index) != "undefined") {
                downCssId = "#download-" + contentId + "-" + index;
                linkCssId = "#link-" + contentId + "-" + index;
            } else {
                index = 0;
            }

            var file = content.contents[index];
            var downloadURL = file.fileurl + "&token=" + MM.config.current_token;

            // Now, we need to download the file.
            // First we load the file system (is not loaded yet).
            MM.fs.init(function() {
                var path = MM.plugins.contents.getLocalPaths(courseId, contentId, file);
                MM.log("Content: Starting download of file: " + downloadURL);
                // All the functions are async, like create dir.
                MM.fs.createDir(path.directory, function() {
                    MM.log("Content: Downloading content to " + path.file + " from URL: " + downloadURL);

                    $(downCssId).attr("src", "img/loading.gif");

                    MM.moodleDownloadFile(downloadURL, path.file,
                        function() {
                            MM.log("Content: Download of content finished " + path.file + " URL: " + downloadURL);
                            content.contents[index].localpath = path.file;
                            MM.db.insert("contents", content);
                            $(downCssId).remove();
                            $(linkCssId).attr("href", MM.fs.getRoot() + "/" + path.file);
                        },
                        function() {
                           MM.log("Content: Error downloading " + path.file + " URL: " + fileurl);
                           $(downCssId).attr("src", "img/download.png");
                         });
                });
            });
        },

        viewFolder: function(courseId, sectionId, contentId) {

            var course = MM.db.get("courses", MM.config.current_site.id + "-" + courseId);
            var content = MM.db.get("contents", MM.config.current_site.id + "-" + contentId);
            content = content.toJSON();

            var data = {
            "options[0][name]" : "",
            "options[0][value]" : ""
            };
            data.courseid = courseId;

            var sectionName = "";
            // Now, we found the section of the content, sectionId may be -1 if we are watching all the contents so it's not a valid clue.
            // Notice that we will retrieve the info from cache.
            MM.moodleWSCall('core_course_get_contents', data, function(sections) {
                $.each(sections, function(index, section) {
                    $.each(section.modules, function(index2, module) {
                        if (module.id == contentId) {
                            sectionName = section.name;
                            return false;
                        }
                    });
                    if (sectionName) {
                        return false;
                    }
                });
            });

            var tpl = {
                    course: course,
                    sectionId: sectionId,
                    courseId: courseId,
                    contentId: contentId,
                    content: content,
                    sectionName: sectionName
                }

            var html = MM.tpl.render(MM.plugins.contents.templates.folder.html, tpl);
            MM.panels.html('right', html);

        },

        infoContent: function(courseId, sectionId, contentId, index) {

            var content = MM.db.get("contents", MM.config.current_site.id + "-" + contentId);
            content = content.toJSON();

            if (typeof(MM.plugins.contents.infoBox) != "undefined") {
                MM.plugins.contents.infoBox.remove();
            }

            var skipFiles = false;

            if (typeof(index) != "undefined") {
                var i = $("#info-" + contentId + "-" + index).offset();
            } else {
                var i = $("#info-" + contentId).offset();
                index = 0;
                if (content.modname == "folder") {
                    skipFiles = true;
                }
            }

            if (typeof(content.contents) == "undefined" || !content.contents[index]) {
                skipFiles = true;
            }

            var information = '
'+content.name+'
';
            if (typeof(content.description) != "undefined") {
                information += '
'+content.description+'
';
            }

            if (! skipFiles) {
                var file = content.contents[index];

                var fileParams = ["author", "license", "timecreated", "timemodified", "filesize"];
                for (var el in fileParams) {
                    var param = fileParams[el];
                    if (typeof(file[param]) != "undefined") {
                        information += MM.lang.s(param)+': ';

                        var value = file[param];

                        switch(param) {
                            case "timecreated":
                            case "timemodified":
                                var d = new Date(value * 1000);
                                value = d.toLocaleString();
                                break;
                            case "filesize":
                                value = file[param] / 1024;
                                // Round to 2 decimals.
                                value = Math.round(value*100)/100 + " kb"
                                break;
                            default:
                                value = file[param];
                        }

                        information += value + '
';
                    }
                }
            }

            information += '
' + MM.lang.s("viewableonthisapp") + ': ';

            if (content.webOnly) {
                information += MM.lang.s("no");
            } else {
                information += MM.lang.s("yes");
            }
            information += "
";

            information += '
'+content.url+'
';

            MM.plugins.contents.infoBox = $('

'+information+'

').addClass("arrow_box");
            $('body').append(MM.plugins.contents.infoBox);

            var width = $("#panel-right").width() / 2;
            $('#infobox-'+contentId).css("top", i.top - 30).css("left", i.left - width - 35).width(width);

            $("a").click(function(e) {
                if (typeof(MM.plugins.contents.infoBox) != "undefined") {
                    MM.plugins.contents.infoBox.remove();
                }
            });

        },

        getLocalPaths: function(courseId, modId, file) {

            var filename = file.fileurl.replace("?forcedownload=1", "");
            filename = filename.substr(filename.lastIndexOf("/") + 1);
            // We store in the sdcard the contents in site/course/modname/id/contentIndex/filename
            var path = MM.config.current_site.id + "/" + courseId + "/" + modId;

            var newfile = path + "/" + filename;

            return {
                directory: path,
                file: newfile
            }
        },

        templates: {
            "folder": {
                html: folderTpl
            },
            "contents": {
                html: contentsTpl
            },
            "sections": {
                html: sectionsTpl
            },
            "mimetypes": JSON.parse(mimeTypes)
        }
    }

    MM.registerPlugin(plugin);
});<commit_msg>MOBILE-201 Reverting some changes<commit_after>var templates = [
    "root/externallib/text!root/plugins/contents/sections.html",
    "root/externallib/text!root/plugins/contents/contents.html",
    "root/externallib/text!root/plugins/contents/folder.html",
    "root/externallib/text!root/plugins/contents/mimetypes.json"
];

define(templates,function (sectionsTpl, contentsTpl, folderTpl, mimeTypes) {
    var plugin = {
        settings: {
            name: "contents",
            type: "course",
            menuURL: "#course/contents/",
            lang: {
                component: "core"
            }
        },

        storage: {
            content: {type: "model"},
            contents: {type: "collection", model: "content"}
        },

        routes: [
            ["course/contents/:courseid", "course_contents", "viewCourseContents"],
            ["course/contents/:courseid/section/:sectionId", "course_contents_section", "viewCourseContentsSection"],
            ["course/contents/:courseid/section/:sectionId/folder/:contentid", "course_contents_folder", "viewFolder"],
            ["course/contents/:courseid/section/:sectionId/download/:contentid", "course_contents_download", "downloadContent"],
            ["course/contents/:courseid/section/:sectionId/info/:contentid", "course_contents_info", "infoContent"],
            ["course/contents/:courseid/section/:sectionId/download/:contentid/:index", "course_contents_download_folder", "downloadContent"],
            ["course/contents/:courseid/section/:sectionId/info/:contentid/:index", "course_contents_info_folder", "infoContent"],
        ],

        viewCourseContents: function(courseId) {

            MM.panels.showLoading('center');

            if (MM.deviceType == "tablet") {
                MM.panels.showLoading('right');
            }

            var data = {
            "options[0][name]" : "",
            "options[0][value]" : ""
            };
            data.courseid = courseId;

            MM.moodleWSCall('core_course_get_contents', data, function(contents) {
                var course = MM.db.get("courses", MM.config.current_site.id + "-" + courseId);

                var tpl = {
                    sections: contents,
                    course: course.toJSON() // Convert a model to a plain javascript object.
                }
                var html = MM.tpl.render(MM.plugins.contents.templates.sections.html, tpl);
                MM.panels.show("center", html);
                if (MM.deviceType == "tablet" && contents.length > 0) {
                    // First section.
                    MM.plugins.contents.viewCourseContentsSection(courseId, 0);
                }
            });
        },

        viewCourseContentsSection: function(courseId, sectionId) {

            if (MM.deviceType == "tablet") {
                MM.panels.showLoading('right');
            }

            var data = {
            "options[0][name]" : "",
            "options[0][value]" : ""
            };
            data.courseid = courseId;

            MM.moodleWSCall('core_course_get_contents', data, function(contents) {
                var course = MM.db.get("courses", MM.config.current_site.id + "-" + courseId);
                var courseName = course.get("fullname");

                var firstContent = 0;

				var contentsStored = [];
				MM.db.each("contents", function(el){
					contentsStored.push(el.get("id"));
				});

                var finalContents = [];
				$.each(JSON.parse(JSON.stringify(contents)), function(index1, sections){

                    // Skip sections deleting contents..
                    if (sectionId > -1 && sectionId != index1) {
                        // This is a continue.
                        return true;
                    }

                    $.each(sections.modules, function(index2, content){

                        content.contentid = content.id;
                        content.courseid = courseId;
                        content.id = MM.config.current_site.id + "-" + content.contentid;

                        if(!firstContent) {
                            firstContent = content.contentid;
                        }

                        // This content is currently in the database.
                        if (contentsStored.indexOf(content.id) > -1) {
                            var c = MM.db.get("contents", content.id);
                            c = c.toJSON();
                            sections.modules[index2].mainExtension = c.mainExtension;
                            sections.modules[index2].webOnly = c.webOnly;

                            if (!sections.modules[index2].webOnly) {
                                var downloaded = false;
                                if (content.modname != "folder") {
                                    downloaded = typeof(c.contents[0].localpath) != "undefined";
                                } else {
                                    downloaded = true;
                                    $.each(c.contents, function (index5, filep) {
                                        if (typeof(filep.localpath) == "undefined") {
                                            downloaded = false;
                                        }
                                    });
                                }
                                sections.modules[index2].downloaded = downloaded;
                            }

                            return true; // This is a continue;
                        }

                        // The mod url also exports contents but are external contents not downloadable by the app.
                        var modContents = ["folder","page","resource"];

                        if (modContents.indexOf(content.modname) == -1) {
                            content.webOnly = true;
                        } else {
                            content.webOnly = false;
                        }
                        sections.modules[index2].webOnly = content.webOnly;

                        MM.db.insert("contents", content);

                        // Sync content files.

                        if (typeof(content.contents) != "undefined") {
                            $.each(content.contents, function (index3, file) {

                                if (file.fileurl.indexOf(MM.config.current_site.siteurl) == -1) {
                                	return true;
                                }

                                var paths = MM.plugins.contents.getLocalPaths(courseId, content.contentid, file);

                                var el = {
                                    id: hex_md5(MM.config.current_site.id + file.fileurl),
                                    url: file.fileurl,
                                    path: paths.directory,
                                    newfile: paths.file,
                                    contentid: content.id,
                                    index: index3,
                                    syncData: {
                                        name: MM.lang.s("content") + ": " + courseName + ": " + content.name,
                                        description: file.fileurl
                                    },
                                    siteid: MM.config.current_site.id,
                                    type: "content"
                                   };

                                // Disabled auto sync temporaly
                                //MM.log("Sync: Adding content: " + el.syncData.name + ": " + el.url);
                                //MM.db.insert("sync", el);

                                var extension = file.filename.substr(file.filename.lastIndexOf(".") + 1);

                                // Exception for folder type, we use the resource icon.
                                if (content.modname != "folder" && typeof(MM.plugins.contents.templates.mimetypes[extension]) != "undefined") {
                                    sections.modules[index2].mainExtension = MM.plugins.contents.templates.mimetypes[extension]["icon"];
                                    content.mainExtension = sections.modules[index2].mainExtension;
                                    MM.db.insert("contents", content);
                                }
                            });
                        }
                    });

                    finalContents.push(sections);

                });

                var tpl = {
                    sections: finalContents,
                    sectionId: sectionId,
                    courseId: courseId,
                    course: course.toJSON() // Convert a model to a plain javascript object.
                }
                var html = MM.tpl.render(MM.plugins.contents.templates.contents.html, tpl);
                MM.panels.show('right', html);
            });
        },

        downloadContent: function(courseId, sectionId, contentId, index) {

            var content = MM.db.get("contents", MM.config.current_site.id + "-" + contentId);
            content = content.toJSON();

            var downCssId = "#download-" + contentId;
            var linkCssId = "#link-" + contentId;

            if (typeof(index) != "undefined") {
                downCssId = "#download-" + contentId + "-" + index;
                linkCssId = "#link-" + contentId + "-" + index;
            } else {
                index = 0;
            }

            var file = content.contents[index];
            var downloadURL = file.fileurl + "&token=" + MM.config.current_token;

            // Now, we need to download the file.
            // First we load the file system (is not loaded yet).
            MM.fs.init(function() {
                var path = MM.plugins.contents.getLocalPaths(courseId, contentId, file);
                MM.log("Content: Starting download of file: " + downloadURL);
                // All the functions are async, like create dir.
                MM.fs.createDir(path.directory, function() {
                    MM.log("Content: Downloading content to " + path.file + " from URL: " + downloadURL);

                    $(downCssId).attr("src", "img/loading.gif");

                    MM.moodleDownloadFile(downloadURL, path.file,
                        function() {
                            MM.log("Content: Download of content finished " + path.file + " URL: " + downloadURL);
                            content.contents[index].localpath = path.file;
                            MM.db.insert("contents", content);
                            $(downCssId).remove();
                            $(linkCssId).attr("href", MM.fs.getRoot() + "/" + path.file);
                        },
                        function() {
                           MM.log("Content: Error downloading " + path.file + " URL: " + fileurl);
                           $(downCssId).attr("src", "img/download.png");
                         });
                });
            });
        },

        viewFolder: function(courseId, sectionId, contentId) {

            var course = MM.db.get("courses", MM.config.current_site.id + "-" + courseId);
            var content = MM.db.get("contents", MM.config.current_site.id + "-" + contentId);
            content = content.toJSON();

            var data = {
            "options[0][name]" : "",
            "options[0][value]" : ""
            };
            data.courseid = courseId;

            var sectionName = "";
            // Now, we found the section of the content, sectionId may be -1 if we are watching all the contents so it's not a valid clue.
            // Notice that we will retrieve the info from cache.
            MM.moodleWSCall('core_course_get_contents', data, function(sections) {
                $.each(sections, function(index, section) {
                    $.each(section.modules, function(index2, module) {
                        if (module.id == contentId) {
                            sectionName = section.name;
                            return false;
                        }
                    });
                    if (sectionName) {
                        return false;
                    }
                });
            });

            var tpl = {
                    course: course,
                    sectionId: sectionId,
                    courseId: courseId,
                    contentId: contentId,
                    content: content,
                    sectionName: sectionName
                }

            var html = MM.tpl.render(MM.plugins.contents.templates.folder.html, tpl);
            MM.panels.html('right', html);

        },

        infoContent: function(courseId, sectionId, contentId, index) {

            var content = MM.db.get("contents", MM.config.current_site.id + "-" + contentId);
            content = content.toJSON();

            if (typeof(MM.plugins.contents.infoBox) != "undefined") {
                MM.plugins.contents.infoBox.remove();
            }

            var skipFiles = false;

            if (typeof(index) != "undefined") {
                var i = $("#info-" + contentId + "-" + index).offset();
            } else {
                var i = $("#info-" + contentId).offset();
                index = 0;
                if (content.modname == "folder") {
                    skipFiles = true;
                }
            }

            if (typeof(content.contents) == "undefined" || !content.contents[index]) {
                skipFiles = true;
            }

            var information = '
'+content.name+'
';
            if (typeof(content.description) != "undefined") {
                information += '
'+content.description+'
';
            }

            if (! skipFiles) {
                var file = content.contents[index];

                var fileParams = ["author", "license", "timecreated", "timemodified", "filesize"];
                for (var el in fileParams) {
                    var param = fileParams[el];
                    if (typeof(file[param]) != "undefined") {
                        information += MM.lang.s(param)+': ';

                        var value = file[param];

                        switch(param) {
                            case "timecreated":
                            case "timemodified":
                                var d = new Date(value * 1000);
                                value = d.toLocaleString();
                                break;
                            case "filesize":
                                value = file[param] / 1024;
                                // Round to 2 decimals.
                                value = Math.round(value*100)/100 + " kb"
                                break;
                            default:
                                value = file[param];
                        }

                        information += value + '
';
                    }
                }
            }

            information += '
' + MM.lang.s("viewableonthisapp") + ': ';

            if (content.webOnly) {
                information += MM.lang.s("no");
            } else {
                information += MM.lang.s("yes");
            }
            information += "
";

            information += '
'+content.url+'
';

            MM.plugins.contents.infoBox = $('

'+information+'

').addClass("arrow_box");
            $('body').append(MM.plugins.contents.infoBox);

            var width = $("#panel-right").width() / 2;
            $('#infobox-'+contentId).css("top", i.top - 30).css("left", i.left - width - 35).width(width);

            $("a").click(function(e) {
                if (typeof(MM.plugins.contents.infoBox) != "undefined") {
                    MM.plugins.contents.infoBox.remove();
                }
            });

        },

        getLocalPaths: function(courseId, modId, file) {

            var filename = file.fileurl.replace("?forcedownload=1", "");
            filename = filename.substr(filename.lastIndexOf("/") + 1);
            // We store in the sdcard the contents in site/course/modname/id/contentIndex/filename
            var path = MM.config.current_site.id + "/" + courseId + "/" + modId;

            var newfile = path + "/" + filename;

            return {
                directory: path,
                file: newfile
            }
        },

        templates: {
            "folder": {
                html: folderTpl
            },
            "contents": {
                html: contentsTpl
            },
            "sections": {
                html: sectionsTpl
            },
            "mimetypes": JSON.parse(mimeTypes)
        }
    }

    MM.registerPlugin(plugin);
});<|endoftext|>