<commit_before>/* ***** BEGIN LICENSE BLOCK *****
* Licensed under Version: MPL 1.1/GPL 2.0/LGPL 2.1
* Full Terms at http://mozile.mozdev.org/license.html
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Playsophy code.
*
* The Initial Developer of the Original Code is Playsophy
* Portions created by the Initial Developer are Copyright (C) 2002-2003
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */

const BXE_VERSION = "0.1alpha";
const BXE_BUILD = "200309250330"

var DebugOutput = true;

mozile_js_files = new Array();

mozile_js_files.push("mozile/mozWrappers.js");
mozile_js_files.push("js/widget.js");

mozile_js_files.push("mozile/eDOM.js");
mozile_js_files.push("js/bxeConfig.js");
mozile_js_files.push("mozile/eDOMXHTML.js");
mozile_js_files.push("js/bxeXMLNode.js");
mozile_js_files.push("js/bxeNodeElements.js");
mozile_js_files.push("js/bxeXMLDocument.js");
mozile_js_files.push("mozile/mozileTransportDriver.js");
mozile_js_files.push("mozile/td/http.js");
mozile_js_files.push("mozile/domlevel3.js");
mozile_js_files.push("mozile/mozCE.js");
mozile_js_files.push("mozile/mozIECE.js");
//mozile_js_files.push("mozile/mozileModify.js");
mozile_js_files.push("js/eDOMEvents.js");
mozile_js_files.push("js/bxeFunctions.js");

var mozile_root_dir = "./";

// some global vars, no need to change them
var mozile_corescript_loaded = 0;
var mozile_script_loaded = 0;
var bxe_config = new Object();
var bxe_about_box = null;
var bxe_format_list = null;
var bxe_context_menu = null;
var bxe_delayedUpdate = false;
var eDOM_bxe_mode = true;

function bxe_start(config_file,fromUrl, configArray) {

	/*if (! (BX_checkUnsupportedBrowsers())) {
		return false;
	}*/

	if((navigator.product == 'Gecko') && (navigator.userAgent.indexOf("Safari") == -1))
	{
		// navigator.productSub > '20020801' (test to see what the date should be)

		// POST04: if document.documentElement != HTML then ... or no "head" ...
		var head = document.getElementsByTagName("head")[0];
		bxe_config.file = config_file;
		bxe_config.fromUrl = fromUrl;
		bxe_config.configArray = configArray;
		if(head)
		{
			// get the location of this script and reuse it for the others
			for(var i=0; i<head.childNodes.length; i++)
			{
				var mozileLoaderRE = /(.*)bxeLoader.js$/;
				if(head.childNodes[i].localName == "SCRIPT")
				{
					var src = head.childNodes[i].src;
					var result = mozileLoaderRE.exec(src);
					if(result)
					{
						mozile_root_dir = result[1];
						break;
					}
				}
			}
			for (var i=0; i < mozile_js_files.length; i++)
			{
				var scr = document.createElementNS("http://www.w3.org/1999/xhtml","script");
				var src = mozile_root_dir + mozile_js_files[i];
				if (mozile_js_files[i] == "js/widget.js") {
					scr.onload = widget_loaded;
				} else {
					scr.onload = corescript_loaded;
				}
				scr.setAttribute("src", src);

				scr.setAttribute("language","JavaScript");
				head.appendChild(scr);
			}
			//when last include src is loaded, call onload handler

		}
		else {
			alert("*** ALERT: MozileLoader only works in XHTML - load Mozile JS explicitly in XML files");
		}
	}

}

// Detect Gecko but exclude Safari (for now); for now, only support XHTML

function bxe_load_xml (xmlfile) {

	var td = new mozileTransportDriver("webdav");
	function callback (e) {
		if (e.isError) {
			alert("Error loading xml file \n"+e.statusText);
			return false;
		}
		var xmldoc =  e.document;
		bxe_config.xmldoc = xmldoc;
		xmldoc.init();
		if (bxe_config.xhtmlfile) {
			xmldoc.importXHTMLDocument(bxe_config.xhtmlfile)
		} else if (bxe_config.xslfile) {
			xmldoc.transformToXPathMode(bxe_config.xslfile)
		} else {
			xmldoc.insertIntoHTMLDocument();
			xml_loaded(xmldoc);
		}

	}
	td.load(xmlfile,callback);

	return true;
}

function widget_loaded(e) {
	bxe_about_box = new Widget_AboutBox();
	bxe_about_box.draw();
	bxe_about_box.setText("Loading files ...");
	corescript_loaded(e);

}

function corescript_loaded(e) {
	mozile_corescript_loaded++;
	debug("from core script " + mozile_corescript_loaded + " of " + mozile_js_files.length  + "loaded: " + e.currentTarget.src);
	if ( mozile_js_files.length == mozile_corescript_loaded) {
		debug("call mozile_core_loaded()");
		mozile_core_loaded();
	} else {
		if (bxe_about_box) {
			bxe_about_box.addText(mozile_corescript_loaded );
		}
	}
}

function script_loaded(e) {
	mozile_script_loaded++;
	debug("from config script " + mozile_script_loaded + " loaded: " + e.currentTarget.src );
	if ( bxe_config.scriptfiles.length == mozile_script_loaded ) {
		debug("call mozile_loaded()");
		mozile_loaded();
	} else {
		bxe_about_box.addText(mozile_script_loaded );
	}
}

function mozile_core_loaded() {
	bxe_about_box.addText("Scripts loaded ...");
	bxe_about_box.addText("Load Config ");
	try {
		bxe_config = new bxeConfig(bxe_config.file, bxe_config.fromUrl, bxe_config.configArray);
	} catch (e) {
		bxe_catch_alert(e);
	}
}

function mozile_loaded() {
	bxe_about_box.addText("Load XML ...");
	bxe_load_xml(bxe_config.xmlfile);

}

function xml_loaded(xmldoc) {
	bxe_about_box.addText("Load RelaxNG ...");
	if (!(bxe_config.validationfile && xmldoc.XMLNode.loadSchema(bxe_config.validationfile,validation_loaded))) {
		bxe_about_box.addText("RelaxNG File was not found");
	}
	document.eDOMaddEventListener("toggleSourceMode",bxe_toggleSourceMode,false);
	document.eDOMaddEventListener("toggleTagMode",bxe_toggleTagMode,false);
	document.eDOMaddEventListener("toggleNormalMode",bxe_toggleNormalMode,false);
	document.eDOMaddEventListener("DocumentSave",__bxeSave,false);
	document.eDOMaddEventListener("ToggleTextClass",bxe_toggleTextClass,false);
	document.eDOMaddEventListener("appendNode",bxe_appendNode,false);
	document.eDOMaddEventListener("InsertLink",bxe_InsertLink,false);
	document.eDOMaddEventListener("InsertTable",bxe_InsertTable,false);
	document.eDOMaddEventListener("InsertImage",bxe_InsertImage,false);
	document.eDOMaddEventListener("OrderedList",bxe_OrderedList,false);
	document.eDOMaddEventListener("UnorderedList",bxe_UnorderedList,false);

	document.eDOMaddEventListener("changeLinesContainer",bxe_changeLinesContainer,false);
	document.eDOMaddEventListener("Exit",bxe_exit,false);

	document.eDOMaddEventListener("ClipboardCopy",function(e) { window.getSelection().copy()},false);
	document.eDOMaddEventListener("ClipboardPaste",function(e) { window.getSelection().paste()},false);
	document.eDOMaddEventListener("ClipboardCut",function(e) { window.getSelection().cut()},false);

	document.eDOMaddEventListener("Undo",function(e) { bxe_not_yet_implemented()}, false);
	document.eDOMaddEventListener("Redo",function(e) { bxe_not_yet_implemented()}, false);

	document.addEventListener("contextmenu",bxe_ContextMenuEvent, false);

	//document.eDOMaddEventListener("NodeInsertedParent",bxe_NodeInsertedParent, false);
	document.eDOMaddEventListener("NodeInsertedBefore",bxe_NodeInsertedBefore,false);
	document.eDOMaddEventListener("NodeBeforeDelete",bxe_NodeBeforeDelete,false);
	/*document.eDOMaddEventListener("NodeChanged",bxe_NodeChanged,false);

	document.eDOMaddEventListener("NodeRemovedChildOnly",bxe_NodeRemovedChildOnly,false);
	*/
	//document.eDOMaddEventListener("NodeAppendedChild",bxe_NodeAppendedChild,false);
	document.eDOMaddEventListener("NodePositionChanged",bxe_NodePositionChanged,false);

	document.eDOMaddEventListener("ContextPopup",bxe_ContextPopup,false);
	bxe_context_menu = new Widget_ContextMenu();
}

function validation_loaded(vdom) {
	bxe_about_box.addText("Validation Loaded ...");

	var vali = bxe_config.xmldoc.XMLNode.validateDocument();
	if (vali.isError) {
		bxe_about_box.addText("Document is *not* valid.");
		//alert(vali.getErrorMessagesAsText());
	}
	else {
		bxe_about_box.addText("Document is valid.");

	}
}

function config_loaded(bxe_config_in) {
	bxe_about_box.addText("& Parsed ...");

	bxe_config = bxe_config_in;
	var head = document.getElementsByTagName("head")[0];
	for (var i=0; i < bxe_config.cssfiles.length; i++)
	{
		var scr = document.createElementNS(XHTMLNS,"link");
		scr.setAttribute("type","text/css");
		scr.setAttribute("rel","stylesheet");
		scr.setAttribute("href",bxe_config.cssfiles[i]);
		head.appendChild(scr);
	}

	for (var i=0; i < bxe_config.scriptfiles.length; i++)
	{
		var scr = document.createElementNS("http://www.w3.org/1999/xhtml","script");
		var src = mozile_root_dir + bxe_config.scriptfiles[i];
		scr.onload = script_loaded;
		scr.setAttribute("src", src);
		scr.setAttribute("language","JavaScript");
		head.appendChild(scr);
	}

}

debug = function (text, options) {

	if (DebugOutput) {

		fn =  bxe_getCaller(debug);

		dump( fn.getName() +  ": " + text + "\n");
		if (options) {

			if (options.evalArguments) {
				var fname= fn.getName();
					dump("  Arguments: (");
					for (var i = 0; i < fn.arguments.length; i++) {
						dump("[" + typeof fn.arguments[i] + "] ");
						switch( typeof( fn.arguments[i] )) {
							case "function":
								dump (fn.arguments[i].getName());
								break;
							case "string":
								dump('"' + fn.arguments[i] + '"');
								break;
							default:
								dump(fn.arguments[i]);
						}
						if (i < fn.arguments.length - 1 ) {
							dump(", ");
						}
					}
					dump (")\n");

			}

			if (options.callstack) {
				var callstack =  new Array();
				dump ("  Callstack: \n");
				dump ("  ----------\n");
				while (fn) {

					callstack.unshift(fn.getName() + "\n");
					var newfn = JsUtil_getCaller(fn);
					if (fn == newfn) {
						callstack.unshift ("  [javascript recursion]\n");
						break;
					}
					fn = newfn;
				}
				for (var i = 0; i < callstack.length; i++) {
					dump("  " +i +": " +callstack[i]);
				}
				dump ("  ----------\n");

			}

		}

	}
}

Function.prototype.getName = function () {
	var r = /function (\w*)([^\{\}]*\))/
	var s = new String( this);
	var m = s.match( r );
	if (m) {
		var f = "";
		if (m[1]) {
			f = m[1];
		} else {
			r = /var id = "(.+)"/;
			var n = s.match(r);
			if (n && n[1]) {
				f = n[1];
			} else {
				f = "anoynmous function";
			}
		}
		var args = m[2];
		return (f+args);
	} else {
		return "anonymous function";
	}
}
function bxe_getCaller( fn )
{
	switch( typeof( fn ))
	{
		case "undefined":
			return bxe_getCaller( bxe_getCaller );

		case "function":
			if( fn.caller )
				return fn.caller;
			if( fn.arguments && fn.arguments.caller )
				return fn.arguments.caller;
	}
	return undefined;
}

<commit_msg>automatic BuildDate Update<commit_after>/* ***** BEGIN LICENSE BLOCK *****
* Licensed under Version: MPL 1.1/GPL 2.0/LGPL 2.1
* Full Terms at http://mozile.mozdev.org/license.html
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Playsophy code.
*
* The Initial Developer of the Original Code is Playsophy
* Portions created by the Initial Developer are Copyright (C) 2002-2003
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */

const BXE_VERSION = "0.1alpha";
const BXE_BUILD = "200309260330"

var DebugOutput = true;

mozile_js_files = new Array();

mozile_js_files.push("mozile/mozWrappers.js");
mozile_js_files.push("js/widget.js");

mozile_js_files.push("mozile/eDOM.js");
mozile_js_files.push("js/bxeConfig.js");
mozile_js_files.push("mozile/eDOMXHTML.js");
mozile_js_files.push("js/bxeXMLNode.js");
mozile_js_files.push("js/bxeNodeElements.js");
mozile_js_files.push("js/bxeXMLDocument.js");
mozile_js_files.push("mozile/mozileTransportDriver.js");
mozile_js_files.push("mozile/td/http.js");
mozile_js_files.push("mozile/domlevel3.js");
mozile_js_files.push("mozile/mozCE.js");
mozile_js_files.push("mozile/mozIECE.js");
//mozile_js_files.push("mozile/mozileModify.js");
mozile_js_files.push("js/eDOMEvents.js");
mozile_js_files.push("js/bxeFunctions.js");

var mozile_root_dir = "./";

// some global vars, no need to change them
var mozile_corescript_loaded = 0;
var mozile_script_loaded = 0;
var bxe_config = new Object();
var bxe_about_box = null;
var bxe_format_list = null;
var bxe_context_menu = null;
var bxe_delayedUpdate = false;
var eDOM_bxe_mode = true;

function bxe_start(config_file,fromUrl, configArray) {

	/*if (! (BX_checkUnsupportedBrowsers())) {
		return false;
	}*/

	if((navigator.product == 'Gecko') && (navigator.userAgent.indexOf("Safari") == -1))
	{
		// navigator.productSub > '20020801' (test to see what the date should be)

		// POST04: if document.documentElement != HTML then ... or no "head" ...
		var head = document.getElementsByTagName("head")[0];
		bxe_config.file = config_file;
		bxe_config.fromUrl = fromUrl;
		bxe_config.configArray = configArray;
		if(head)
		{
			// get the location of this script and reuse it for the others
			for(var i=0; i<head.childNodes.length; i++)
			{
				var mozileLoaderRE = /(.*)bxeLoader.js$/;
				if(head.childNodes[i].localName == "SCRIPT")
				{
					var src = head.childNodes[i].src;
					var result = mozileLoaderRE.exec(src);
					if(result)
					{
						mozile_root_dir = result[1];
						break;
					}
				}
			}
			for (var i=0; i < mozile_js_files.length; i++)
			{
				var scr = document.createElementNS("http://www.w3.org/1999/xhtml","script");
				var src = mozile_root_dir + mozile_js_files[i];
				if (mozile_js_files[i] == "js/widget.js") {
					scr.onload = widget_loaded;
				} else {
					scr.onload = corescript_loaded;
				}
				scr.setAttribute("src", src);

				scr.setAttribute("language","JavaScript");
				head.appendChild(scr);
			}
			//when last include src is loaded, call onload handler

		}
		else {
			alert("*** ALERT: MozileLoader only works in XHTML - load Mozile JS explicitly in XML files");
		}
	}

}

// Detect Gecko but exclude Safari (for now); for now, only support XHTML

function bxe_load_xml (xmlfile) {

	var td = new mozileTransportDriver("webdav");
	function callback (e) {
		if (e.isError) {
			alert("Error loading xml file \n"+e.statusText);
			return false;
		}
		var xmldoc =  e.document;
		bxe_config.xmldoc = xmldoc;
		xmldoc.init();
		if (bxe_config.xhtmlfile) {
			xmldoc.importXHTMLDocument(bxe_config.xhtmlfile)
		} else if (bxe_config.xslfile) {
			xmldoc.transformToXPathMode(bxe_config.xslfile)
		} else {
			xmldoc.insertIntoHTMLDocument();
			xml_loaded(xmldoc);
		}

	}
	td.load(xmlfile,callback);

	return true;
}

function widget_loaded(e) {
	bxe_about_box = new Widget_AboutBox();
	bxe_about_box.draw();
	bxe_about_box.setText("Loading files ...");
	corescript_loaded(e);

}

function corescript_loaded(e) {
	mozile_corescript_loaded++;
	debug("from core script " + mozile_corescript_loaded + " of " + mozile_js_files.length  + "loaded: " + e.currentTarget.src);
	if ( mozile_js_files.length == mozile_corescript_loaded) {
		debug("call mozile_core_loaded()");
		mozile_core_loaded();
	} else {
		if (bxe_about_box) {
			bxe_about_box.addText(mozile_corescript_loaded );
		}
	}
}

function script_loaded(e) {
	mozile_script_loaded++;
	debug("from config script " + mozile_script_loaded + " loaded: " + e.currentTarget.src );
	if ( bxe_config.scriptfiles.length == mozile_script_loaded ) {
		debug("call mozile_loaded()");
		mozile_loaded();
	} else {
		bxe_about_box.addText(mozile_script_loaded );
	}
}

function mozile_core_loaded() {
	bxe_about_box.addText("Scripts loaded ...");
	bxe_about_box.addText("Load Config ");
	try {
		bxe_config = new bxeConfig(bxe_config.file, bxe_config.fromUrl, bxe_config.configArray);
	} catch (e) {
		bxe_catch_alert(e);
	}
}

function mozile_loaded() {
	bxe_about_box.addText("Load XML ...");
	bxe_load_xml(bxe_config.xmlfile);

}

function xml_loaded(xmldoc) {
	bxe_about_box.addText("Load RelaxNG ...");
	if (!(bxe_config.validationfile && xmldoc.XMLNode.loadSchema(bxe_config.validationfile,validation_loaded))) {
		bxe_about_box.addText("RelaxNG File was not found");
	}
	document.eDOMaddEventListener("toggleSourceMode",bxe_toggleSourceMode,false);
	document.eDOMaddEventListener("toggleTagMode",bxe_toggleTagMode,false);
	document.eDOMaddEventListener("toggleNormalMode",bxe_toggleNormalMode,false);
	document.eDOMaddEventListener("DocumentSave",__bxeSave,false);
	document.eDOMaddEventListener("ToggleTextClass",bxe_toggleTextClass,false);
	document.eDOMaddEventListener("appendNode",bxe_appendNode,false);
	document.eDOMaddEventListener("InsertLink",bxe_InsertLink,false);
	document.eDOMaddEventListener("InsertTable",bxe_InsertTable,false);
	document.eDOMaddEventListener("InsertImage",bxe_InsertImage,false);
	document.eDOMaddEventListener("OrderedList",bxe_OrderedList,false);
	document.eDOMaddEventListener("UnorderedList",bxe_UnorderedList,false);

	document.eDOMaddEventListener("changeLinesContainer",bxe_changeLinesContainer,false);
	document.eDOMaddEventListener("Exit",bxe_exit,false);

	document.eDOMaddEventListener("ClipboardCopy",function(e) { window.getSelection().copy()},false);
	document.eDOMaddEventListener("ClipboardPaste",function(e) { window.getSelection().paste()},false);
	document.eDOMaddEventListener("ClipboardCut",function(e) { window.getSelection().cut()},false);

	document.eDOMaddEventListener("Undo",function(e) { bxe_not_yet_implemented()}, false);
	document.eDOMaddEventListener("Redo",function(e) { bxe_not_yet_implemented()}, false);

	document.addEventListener("contextmenu",bxe_ContextMenuEvent, false);

	//document.eDOMaddEventListener("NodeInsertedParent",bxe_NodeInsertedParent, false);
	document.eDOMaddEventListener("NodeInsertedBefore",bxe_NodeInsertedBefore,false);
	document.eDOMaddEventListener("NodeBeforeDelete",bxe_NodeBeforeDelete,false);
	/*document.eDOMaddEventListener("NodeChanged",bxe_NodeChanged,false);

	document.eDOMaddEventListener("NodeRemovedChildOnly",bxe_NodeRemovedChildOnly,false);
	*/
	//document.eDOMaddEventListener("NodeAppendedChild",bxe_NodeAppendedChild,false);
	document.eDOMaddEventListener("NodePositionChanged",bxe_NodePositionChanged,false);

	document.eDOMaddEventListener("ContextPopup",bxe_ContextPopup,false);
	bxe_context_menu = new Widget_ContextMenu();
}

function validation_loaded(vdom) {
	bxe_about_box.addText("Validation Loaded ...");

	var vali = bxe_config.xmldoc.XMLNode.validateDocument();
	if (vali.isError) {
		bxe_about_box.addText("Document is *not* valid.");
		//alert(vali.getErrorMessagesAsText());
	}
	else {
		bxe_about_box.addText("Document is valid.");

	}
}

function config_loaded(bxe_config_in) {
	bxe_about_box.addText("& Parsed ...");

	bxe_config = bxe_config_in;
	var head = document.getElementsByTagName("head")[0];
	for (var i=0; i < bxe_config.cssfiles.length; i++)
	{
		var scr = document.createElementNS(XHTMLNS,"link");
		scr.setAttribute("type","text/css");
		scr.setAttribute("rel","stylesheet");
		scr.setAttribute("href",bxe_config.cssfiles[i]);
		head.appendChild(scr);
	}

	for (var i=0; i < bxe_config.scriptfiles.length; i++)
	{
		var scr = document.createElementNS("http://www.w3.org/1999/xhtml","script");
		var src = mozile_root_dir + bxe_config.scriptfiles[i];
		scr.onload = script_loaded;
		scr.setAttribute("src", src);
		scr.setAttribute("language","JavaScript");
		head.appendChild(scr);
	}

}

debug = function (text, options) {

	if (DebugOutput) {

		fn =  bxe_getCaller(debug);

		dump( fn.getName() +  ": " + text + "\n");
		if (options) {

			if (options.evalArguments) {
				var fname= fn.getName();
					dump("  Arguments: (");
					for (var i = 0; i < fn.arguments.length; i++) {
						dump("[" + typeof fn.arguments[i] + "] ");
						switch( typeof( fn.arguments[i] )) {
							case "function":
								dump (fn.arguments[i].getName());
								break;
							case "string":
								dump('"' + fn.arguments[i] + '"');
								break;
							default:
								dump(fn.arguments[i]);
						}
						if (i < fn.arguments.length - 1 ) {
							dump(", ");
						}
					}
					dump (")\n");

			}

			if (options.callstack) {
				var callstack =  new Array();
				dump ("  Callstack: \n");
				dump ("  ----------\n");
				while (fn) {

					callstack.unshift(fn.getName() + "\n");
					var newfn = JsUtil_getCaller(fn);
					if (fn == newfn) {
						callstack.unshift ("  [javascript recursion]\n");
						break;
					}
					fn = newfn;
				}
				for (var i = 0; i < callstack.length; i++) {
					dump("  " +i +": " +callstack[i]);
				}
				dump ("  ----------\n");

			}

		}

	}
}

Function.prototype.getName = function () {
	var r = /function (\w*)([^\{\}]*\))/
	var s = new String( this);
	var m = s.match( r );
	if (m) {
		var f = "";
		if (m[1]) {
			f = m[1];
		} else {
			r = /var id = "(.+)"/;
			var n = s.match(r);
			if (n && n[1]) {
				f = n[1];
			} else {
				f = "anoynmous function";
			}
		}
		var args = m[2];
		return (f+args);
	} else {
		return "anonymous function";
	}
}
function bxe_getCaller( fn )
{
	switch( typeof( fn ))
	{
		case "undefined":
			return bxe_getCaller( bxe_getCaller );

		case "function":
			if( fn.caller )
				return fn.caller;
			if( fn.arguments && fn.arguments.caller )
				return fn.arguments.caller;
	}
	return undefined;
}

<|endoftext|>


<commit_before>
import React from 'react';

export class Main extends React.Component {
  render() {
    return

Current state: { this.props.value }

      <button onClick={ this.props.onClickIncrement }>
        Increment
      </button>
      <button onClick={ this.props.onClickDecrement }>
        Decrement
      </button>

;
  }
}

Main.propTypes = {
  value: React.PropTypes.number
}
<commit_msg>Specify the types of these<commit_after>
import React from 'react';

export class Main extends React.Component {
  render() {
    return

Current state: { this.props.value }

      <button onClick={ this.props.onClickIncrement }>
        Increment
      </button>
      <button onClick={ this.props.onClickDecrement }>
        Decrement
      </button>

;
  }
}

Main.propTypes = {
  value: React.PropTypes.number,
  onClickIncrement: React.PropTypes.function,
  onClickDecrement: React.PropTypes.function
}
<|endoftext|>


<commit_before>'use strict';

var normalizeOptions   = require('es5-ext/object/normalize-options')
  , ensureDatabase     = require('dbjs/valid-dbjs')
  , ensureObject       = require('es5-ext/object/valid-object')
  , Set                = require('es6-set')
  , customError        = require('es5-ext/error/custom')
  , stringify          = JSON.stringify
  , dateStringtoDbDate = require('../../utils/date-string-to-db-date')
  , aFrom              = require('es5-ext/array/from')
  , ensureArray        = require('es5-ext/array/valid-array')
  , processingStepsMeta, db, availableServices;

var queryConf = [
	{
		name: 'dateFrom',
		ensure: function (value, resolvedQuery, query) {
			var now = new db.Date(), dateFrom, dateTo;
			if (!value) return;
			dateFrom = dateStringtoDbDate(db, value);
			if (dateFrom > now) throw new Error('From cannot be in future');
			if (query.dateTo) {
				dateTo = dateStringtoDbDate(db, query.dateTo);
				if (dateTo < dateFrom) throw new Error('Invalid date range');
			}
			return dateFrom;
		}
	},
	{
		name: 'dateTo',
		ensure: function (value) {
			var now = new db.Date(), dateTo;
			if (!value) return;
			dateTo = dateStringtoDbDate(db, value);
			if (dateTo > now) {
				throw customError("To date cannot be in future", { fixedQueryValue: now });
			}
			return dateTo;
		}
	}
];

module.exports = exports = function (data) {
	var options         = normalizeOptions(ensureObject(data)), conf;
	db                  = ensureDatabase(options.db);
	processingStepsMeta = options.processingStepsMeta;
	conf                = aFrom(queryConf);
	if (processingStepsMeta) {
		availableServices   = new Set();
		Object.keys(processingStepsMeta).forEach(function (stepShortPath) {
			processingStepsMeta[stepShortPath]._services.forEach(function (serviceName) {
				availableServices.add(serviceName);
			});
		});

		conf.push({
			name: 'service',
			ensure: function (value) {
				if (!value) return;
				if (!availableServices.has(value)) {
					throw new Error("Unrecognized service value " + stringify(value));
				}
				return value;
			}
		}, {
			name: 'step',
			ensure: function (value) {
				if (!value) return;
				if (!processingStepsMeta[value]) {
					throw new Error("Unrecognized step value " + stringify(value));
				}
				return value;
			}
		});
	}
	if (exports.customQueryConf) {
		ensureArray(exports.customQueryConf).forEach(function (confItem) {
			conf.push(confItem);
		});
	}

	return conf;
};
<commit_msg>Improve date range query handling<commit_after>'use strict';

var normalizeOptions   = require('es5-ext/object/normalize-options')
  , ensureDatabase     = require('dbjs/valid-dbjs')
  , ensureObject       = require('es5-ext/object/valid-object')
  , Set                = require('es6-set')
  , customError        = require('es5-ext/error/custom')
  , stringify          = JSON.stringify
  , dateStringtoDbDate = require('../../utils/date-string-to-db-date')
  , aFrom              = require('es5-ext/array/from')
  , ensureArray        = require('es5-ext/array/valid-array')
  , processingStepsMeta, db, availableServices;

var queryConf = [
	{
		name: 'dateFrom',
		ensure: function (value, resolvedQuery, query) {
			var now = new db.Date(), dateFrom, dateTo;
			if (!value) return;
			dateFrom = dateStringtoDbDate(db, value);
			if (dateFrom > now) {
				throw customError("From date cannot be in future", { fixedQueryValue: null });
			}
			if (query.dateTo) {
				dateTo = dateStringtoDbDate(db, query.dateTo);
				if (dateTo < dateFrom) {
					throw customError("date 'from' cannot be younger than 'to'",
						{ fixedQueryValue: query.dateTo });
				}
			}
			return dateFrom;
		}
	},
	{
		name: 'dateTo',
		ensure: function (value) {
			var now = new db.Date(), dateTo;
			if (!value) return;
			dateTo = dateStringtoDbDate(db, value);
			if (dateTo > now) {
				throw customError("To date cannot be in future", { fixedQueryValue: null });
			}
			return dateTo;
		}
	}
];

module.exports = exports = function (data) {
	var options         = normalizeOptions(ensureObject(data)), conf;
	db                  = ensureDatabase(options.db);
	processingStepsMeta = options.processingStepsMeta;
	conf                = aFrom(queryConf);
	if (processingStepsMeta) {
		availableServices   = new Set();
		Object.keys(processingStepsMeta).forEach(function (stepShortPath) {
			processingStepsMeta[stepShortPath]._services.forEach(function (serviceName) {
				availableServices.add(serviceName);
			});
		});

		conf.push({
			name: 'service',
			ensure: function (value) {
				if (!value) return;
				if (!availableServices.has(value)) {
					throw new Error("Unrecognized service value " + stringify(value));
				}
				return value;
			}
		}, {
			name: 'step',
			ensure: function (value) {
				if (!value) return;
				if (!processingStepsMeta[value]) {
					throw new Error("Unrecognized step value " + stringify(value));
				}
				return value;
			}
		});
	}
	if (exports.customQueryConf) {
		ensureArray(exports.customQueryConf).forEach(function (confItem) {
			conf.push(confItem);
		});
	}

	return conf;
};
<|endoftext|>


<commit_before>$(document).ready(function() {
  $("#podcast_submit").click(function(){
      title=encodeURIComponent($("#podcast_title").val());
      post=encodeURIComponent($("#podcast_post").val());
      file=encodeURIComponent($("#podcast_file").val());
      $.ajax({
        type: "POST",
        url: "../../../publish_podcast.php",
        data: "title="+title+"&post="+post+"&file="+file,
        success: function(html)
        {
          if(html=='true')
          {
            window.location.reload();
          }
          else
          {
            $('#newPodcast').modal('hide');
            $("#top_msg").css('display', 'inline', 'important');
            $("#top_msg").html('
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'+html+'
');
          }
        }
      });
    return false;
  });

  $('#newPodcast').on('hide.bs.modal', function (e) {
    podFile=encodeURIComponent($("#podcast_file").val());
    if (podFile != '')
    {
      $.ajax({
        type: "POST",
        url: "../../../delete_podcast_file.php",
        data: "file="+podFile,
        success: function(html)
        {
          if(html)
          {
            $("#uploadedPodcasts").html('');
            $("#podcast_file").val('');
          }
        }
      });
    }
  });

  $('#editPodcast').on('show.bs.modal', function (e) {
    $("#edit_podcast_post").val("");
    $("#edit_podcast_title").val("");
    $("#edit_podcast_file").val("");
    userID=encodeURIComponent($(e.relatedTarget).attr("id"));
    $("#edit_podcast_postid").val(userID);
    $.ajax({
      type: "POST",
      url: "../../../get_title_content.php",
      data: "id="+userID,
      success: function(html)
      {
        if(html)
        {
          $("#edit_podcast_title").val(html);
        }
      }
    });
    $.ajax({
      type: "POST",
      url: "../../../get_post_content.php",
      data: "id="+userID,
      success: function(html)
      {
        if(html)
        {
          $("#edit_podcast_post").val(html);
        }
      }
    });
    $.ajax({
      type: "POST",
      url: "../../../get_podcast_file.php",
      data: "id="+userID,
      success: function(html)
      {
        if(html)
        {
          var fileList = html.split(',');
          for (var i = 0; i < fileList.length; i++)
          {
            $("#edit_uploadedPodcasts").append('
<button type="button" class="close podcast_file_delete" id="'+fileList[i]+'">×</button>'+fileList[i]+'
');
            linkEditFileDelete('.podcast_file_delete');
            if ($("#edit_podcast_file").val() == '')
            {
              $("#edit_podcast_file").val(fileList[i]);
            }
            else
            {
              $("#edit_podcast_file").val($("#edit_podcast_file").val()+','+fileList[i]);
            }
          }
        }
      }
    });
  });

  $('#editPodcast').on('hide.bs.modal', function (e) {
    userID=encodeURIComponent($("#edit_podcast_postid").val());
    $.ajax({
      type: "POST",
      url: "../../../get_podcast_file.php",
      data: "id="+userID,
      success: function(html)
      {
        if(html)
        {
          podFile=encodeURIComponent($("#edit_podcast_file").val());

          var fileList = $("#edit_podcast_file").val().split(',');
          var oldFileList = html.split(',');
          for (var i = 0; i < fileList.length; i++)
          {
            var index = oldFileList.indexOf(fileList[i]);
            if (index == -1)
            {
              $.ajax({
                type: "POST",
                url: "../../../delete_podcast_file.php",
                data: "file="+fileList[i],
                success: function(response)
                {
                  if(response)
                  {
                    $("#edit_uploadedPodcasts").html('');
                    $("#edit_podcast_file").val('');
                  }
                }
              });
            }
          }
        }
      }
    });
  });

  $("#edit_submit").click(function(){
      postID=encodeURIComponent($("#edit_podcast_postid").val());
      title=encodeURIComponent($("#edit_podcast_title").val());
      post=encodeURIComponent($("#edit_podcast_post").val());
      file=encodeURIComponent($("#edit_podcast_file").val());
      $.ajax({
        type: "POST",
        url: "../../../edit_podcast.php",
        data: "postID="+postID+"&title="+title+"&post="+post+"&file="+file,
        success: function(html)
        {
          if(html=='true')
          {
            window.location.reload();
          }
          else
          {
            $('#editPodcast').modal('hide');
            $("#top_msg").css('display', 'inline', 'important');
            $("#top_msg").html('
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'+html+'
');
          }
        }
      });
    return false;
  });

  $("#comment_submit").click(function(){
      $('#newComment').modal('hide');
      postID=encodeURIComponent($("#post_id").val());
      post=encodeURIComponent($("#comment_post").val());
      $.ajax({
        type: "POST",
        url: "../../../includes/add_comment.php",
        data: "postID="+postID+"&service=podcast&comment="+post,
        success: function(html)
        {
          if(html=='true')
          {
            window.location.reload();
          }
          else
          {
            $("#top_msg").css('display', 'inline', 'important');
            $("#top_msg").html('
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'+html+'
');
          }
        }
      });
    return false;
  });

  $('#editComment').on('show.bs.modal', function (e) {
    $("#edit_comment_post").val("");
    commentID=encodeURIComponent($(e.relatedTarget).attr("id"));
    $("#edit_comment_postid").val(commentID);
    $.ajax({
      type: "POST",
      url: "../../../includes/get_comment_content.php",
      data: "id="+commentID,
      success: function(html)
      {
        if(html)
        {
          $("#edit_comment_post").val(html);
        }
      }
    });
  });

  $("#edit_comment_submit").click(function(){
      $('#editComment').modal('hide');
      postID=encodeURIComponent($("#edit_comment_postid").val());
      post=encodeURIComponent($("#edit_comment_post").val());
      $.ajax({
        type: "POST",
        url: "../../../includes/edit_comment.php",
        data: "commentID="+postID+"&post="+post,
        success: function(html)
        {
          if(html=='true')
          {
            window.location.reload();
          }
          else
          {
            $("#top_msg").css('display', 'inline', 'important');
            $("#top_msg").html('
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'+html+'
');
          }
        }
      });
    return false;
  });
});

$(function() {
  $('#uploadPodcast').fileupload({
      dataType: 'json',
      url: '../../../upload_podcast.php',
      paramName: 'file',
      done: function (e, data) {
        $("#uploadedPodcasts").html('');
        if (!data.result.error)
        {
          podFile=encodeURIComponent($("#podcast_file").val());
          if (podFile != '')
          {
            $("#podcast_file").val(podFile+','+data.result.file.name);
          }
          else
          {
            $("#podcast_file").val(data.result.file.name);
          }
          $("#uploadedPodcasts").append('
<button type="button" class="close podcast_file_delete" id="'+data.result.file.name+'">×</button>'+data.result.file.name+'
');
          linkFileDelete('.podcast_file_delete');
        }
        else
        {
          $("#top_msg").css('display', 'inline', 'important');
          $("#top_msg").html('
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'+data.result.error.message+'
');
        }
      }
  });

  $('#edit_uploadPodcast').fileupload({
      dataType: 'json',
      url: '../../../upload_podcast.php',
      paramName: 'file',
      done: function (e, data) {
        if (!data.result.error)
        {
          podFile=encodeURIComponent($("#edit_podcast_file").val());
          if (podFile != '')
          {
            $("#edit_podcast_file").val(podFile+','+data.result.file.name);
          }
          else
          {
            $("#edit_podcast_file").val(data.result.file.name);
          }
          $("#edit_uploadedPodcasts").append('
<button type="button" class="close podcast_file_delete" id="'+data.result.file.name+'">×</button>'+data.result.file.name+'
');
          linkEditFileDelete('.podcast_file_delete');
        }
        else
        {
          $("#top_msg").css('display', 'inline', 'important');
          $("#top_msg").html('
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'+data.result.error.message+'
');
        }
      }
  });
});

function loadMorePosts(start, count)
{
  blog_id=encodeURIComponent($(".podcast-main").attr("id"));
  $.ajax({
    type: "POST",
    url: "../../../get_post.php",
    data: "userID="+blog_id+"&postCount="+count+"&startPost="+start,
    success: function(html)
    {
      if(html)
      {
        $(".podcast-main").append(html);
        linkPostDelete('.delete_post');
        linkAudioPlayer('audio');
        $(window).bind('scroll', bindScrollPosts);
      }
    }
  });
}

function loadMoreComments(start, count)
{
  post_id=encodeURIComponent($(".post-comments").attr("id"));
  $.ajax({
    type: "POST",
    url: "../../../includes/get_comment.php",
    data: "postID="+post_id+"&service=podcast&postCount="+count+"&startPost="+start,
    success: function(html)
    {
      if(html)
      {
        $(".post-comments").append(html);
        linkCommentDelete('.delete_comment');
        $(window).bind('scroll', bindScrollComments);
      }
    }
  });
}

function bindScrollPosts()
{
   if($(window).scrollTop() + $(window).height() > $(document).height() - 100)
   {
       $(window).unbind('scroll');
       loadMorePosts(start_post, posts);
       start_post = start_post + posts;
   }
}

function bindScrollComments()
{
   if($(window).scrollTop() + $(window).height() > $(document).height() - 100)
   {
       $(window).unbind('scroll');
       loadMoreComments(start_post, posts);
       start_post = start_post + posts;
   }
}

function linkPostDelete(selector)
{
  $(selector).click(function() {
    var object = $(this);
    post_id=encodeURIComponent(object.attr("id"));
    bootbox.confirm("Are you sure you want to delete your post?", function(result) {
      if (result)
      {
        $.ajax({
          type: "POST",
          url: "../../../delete_podcast.php",
          data: "id="+post_id,
          success: function(html)
          {
            if(html=='true')
            {
              window.location.reload();
            }
            else
            {
              $("#top_msg").css('display', 'inline', 'important');
              $("#top_msg").html('
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'+html+'
');
            }
          }
        });
      }
    });
  });
}

function linkCommentDelete(selector)
{
  $(selector).click(function() {
    var object = $(this);
    post_id=encodeURIComponent(object.attr("id"));
    bootbox.confirm("Are you sure you want to delete your comment?", function(result) {
      if (result)
      {
        $.ajax({
          type: "POST",
          url: "../../../includes/delete_comment.php",
          data: "id="+post_id,
          success: function(html)
          {
            if(html=='true')
            {
              window.location.reload();
            }
            else
            {
              $("#top_msg").css('display', 'inline', 'important');
              $("#top_msg").html('
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'+html+'
');
            }
          }
        });
      }
    });
  });
}

function linkFileDelete(selector)
{
  $(selector).click(function(){
    var object = $(this);
    podFile=encodeURIComponent(object.attr('id'));
    allFiles=$("#podcast_file").val();
    $.ajax({
      type: "POST",
      url: "../../../delete_podcast_file.php",
      data: "file="+podFile,
      success: function(html)
      {
        var fileList = allFiles.split(',');
        var index = fileList.indexOf(podFile);
        if (index != -1)
        {
          fileList.splice(index, 1);
          $("#podcast_file").val(fileList.toString());
        }
        $(".uploaded_file_"+podFile.replace(".", "_")).remove();
      }
    });
    return false;
  });
}

function linkEditFileDelete(selector)
{
  $(selector).click(function(){
    var object = $(this);
    podFile=encodeURIComponent(object.attr('id'));
    allFiles=$("#edit_podcast_file").val();
    $.ajax({
      type: "POST",
      url: "../../../delete_podcast_file.php",
      data: "file="+podFile,
      success: function(html)
      {
        var fileList = allFiles.split(',');
        var index = fileList.indexOf(podFile);
        if (index != -1)
        {
          fileList.splice(index, 1);
          $("#edit_podcast_file").val(fileList.toString());
        }
        $(".uploaded_file_"+podFile.replace(".", "_")).remove();
      }
    });
    return false;
  });
}

function linkAudioPlayer(selector)
{
  $(selector).audioPlayer(
  {
    classPrefix: 'audioplayer'
  });
}<commit_msg>Removed url encoding of podcast files<commit_after>$(document).ready(function() {
  $("#podcast_submit").click(function(){
      title=encodeURIComponent($("#podcast_title").val());
      post=encodeURIComponent($("#podcast_post").val());
      file=encodeURIComponent($("#podcast_file").val());
      $.ajax({
        type: "POST",
        url: "../../../publish_podcast.php",
        data: "title="+title+"&post="+post+"&file="+file,
        success: function(html)
        {
          if(html=='true')
          {
            window.location.reload();
          }
          else
          {
            $('#newPodcast').modal('hide');
            $("#top_msg").css('display', 'inline', 'important');
            $("#top_msg").html('
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'+html+'
');
          }
        }
      });
    return false;
  });

  $('#newPodcast').on('hide.bs.modal', function (e) {
    podFile=encodeURIComponent($("#podcast_file").val());
    if (podFile != '')
    {
      $.ajax({
        type: "POST",
        url: "../../../delete_podcast_file.php",
        data: "file="+podFile,
        success: function(html)
        {
          if(html)
          {
            $("#uploadedPodcasts").html('');
            $("#podcast_file").val('');
          }
        }
      });
    }
  });

  $('#editPodcast').on('show.bs.modal', function (e) {
    $("#edit_podcast_post").val("");
    $("#edit_podcast_title").val("");
    $("#edit_podcast_file").val("");
    userID=encodeURIComponent($(e.relatedTarget).attr("id"));
    $("#edit_podcast_postid").val(userID);
    $.ajax({
      type: "POST",
      url: "../../../get_title_content.php",
      data: "id="+userID,
      success: function(html)
      {
        if(html)
        {
          $("#edit_podcast_title").val(html);
        }
      }
    });
    $.ajax({
      type: "POST",
      url: "../../../get_post_content.php",
      data: "id="+userID,
      success: function(html)
      {
        if(html)
        {
          $("#edit_podcast_post").val(html);
        }
      }
    });
    $.ajax({
      type: "POST",
      url: "../../../get_podcast_file.php",
      data: "id="+userID,
      success: function(html)
      {
        if(html)
        {
          var fileList = html.split(',');
          for (var i = 0; i < fileList.length; i++)
          {
            $("#edit_uploadedPodcasts").append('
<button type="button" class="close podcast_file_delete" id="'+fileList[i]+'">×</button>'+fileList[i]+'
');
            linkEditFileDelete('.podcast_file_delete');
            if ($("#edit_podcast_file").val() == '')
            {
              $("#edit_podcast_file").val(fileList[i]);
            }
            else
            {
              $("#edit_podcast_file").val($("#edit_podcast_file").val()+','+fileList[i]);
            }
          }
        }
      }
    });
  });

  $('#editPodcast').on('hide.bs.modal', function (e) {
    userID=encodeURIComponent($("#edit_podcast_postid").val());
    $.ajax({
      type: "POST",
      url: "../../../get_podcast_file.php",
      data: "id="+userID,
      success: function(html)
      {
        if(html)
        {
          podFile=encodeURIComponent($("#edit_podcast_file").val());

          var fileList = $("#edit_podcast_file").val().split(',');
          var oldFileList = html.split(',');
          for (var i = 0; i < fileList.length; i++)
          {
            var index = oldFileList.indexOf(fileList[i]);
            if (index == -1)
            {
              $.ajax({
                type: "POST",
                url: "../../../delete_podcast_file.php",
                data: "file="+fileList[i],
                success: function(response)
                {
                  if(response)
                  {
                    $("#edit_uploadedPodcasts").html('');
                    $("#edit_podcast_file").val('');
                  }
                }
              });
            }
          }
        }
      }
    });
  });

  $("#edit_submit").click(function(){
      postID=encodeURIComponent($("#edit_podcast_postid").val());
      title=encodeURIComponent($("#edit_podcast_title").val());
      post=encodeURIComponent($("#edit_podcast_post").val());
      file=encodeURIComponent($("#edit_podcast_file").val());
      $.ajax({
        type: "POST",
        url: "../../../edit_podcast.php",
        data: "postID="+postID+"&title="+title+"&post="+post+"&file="+file,
        success: function(html)
        {
          if(html=='true')
          {
            window.location.reload();
          }
          else
          {
            $('#editPodcast').modal('hide');
            $("#top_msg").css('display', 'inline', 'important');
            $("#top_msg").html('
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'+html+'
');
          }
        }
      });
    return false;
  });

  $("#comment_submit").click(function(){
      $('#newComment').modal('hide');
      postID=encodeURIComponent($("#post_id").val());
      post=encodeURIComponent($("#comment_post").val());
      $.ajax({
        type: "POST",
        url: "../../../includes/add_comment.php",
        data: "postID="+postID+"&service=podcast&comment="+post,
        success: function(html)
        {
          if(html=='true')
          {
            window.location.reload();
          }
          else
          {
            $("#top_msg").css('display', 'inline', 'important');
            $("#top_msg").html('
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'+html+'
');
          }
        }
      });
    return false;
  });

  $('#editComment').on('show.bs.modal', function (e) {
    $("#edit_comment_post").val("");
    commentID=encodeURIComponent($(e.relatedTarget).attr("id"));
    $("#edit_comment_postid").val(commentID);
    $.ajax({
      type: "POST",
      url: "../../../includes/get_comment_content.php",
      data: "id="+commentID,
      success: function(html)
      {
        if(html)
        {
          $("#edit_comment_post").val(html);
        }
      }
    });
  });

  $("#edit_comment_submit").click(function(){
      $('#editComment').modal('hide');
      postID=encodeURIComponent($("#edit_comment_postid").val());
      post=encodeURIComponent($("#edit_comment_post").val());
      $.ajax({
        type: "POST",
        url: "../../../includes/edit_comment.php",
        data: "commentID="+postID+"&post="+post,
        success: function(html)
        {
          if(html=='true')
          {
            window.location.reload();
          }
          else
          {
            $("#top_msg").css('display', 'inline', 'important');
            $("#top_msg").html('
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'+html+'
');
          }
        }
      });
    return false;
  });
});

$(function() {
  $('#uploadPodcast').fileupload({
      dataType: 'json',
      url: '../../../upload_podcast.php',
      paramName: 'file',
      done: function (e, data) {
        $("#uploadedPodcasts").html('');
        if (!data.result.error)
        {
          podFile=$("#podcast_file").val();
          if (podFile != '')
          {
            $("#podcast_file").val(podFile+','+data.result.file.name);
          }
          else
          {
            $("#podcast_file").val(data.result.file.name);
          }
          $("#uploadedPodcasts").append('
<button type="button" class="close podcast_file_delete" id="'+data.result.file.name+'">×</button>'+data.result.file.name+'
');
          linkFileDelete('.podcast_file_delete');
        }
        else
        {
          $("#top_msg").css('display', 'inline', 'important');
          $("#top_msg").html('
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'+data.result.error.message+'
');
        }
      }
  });

  $('#edit_uploadPodcast').fileupload({
      dataType: 'json',
      url: '../../../upload_podcast.php',
      paramName: 'file',
      done: function (e, data) {
        if (!data.result.error)
        {
          podFile=$("#edit_podcast_file").val();
          if (podFile != '')
          {
            $("#edit_podcast_file").val(podFile+','+data.result.file.name);
          }
          else
          {
            $("#edit_podcast_file").val(data.result.file.name);
          }
          $("#edit_uploadedPodcasts").append('
<button type="button" class="close podcast_file_delete" id="'+data.result.file.name+'">×</button>'+data.result.file.name+'
');
          linkEditFileDelete('.podcast_file_delete');
        }
        else
        {
          $("#top_msg").css('display', 'inline', 'important');
          $("#top_msg").html('
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'+data.result.error.message+'
');
        }
      }
  });
});

function loadMorePosts(start, count)
{
  blog_id=encodeURIComponent($(".podcast-main").attr("id"));
  $.ajax({
    type: "POST",
    url: "../../../get_post.php",
    data: "userID="+blog_id+"&postCount="+count+"&startPost="+start,
    success: function(html)
    {
      if(html)
      {
        $(".podcast-main").append(html);
        linkPostDelete('.delete_post');
        linkAudioPlayer('audio');
        $(window).bind('scroll', bindScrollPosts);
      }
    }
  });
}

function loadMoreComments(start, count)
{
  post_id=encodeURIComponent($(".post-comments").attr("id"));
  $.ajax({
    type: "POST",
    url: "../../../includes/get_comment.php",
    data: "postID="+post_id+"&service=podcast&postCount="+count+"&startPost="+start,
    success: function(html)
    {
      if(html)
      {
        $(".post-comments").append(html);
        linkCommentDelete('.delete_comment');
        $(window).bind('scroll', bindScrollComments);
      }
    }
  });
}

function bindScrollPosts()
{
   if($(window).scrollTop() + $(window).height() > $(document).height() - 100)
   {
       $(window).unbind('scroll');
       loadMorePosts(start_post, posts);
       start_post = start_post + posts;
   }
}

function bindScrollComments()
{
   if($(window).scrollTop() + $(window).height() > $(document).height() - 100)
   {
       $(window).unbind('scroll');
       loadMoreComments(start_post, posts);
       start_post = start_post + posts;
   }
}

function linkPostDelete(selector)
{
  $(selector).click(function() {
    var object = $(this);
    post_id=encodeURIComponent(object.attr("id"));
    bootbox.confirm("Are you sure you want to delete your post?", function(result) {
      if (result)
      {
        $.ajax({
          type: "POST",
          url: "../../../delete_podcast.php",
          data: "id="+post_id,
          success: function(html)
          {
            if(html=='true')
            {
              window.location.reload();
            }
            else
            {
              $("#top_msg").css('display', 'inline', 'important');
              $("#top_msg").html('
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'+html+'
');
            }
          }
        });
      }
    });
  });
}

function linkCommentDelete(selector)
{
  $(selector).click(function() {
    var object = $(this);
    post_id=encodeURIComponent(object.attr("id"));
    bootbox.confirm("Are you sure you want to delete your comment?", function(result) {
      if (result)
      {
        $.ajax({
          type: "POST",
          url: "../../../includes/delete_comment.php",
          data: "id="+post_id,
          success: function(html)
          {
            if(html=='true')
            {
              window.location.reload();
            }
            else
            {
              $("#top_msg").css('display', 'inline', 'important');
              $("#top_msg").html('
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'+html+'
');
            }
          }
        });
      }
    });
  });
}

function linkFileDelete(selector)
{
  $(selector).click(function(){
    var object = $(this);
    podFile=encodeURIComponent(object.attr('id'));
    allFiles=$("#podcast_file").val();
    $.ajax({
      type: "POST",
      url: "../../../delete_podcast_file.php",
      data: "file="+podFile,
      success: function(html)
      {
        var fileList = allFiles.split(',');
        var index = fileList.indexOf(podFile);
        if (index != -1)
        {
          fileList.splice(index, 1);
          $("#podcast_file").val(fileList.toString());
        }
        $(".uploaded_file_"+podFile.replace(".", "_")).remove();
      }
    });
    return false;
  });
}

function linkEditFileDelete(selector)
{
  $(selector).click(function(){
    var object = $(this);
    podFile=encodeURIComponent(object.attr('id'));
    allFiles=$("#edit_podcast_file").val();
    $.ajax({
      type: "POST",
      url: "../../../delete_podcast_file.php",
      data: "file="+podFile,
      success: function(html)
      {
        var fileList = allFiles.split(',');
        var index = fileList.indexOf(podFile);
        if (index != -1)
        {
          fileList.splice(index, 1);
          $("#edit_podcast_file").val(fileList.toString());
        }
        $(".uploaded_file_"+podFile.replace(".", "_")).remove();
      }
    });
    return false;
  });
}

function linkAudioPlayer(selector)
{
  $(selector).audioPlayer(
  {
    classPrefix: 'audioplayer'
  });
}<|endoftext|>


<commit_before>/* eslint-disable max-len */
const getDisplayItemTemplate = () => {
  const uniqueId = `display-item-${Date.now()}`;
  return `

        <input class="mdl-textfield__input display-item-label" type="text" id="${uniqueId}-label" value="">
        Label

        <input class="mdl-textfield__input display-item-amount" type="text" pattern="-?[0-9]*(\.[0-9]+)?" id="${uniqueId}-amount" value="">
        Amount
        The value must be a number.

        <input class="mdl-textfield__input display-item-currency" type="text" id="${uniqueId}-currency" value="USD">
        Currency

`;
};

const getShippingOptionTemplate = () => {
  const uniqueId = `shipping-opt-${Date.now()}`;
  return `

      <input class="mdl-textfield__input" type="text" id="${uniqueId}-id" value="${this._shippingId}">
      ID

        <input class="mdl-textfield__input" type="text" id="${uniqueId}-label" value="">
        Label

        <input class="mdl-textfield__input" type="text" pattern="-?[0-9]*(\.[0-9]+)?" id="${uniqueId}-amount" value="">
        Amount
        The value must be a number.

        <input type="checkbox" id="${uniqueId}-selected" class="mdl-checkbox__input">
        Selected

`;
};
/* eslint-enable max-len */

class DemoController {
  constructor() {
    this._shippingId = 0;

    const addDisplayItemBtn = document.querySelector('.add-display-item');
    addDisplayItemBtn.addEventListener('click', () => this.addDisplayItem());

    const addShippingOptBtn = document.querySelector('.add-shipping-opt');
    addShippingOptBtn.addEventListener('click', () => this.addShippingOpt());

    const buyNowBtn = document.querySelector('.buy-now-btn');
    buyNowBtn.addEventListener('click', () => this.buyNowClick());
  }

  addDisplayItem() {
    const templateString = getDisplayItemTemplate();
    const documentHack = document.createElement('div');
    documentHack.innerHTML = templateString;
    const newDisplayItem = documentHack.firstChild;

    const mdlElements = newDisplayItem.querySelectorAll(`.needs-mdl-upgrade`);
    mdlElements.forEach((mdlElement) => {
      window.componentHandler.upgradeElement(mdlElement);
    });

    const itemsContainer = document.querySelector('.display-items-container');
    itemsContainer.appendChild(newDisplayItem);
  }

  addShippingOpt() {
    this._shippingId++;
    const templateString = getShippingOptionTemplate();

    const documentHack = document.createElement('div');
    documentHack.innerHTML = templateString;
    const newDisplayItem = documentHack.firstChild;

    const mdlElements = newDisplayItem.querySelectorAll(`.needs-mdl-upgrade`);
    mdlElements.forEach((mdlElement) => {
      window.componentHandler.upgradeElement(mdlElement);
    });

    const itemsContainer = document.querySelector('.shipping-opts-container');
    itemsContainer.appendChild(newDisplayItem);
  }

  buyNowClick() {
    // Supported payment methods
    const supportedPaymentMethods = [];
    const basicCardCheckboxes = document.querySelectorAll(
      '.basic-card-payment-methods input[type=\'checkbox\']');
    basicCardCheckboxes.forEach((basicCardCheckbox) => {
      if (basicCardCheckbox.checked &&
        basicCardCheckbox.dataset.paymentmethod) {
        supportedPaymentMethods.push(basicCardCheckbox.dataset.paymentmethod);
      }
    });

    const displayItemsFromUI = [];
    const displayItemElements =
      document.querySelectorAll('.display-item-wrapper');
    displayItemElements.forEach((displayItemElement) => {
      const labelValue =
        displayItemElement.querySelector('.display-item-label').value;
      const amountValue =
        displayItemElement.querySelector('.display-item-amount').value;
      const currencyValue =
        displayItemElement.querySelector('.display-item-currency').value;

      if (!labelValue || labelValue.length === 0 ||
        !amountValue || amountValue.length === 0) {
        console.warn('Found a display item without a label and / ' +
          'or amount value so excluding it from the results.');
        return;
      }

      displayItemsFromUI.push({
        label: labelValue,
        amount: {
          currency: currencyValue,
          value: amountValue,
        },
      });
    });

    const totalLabelValue =
      document.querySelector('.summary-label').value;
    const totalCurrencyValue =
      document.querySelector('.summary-currency').value;
    const totalAmountValue =
      document.querySelector('.summary-amount').value;

    const totalFromUI = {
      label: totalLabelValue,
      amount: {
        currency: totalCurrencyValue,
        value: totalAmountValue,
      },
    };

    /**
    // Checkout details
    var shipping_options = [];
    $("#shipping-options").children(".shipping-option").each(function(idx) {
      var option_id = $(this).find(".shipping-option-id").val();
      var option_label = $(this).find(".shipping-option-label").val();
      var option_amount = $(this).find(".shipping-option-amount").val();
      var option_selected = $(this).find("button").hasClass("button-primary");
      shipping_options.push({
        id: option_id,
        label: option_label,
        amount: {
          currency: $("#currency").val(), value: option_amount
        },
        selected: option_selected
      })
    });
    var details = {
      shippingOptions: shipping_options,
    };
    var shipping_type = document.getElementById("shipping-type");
    var options = {
      shippingType: shipping_type.options[shipping_type.selectedIndex].value
    };
    $("#options .options-request button.button-primary").each(function(idx) {
      var option_text = $(this).text();
      if (option_text == "Name")
        options.requestPayerName = true;
      if (option_text == "Phone")
        options.requestPayerPhone = true;
      if (option_text == "Email")
        options.requestPayerEmail = true;
      if (option_text == "Shipping")
        options.requestShipping = true;
    });
    **/

    // Why is this an array of an object with supportedMethods?
    const supportedInstruments = [{
      supportedMethods: supportedPaymentMethods,
    }];
    const details = {
      displayItems: displayItemsFromUI,
      // Excluding total will result in an error - it's a required field.
      total: totalFromUI,
    };
    const options = {};

    const paymentRequest = new PaymentRequest(
      supportedInstruments,
      details,
      options);
    paymentRequest.show()
    .then((result) => {
      // Process the payment
      const data = {};
      data.methodName = result.methodName;
      data.details = result.details;

      // $("#result").text(JSON.stringify(data, null, 2));
      return result.complete('success');
    })
    .catch((err) => {
      console.group(
        'The promise from `paymentRequest.show()` rejected.');
      console.warn('This is normally due to the user closing or cancelling ' +
        'the payment request UI.');
      console.warn(`The error received was: '${err.message}'`);
      console.groupEnd();
    });
  }
}

window.addEventListener('load', function() {
  if ('PaymentRequest' in window) {
    // Enable the demo
    const demoContainer = document.querySelector('.demo-container');
    demoContainer.classList.remove('is-not-supported');
    new DemoController();
  } else {
    document.querySelector('.supported-warning').classList.remove('hide');
  }
});
<commit_msg>Error with currencies<commit_after>/* eslint-disable max-len */
const getDisplayItemTemplate = () => {
  const uniqueId = `display-item-${Date.now()}`;
  return `

        <input class="mdl-textfield__input display-item-label" type="text" id="${uniqueId}-label" value="">
        Label

        <input class="mdl-textfield__input display-item-amount" type="text" pattern="-?[0-9]*(\.[0-9]+)?" id="${uniqueId}-amount" value="">
        Amount
        The value must be a number.

        <input class="mdl-textfield__input display-item-currency" type="text" id="${uniqueId}-currency" value="USD">
        Currency

`;
};

const getShippingOptionTemplate = () => {
  const uniqueId = `shipping-opt-${Date.now()}`;
  return `

      <input class="mdl-textfield__input" type="text" id="${uniqueId}-id" value="${this._shippingId}">
      ID

        <input class="mdl-textfield__input" type="text" id="${uniqueId}-label" value="">
        Label

        <input class="mdl-textfield__input" type="text" pattern="-?[0-9]*(\.[0-9]+)?" id="${uniqueId}-amount" value="">
        Amount
        The value must be a number.

        <input type="checkbox" id="${uniqueId}-selected" class="mdl-checkbox__input">
        Selected

`;
};
/* eslint-enable max-len */

class DemoController {
  constructor() {
    this._shippingId = 0;

    const addDisplayItemBtn = document.querySelector('.add-display-item');
    addDisplayItemBtn.addEventListener('click', () => this.addDisplayItem());

    const addShippingOptBtn = document.querySelector('.add-shipping-opt');
    addShippingOptBtn.addEventListener('click', () => this.addShippingOpt());

    const buyNowBtn = document.querySelector('.buy-now-btn');
    buyNowBtn.addEventListener('click', () => this.buyNowClick());
  }

  addDisplayItem() {
    const templateString = getDisplayItemTemplate();
    const documentHack = document.createElement('div');
    documentHack.innerHTML = templateString;
    const newDisplayItem = documentHack.firstChild;

    const mdlElements = newDisplayItem.querySelectorAll(`.needs-mdl-upgrade`);
    mdlElements.forEach((mdlElement) => {
      window.componentHandler.upgradeElement(mdlElement);
    });

    const itemsContainer = document.querySelector('.display-items-container');
    itemsContainer.appendChild(newDisplayItem);
  }

  addShippingOpt() {
    this._shippingId++;
    const templateString = getShippingOptionTemplate();

    const documentHack = document.createElement('div');
    documentHack.innerHTML = templateString;
    const newDisplayItem = documentHack.firstChild;

    const mdlElements = newDisplayItem.querySelectorAll(`.needs-mdl-upgrade`);
    mdlElements.forEach((mdlElement) => {
      window.componentHandler.upgradeElement(mdlElement);
    });

    const itemsContainer = document.querySelector('.shipping-opts-container');
    itemsContainer.appendChild(newDisplayItem);
  }

  buyNowClick() {
    // Supported payment methods
    const supportedPaymentMethods = [];
    const basicCardCheckboxes = document.querySelectorAll(
      '.basic-card-payment-methods input[type=\'checkbox\']');
    basicCardCheckboxes.forEach((basicCardCheckbox) => {
      if (basicCardCheckbox.checked &&
        basicCardCheckbox.dataset.paymentmethod) {
        supportedPaymentMethods.push(basicCardCheckbox.dataset.paymentmethod);
      }
    });

    const displayItemsFromUI = [];
    const displayItemElements =
      document.querySelectorAll('.display-item-wrapper');
    displayItemElements.forEach((displayItemElement) => {
      const labelValue =
        displayItemElement.querySelector('.display-item-label').value;
      const amountValue =
        displayItemElement.querySelector('.display-item-amount').value;
      const currencyValue =
        displayItemElement.querySelector('.display-item-currency').value;

      if (!labelValue || labelValue.length === 0 ||
        !amountValue || amountValue.length === 0) {
        console.warn('Found a display item without a label and / ' +
          'or amount value so excluding it from the results.');
        return;
      }

      displayItemsFromUI.push({
        label: labelValue,
        amount: {
          currency: currencyValue,
          value: amountValue,
        },
      });
    });

    const totalLabelValue =
      document.querySelector('.summary-label').value;
    const totalCurrencyValue =
      document.querySelector('.summary-currency').value;
    const totalAmountValue =
      document.querySelector('.summary-amount').value;

    const totalFromUI = {
      label: totalLabelValue,
      amount: {
        currency: totalCurrencyValue,
        value: totalAmountValue,
      },
    };

    /**
    // Checkout details
    var shipping_options = [];
    $("#shipping-options").children(".shipping-option").each(function(idx) {
      var option_id = $(this).find(".shipping-option-id").val();
      var option_label = $(this).find(".shipping-option-label").val();
      var option_amount = $(this).find(".shipping-option-amount").val();
      var option_selected = $(this).find("button").hasClass("button-primary");
      shipping_options.push({
        id: option_id,
        label: option_label,
        amount: {
          currency: $("#currency").val(), value: option_amount
        },
        selected: option_selected
      })
    });
    var details = {
      shippingOptions: shipping_options,
    };
    var shipping_type = document.getElementById("shipping-type");
    var options = {
      shippingType: shipping_type.options[shipping_type.selectedIndex].value
    };
    $("#options .options-request button.button-primary").each(function(idx) {
      var option_text = $(this).text();
      if (option_text == "Name")
        options.requestPayerName = true;
      if (option_text == "Phone")
        options.requestPayerPhone = true;
      if (option_text == "Email")
        options.requestPayerEmail = true;
      if (option_text == "Shipping")
        options.requestShipping = true;
    });
    **/
    const options = {
      requestPayerName: false,
      requestPayerPhone: false,
      requestPayerEmail: false,
      requestShipping: false,
    };

    if (document.querySelector('#checkbox-buyer-name').checked) {
      options.requestPayerName = true;
    }

    if (document.querySelector('#checkbox-buyer-phone').checked) {
      options.requestPayerPhone = true;
    }

    if (document.querySelector('#checkbox-buyer-email').checked) {
      options.requestPayerEmail = true;
    }

    if (document.querySelector('#checkbox-shipping').checked) {
      options.requestShipping = true;
    }

    // Why is this an array of an object with supportedMethods?
    const supportedInstruments = [{
      supportedMethods: supportedPaymentMethods,
    }];
    const details = {
      displayItems: displayItemsFromUI,
      // Excluding total will result in an error - it's a required field.
      total: totalFromUI,
    };

    const paymentRequest = new PaymentRequest(
      supportedInstruments,
      details,
      options);

    paymentRequest.addEventListener(
      'shippingaddresschange', this.onShippingAddressChange);

    paymentRequest.show()
    .then((result) => {
      // Process the payment
      const data = {};
      data.methodName = result.methodName;
      data.details = result.details;

      // $("#result").text(JSON.stringify(data, null, 2));
      return result.complete('success');
    })
    .catch((err) => {
      console.group(
        'The promise from `paymentRequest.show()` rejected.');
      console.warn('This is normally due to the user closing or cancelling ' +
        'the payment request UI.');
      console.warn(`The error message received was: '${err.message}'`);
      console.error(err);
      console.groupEnd();
    });
  }

  onShippingAddressChange(event) {
  // TODO: This needs a big rewrite to actuall be useful
  // or demonstrate a "relatively" normal use case.

  const paymentRequest = event.target;

  console.log(`New shipping address is: `, paymentRequest.shippingAddress);

  /** const newAddress = paymentRequest.shippingAddress;
  if (newAddress.country === 'US') {
    const shippingOption = {
      id: '',
      label: '',
      amount: {currency: 'USD', value: '0.00'},
      selected: true,
    };

    if (newAddress.region === 'US') {
      shippingOption.id = 'us';
      shippingOption.label = 'Standard shipping in US';
      shippingOption.amount.value = '0.00';
      details.total.amount.value = '55.00';
    } else {
      shippingOption.id = 'others';
      shippingOption.label = 'International shipping';
      shippingOption.amount.value = '10.00';
      details.total.amount.value = '65.00';
    }

    if (details.displayItems.length === 2) {
      details.displayItems.splice(1, 0, shippingOption);
    } else {
      details.displayItems.splice(1, 1, shippingOption);
    }

    details.shippingOptions = [shippingOption];
  } else {
    details.shippingOptions = [];
  }**/

  // This leads to a bug.
  const promise = Promise.resolve({
    total: {
      label: 'Haro',
      amount: {
        currency: 'GBP',
        value: '1',
      },
    },
    shippingOptions: [{
      id: 'us',
      label: 'shipping label',
      selected: true,
      amount: {
        currency: 'USD',
        value: '0.00',
      },
    }],
  });

  event.updateWith(promise);
}
}

window.addEventListener('load', function() {
  if ('PaymentRequest' in window) {
    // Enable the demo
    const demoContainer = document.querySelector('.demo-container');
    demoContainer.classList.remove('is-not-supported');
    new DemoController();
  } else {
    document.querySelector('.supported-warning').classList.remove('hide');
  }
});
<|endoftext|>


<commit_before>define(
    'imcms-profile-editor',
    [
        'imcms-bem-builder', 'imcms-components-builder', 'imcms-i18n-texts', 'imcms-modal-window-builder',
        'imcms-profiles-rest-api', 'imcms-profile-to-row-transformer'
    ],
    function (BEM, components, texts, modal, profileRestApi, profileToRow) {

        texts = texts.superAdmin.profiles;

        let $profileNameRow;
        let $profileDocNameRow;
        let $profileEditButtons;

        function buildProfileNameRow() {
            $profileNameRow = components.texts.textBox('<div>', {
                text: texts.editProfile.name
            });
            $profileNameRow.$input.attr('enable', 'enable');
            return $profileNameRow;
        }

        function buildProfileDocNameRow() {
            $profileDocNameRow = components.texts.textBox('<div>', {
                text: texts.editProfile.docName,
            });
            $profileDocNameRow.$input.attr('enable', 'enable');
            return $profileDocNameRow;
        }

        let errorMsg;

        function buildErrorBlock() {
            errorMsg = components.texts.errorText("<div>", texts.error, {style: 'display: none;'});
            return errorMsg;
        }

        function onCancelChanges($profileRowElement, profile) {

            getOnDiscardChanges(function () {
                onProfileView = onProfileSimpleView;
                currentProfile = profile;
                $profileRow = $profileRowElement;
                prepareProfileView();
            }).call();
        }

        function onEditProfile() {
            onProfileView = onCancelChanges;

            $profileEditButtons.slideDown();

            $profileNameRow.$input.focus();
            $profileDocNameRow.$input.focus();
        }

        function onDeleteProfile() {
            modal.buildModalWindow(texts.warnDelete, function (confirmed) {
                if (!confirmed) return;

                profileRestApi.remove(currentProfile).done(function () {
                    $profileRow.remove();
                    currentProfile = null;
                    onEditDelegate = onSimpleEdit;
                    $container.slideUp();
                })
            });
        }

        function onSaveProfile() {

            let name = $profileNameRow.getValue();
            let docName = $profileDocNameRow.getValue();

            if (!name && !docName) {
                $profileNameRow.$input.focus();
                $profileDocNameRow.$input.focus();
                return;
            }

            let currentProfileToSave = {
                id: currentProfile.id,
                name: name,
                documentName: docName
            };

            if (currentProfileToSave.id) {
                profileRestApi.replace(currentProfileToSave).success(function (savedProfile) {
                    currentProfile.id = savedProfile.id;
                    currentProfile.name = savedProfile.name;
                    currentProfile.documentName = savedProfile.documentName;
                    $profileRow.find('.profile-info-row__profile-name').text(currentProfile.name);
                    $profileRow.find('.profile-info-row__profile-doc-name').text(currentProfile.documentName);
                    onProfileView = onProfileSimpleView;
                    prepareProfileView();
                }).error(function () {
                    errorMsg.css('display', 'inline-block').slideDown();
                });
            } else {
                profileRestApi.create(currentProfileToSave).success(function (profile) {
                    $profileRow = profileToRow.transform((currentProfile = profile), profileEditor);

                    $container.parent().find('.profiles-table').append($profileRow);

                    onProfileView = onProfileSimpleView;
                    prepareProfileView();
                }).error(function () {
                    errorMsg.css('display', 'inline-block').slideDown();
                });
            }
        }

        function getOnDiscardChanges(onConfirm) {
            return function () {
                modal.buildModalWindow(texts.warnChangeMessage, function (confirmed) {
                    if (!confirmed) return;
                    onConfirm.call();
                });
            }
        }

        function getOnWarnCancel(onConfirm) {
            return function () {
                modal.buildModalWindow(texts.warnCancelMessage, function (confirmed) {
                    if (!confirmed) return;
                    onConfirm.call();
                })
            }
        }

        function buildProfileEditButtons() {
            return $profileEditButtons = components.buttons.buttonsContainer('<div>', [
                components.buttons.saveButton({
                    text: texts.createNewProfile.buttonSave,
                    click: onSaveProfile
                }),
                components.buttons.negativeButton({
                    text: texts.cancel,
                    click: getOnWarnCancel(function () {
                        onProfileView = onProfileSimpleView;

                        if (currentProfile.id) {
                            prepareProfileView();
                            $container.slideUp();

                        } else {
                            currentProfile = null;
                            onEditDelegate = onSimpleEdit;
                            $container.slideUp();
                        }
                    })
                })
            ]);
        }

        function prepareProfileView() {
            onEditDelegate = onSimpleEdit;

            $profileRow.parent()
                .find('.profiles-table__profile-row--active')
                .removeClass('profiles-table__profile-row--active');

            $profileRow.addClass('profiles-table__profile-row--active');

            $profileNameRow.$input.attr('enable', 'enable');
            $profileNameRow.setValue(currentProfile.name);

            $profileDocNameRow.$input.attr('enable', 'enable');
            $profileDocNameRow.setValue(currentProfile.documentName);

            $profileEditButtons.slideDown('fast');

            $container.css('display', 'inline-block');
            errorMsg.css('display', 'none').slideUp();
        }

        function onProfileSimpleView($profileRowElement, profile) {
            if (currentProfile && currentProfile.id === profile.id) return;
            currentProfile = profile;
            $profileRow = $profileRowElement;

            prepareProfileView();
        }

        var $container;
        var currentProfile;
        var $profileRow;
        var onProfileView = onProfileSimpleView;

        function buildProfilesContainer() {
            return $container || ($container = new BEM({
                block: 'profiles-editor',
                elements: {
                    'profile-name-row': buildProfileNameRow(),
                    'profile-doc-name-row': buildProfileDocNameRow(),
                    'error-row': buildErrorBlock(),
                    'profile-button-edit': buildProfileEditButtons()
                }
            }).buildBlockStructure('<div>', {style: 'display: none;'}));
        }

        function viewProfile($profileRow, profile) {
            $container.slideDown();
            onProfileView($profileRow, profile);
        }

        var onEditDelegate = onSimpleEdit;

        function onSimpleEdit($profileRow, profile) {
            viewProfile($profileRow, profile);
            onEditProfile();
        }

        function editProfile($profileRow, profile) {
            onEditDelegate($profileRow, profile);
            onEditDelegate = function () {
            }
        }

        var profileEditor = {
            buildProfilesContainer: buildProfilesContainer,
            viewProfile: viewProfile,
            editProfile: editProfile,
            deleteButton: onDeleteProfile
        };

        return profileEditor;
    }
);<commit_msg>IMCMS-336 New design to super admin page: profiles tab - Fixed attribute input<commit_after>define(
    'imcms-profile-editor',
    [
        'imcms-bem-builder', 'imcms-components-builder', 'imcms-i18n-texts', 'imcms-modal-window-builder',
        'imcms-profiles-rest-api', 'imcms-profile-to-row-transformer'
    ],
    function (BEM, components, texts, modal, profileRestApi, profileToRow) {

        texts = texts.superAdmin.profiles;

        let $profileNameRow;
        let $profileDocNameRow;
        let $profileEditButtons;

        function buildProfileNameRow() {
            $profileNameRow = components.texts.textBox('<div>', {
                text: texts.editProfile.name
            });
            $profileNameRow.$input.attr('enabled', 'enabled');
            return $profileNameRow;
        }

        function buildProfileDocNameRow() {
            $profileDocNameRow = components.texts.textBox('<div>', {
                text: texts.editProfile.docName,
            });
            $profileDocNameRow.$input.attr('enabled', 'enabled');
            return $profileDocNameRow;
        }

        let errorMsg;

        function buildErrorBlock() {
            errorMsg = components.texts.errorText("<div>", texts.error, {style: 'display: none;'});
            return errorMsg;
        }

        function onCancelChanges($profileRowElement, profile) {

            getOnDiscardChanges(function () {
                onProfileView = onProfileSimpleView;
                currentProfile = profile;
                $profileRow = $profileRowElement;
                prepareProfileView();
            }).call();
        }

        function onEditProfile() {
            onProfileView = onCancelChanges;

            $profileEditButtons.slideDown();

            $profileNameRow.$input.focus();
            $profileDocNameRow.$input.focus();
        }

        function onDeleteProfile() {
            modal.buildModalWindow(texts.warnDelete, function (confirmed) {
                if (!confirmed) return;

                profileRestApi.remove(currentProfile).done(function () {
                    $profileRow.remove();
                    currentProfile = null;
                    onEditDelegate = onSimpleEdit;
                    $container.slideUp();
                })
            });
        }

        function onSaveProfile() {

            let name = $profileNameRow.getValue();
            let docName = $profileDocNameRow.getValue();

            if (!name && !docName) {
                $profileNameRow.$input.focus();
                $profileDocNameRow.$input.focus();
                return;
            }

            let currentProfileToSave = {
                id: currentProfile.id,
                name: name,
                documentName: docName
            };

            if (currentProfileToSave.id) {
                profileRestApi.replace(currentProfileToSave).success(function (savedProfile) {
                    currentProfile.id = savedProfile.id;
                    currentProfile.name = savedProfile.name;
                    currentProfile.documentName = savedProfile.documentName;
                    $profileRow.find('.profile-info-row__profile-name').text(currentProfile.name);
                    $profileRow.find('.profile-info-row__profile-doc-name').text(currentProfile.documentName);
                    onProfileView = onProfileSimpleView;
                    prepareProfileView();
                }).error(function () {
                    errorMsg.css('display', 'inline-block').slideDown();
                });
            } else {
                profileRestApi.create(currentProfileToSave).success(function (profile) {
                    $profileRow = profileToRow.transform((currentProfile = profile), profileEditor);

                    $container.parent().find('.profiles-table').append($profileRow);

                    onProfileView = onProfileSimpleView;
                    prepareProfileView();
                }).error(function () {
                    errorMsg.css('display', 'inline-block').slideDown();
                });
            }
        }

        function getOnDiscardChanges(onConfirm) {
            return function () {
                modal.buildModalWindow(texts.warnChangeMessage, function (confirmed) {
                    if (!confirmed) return;
                    onConfirm.call();
                });
            }
        }

        function getOnWarnCancel(onConfirm) {
            return function () {
                modal.buildModalWindow(texts.warnCancelMessage, function (confirmed) {
                    if (!confirmed) return;
                    onConfirm.call();
                })
            }
        }

        function buildProfileEditButtons() {
            return $profileEditButtons = components.buttons.buttonsContainer('<div>', [
                components.buttons.saveButton({
                    text: texts.createNewProfile.buttonSave,
                    click: onSaveProfile
                }),
                components.buttons.negativeButton({
                    text: texts.cancel,
                    click: getOnWarnCancel(function () {
                        onProfileView = onProfileSimpleView;

                        if (currentProfile.id) {
                            prepareProfileView();
                            $container.slideUp();

                        } else {
                            currentProfile = null;
                            onEditDelegate = onSimpleEdit;
                            $container.slideUp();
                        }
                    })
                })
            ]);
        }

        function prepareProfileView() {
            onEditDelegate = onSimpleEdit;

            $profileRow.parent()
                .find('.profiles-table__profile-row--active')
                .removeClass('profiles-table__profile-row--active');

            $profileRow.addClass('profiles-table__profile-row--active');

            $profileNameRow.$input.attr('enabled', 'enabled');
            $profileNameRow.setValue(currentProfile.name);

            $profileDocNameRow.$input.attr('enabled', 'enabled');
            $profileDocNameRow.setValue(currentProfile.documentName);

            $profileEditButtons.slideDown('fast');

            $container.css('display', 'inline-block');
            errorMsg.css('display', 'none').slideUp();
        }

        function onProfileSimpleView($profileRowElement, profile) {
            if (currentProfile && currentProfile.id === profile.id) return;
            currentProfile = profile;
            $profileRow = $profileRowElement;

            prepareProfileView();
        }

        var $container;
        var currentProfile;
        var $profileRow;
        var onProfileView = onProfileSimpleView;

        function buildProfilesContainer() {
            return $container || ($container = new BEM({
                block: 'profiles-editor',
                elements: {
                    'profile-name-row': buildProfileNameRow(),
                    'profile-doc-name-row': buildProfileDocNameRow(),
                    'error-row': buildErrorBlock(),
                    'profile-button-edit': buildProfileEditButtons()
                }
            }).buildBlockStructure('<div>', {style: 'display: none;'}));
        }

        function viewProfile($profileRow, profile) {
            $container.slideDown();
            onProfileView($profileRow, profile);
        }

        var onEditDelegate = onSimpleEdit;

        function onSimpleEdit($profileRow, profile) {
            viewProfile($profileRow, profile);
            onEditProfile();
        }

        function editProfile($profileRow, profile) {
            onEditDelegate($profileRow, profile);
            onEditDelegate = function () {
            }
        }

        var profileEditor = {
            buildProfilesContainer: buildProfilesContainer,
            viewProfile: viewProfile,
            editProfile: editProfile,
            deleteButton: onDeleteProfile
        };

        return profileEditor;
    }
);<|endoftext|>